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"]
32 use std::{iter, sync::Arc};
34 use arrayvec::ArrayVec;
35 use base_db::{CrateDisplayName, CrateId, Edition, FileId};
38 adt::{ReprKind, VariantData},
39 expr::{BindingAnnotation, LabelId, Pat, PatId},
40 item_tree::ItemTreeNode,
41 lang_item::LangItemTarget,
43 resolver::{HasResolver, Resolver},
45 AdtId, AssocContainerId, AssocItemId, AssocItemLoc, AttrDefId, ConstId, ConstParamId,
46 DefWithBodyId, EnumId, FunctionId, GenericDefId, HasModule, ImplId, LifetimeParamId,
47 LocalEnumVariantId, LocalFieldId, Lookup, ModuleId, StaticId, StructId, TraitId, TypeAliasId,
50 use hir_expand::{diagnostics::DiagnosticSink, name::name, MacroDefKind};
53 display::{write_bounds_like_dyn_trait_with_prefix, HirDisplayError, HirFormatter},
54 method_resolution, to_assoc_type_id,
55 traits::{FnTrait, Solution, SolutionVariables},
56 AliasTy, BoundVar, CallableDefId, CallableSig, Canonical, DebruijnIndex, GenericPredicate,
57 InEnvironment, Interner, Obligation, ProjectionPredicate, ProjectionTy, Scalar, Substs, Ty,
58 TyDefId, TyKind, TyVariableKind,
60 use rustc_hash::FxHashSet;
61 use stdx::{format_to, impl_from};
63 ast::{self, AttrsOwner, NameOwner},
66 use tt::{Ident, Leaf, Literal, TokenTree};
68 use crate::db::{DefDatabase, HirDatabase};
71 attrs::{HasAttrs, Namespace},
72 has_source::HasSource,
73 semantics::{PathResolution, Semantics, SemanticsScope},
76 // Be careful with these re-exports.
78 // `hir` is the boundary between the compiler and the IDE. It should try hard to
79 // isolate the compiler from the ide, to allow the two to be refactored
80 // independently. Re-exporting something from the compiler is the sure way to
81 // breach the boundary.
83 // Generally, a refactoring which *removes* a name from this list is a good
88 attr::{Attrs, Documentation},
89 body::scope::ExprScopes,
90 find_path::PrefixKind,
93 nameres::ModuleSource,
94 path::{ModPath, PathKind},
95 type_ref::{Mutability, TypeRef},
96 visibility::Visibility,
100 ExpandResult, HirFileId, InFile, MacroCallId, MacroCallLoc, /* FIXME */ MacroDefId,
103 hir_ty::display::HirDisplay,
106 // These are negative re-exports: pub using these names is forbidden, they
107 // should remain private to hir internals.
111 hir_expand::{hygiene::Hygiene, name::AsName},
114 /// hir::Crate describes a single crate. It's the main interface with which
115 /// a crate's dependencies interact. Mostly, it should be just a proxy for the
117 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
119 pub(crate) id: CrateId,
123 pub struct CrateDependency {
129 pub fn dependencies(self, db: &dyn HirDatabase) -> Vec<CrateDependency> {
130 db.crate_graph()[self.id]
134 let krate = Crate { id: dep.crate_id };
135 let name = dep.as_name();
136 CrateDependency { krate, name }
141 // FIXME: add `transitive_reverse_dependencies`.
142 pub fn reverse_dependencies(self, db: &dyn HirDatabase) -> Vec<Crate> {
143 let crate_graph = db.crate_graph();
147 crate_graph[krate].dependencies.iter().any(|it| it.crate_id == self.id)
149 .map(|id| Crate { id })
153 pub fn root_module(self, db: &dyn HirDatabase) -> Module {
154 let def_map = db.crate_def_map(self.id);
155 Module { id: def_map.module_id(def_map.root()) }
158 pub fn root_file(self, db: &dyn HirDatabase) -> FileId {
159 db.crate_graph()[self.id].root_file_id
162 pub fn edition(self, db: &dyn HirDatabase) -> Edition {
163 db.crate_graph()[self.id].edition
166 pub fn display_name(self, db: &dyn HirDatabase) -> Option<CrateDisplayName> {
167 db.crate_graph()[self.id].display_name.clone()
170 pub fn query_external_importables(
172 db: &dyn DefDatabase,
173 query: import_map::Query,
174 ) -> impl Iterator<Item = Either<ModuleDef, MacroDef>> {
175 import_map::search_dependencies(db, self.into(), query).into_iter().map(|item| match item {
176 ItemInNs::Types(mod_id) | ItemInNs::Values(mod_id) => Either::Left(mod_id.into()),
177 ItemInNs::Macros(mac_id) => Either::Right(mac_id.into()),
181 pub fn all(db: &dyn HirDatabase) -> Vec<Crate> {
182 db.crate_graph().iter().map(|id| Crate { id }).collect()
185 /// Try to get the root URL of the documentation of a crate.
186 pub fn get_html_root_url(self: &Crate, db: &dyn HirDatabase) -> Option<String> {
187 // Look for #![doc(html_root_url = "...")]
188 let attrs = db.attrs(AttrDefId::ModuleId(self.root_module(db).into()));
189 let doc_attr_q = attrs.by_key("doc");
191 if !doc_attr_q.exists() {
195 let doc_url = doc_attr_q.tt_values().map(|tt| {
196 let name = tt.token_trees.iter()
197 .skip_while(|tt| !matches!(tt, TokenTree::Leaf(Leaf::Ident(Ident{text: ref ident, ..})) if ident == "html_root_url"))
202 Some(TokenTree::Leaf(Leaf::Literal(Literal{ref text, ..}))) => Some(text),
205 }).flat_map(|t| t).next();
207 doc_url.map(|s| s.trim_matches('"').trim_end_matches('/').to_owned() + "/")
211 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
213 pub(crate) id: ModuleId,
216 /// The defs which can be visible in the module.
217 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
222 // Can't be directly declared, but can be imported.
227 TypeAlias(TypeAlias),
228 BuiltinType(BuiltinType),
233 Adt(Struct, Enum, Union),
243 impl From<VariantDef> for ModuleDef {
244 fn from(var: VariantDef) -> Self {
246 VariantDef::Struct(t) => Adt::from(t).into(),
247 VariantDef::Union(t) => Adt::from(t).into(),
248 VariantDef::Variant(t) => t.into(),
254 pub fn module(self, db: &dyn HirDatabase) -> Option<Module> {
256 ModuleDef::Module(it) => it.parent(db),
257 ModuleDef::Function(it) => Some(it.module(db)),
258 ModuleDef::Adt(it) => Some(it.module(db)),
259 ModuleDef::Variant(it) => Some(it.module(db)),
260 ModuleDef::Const(it) => Some(it.module(db)),
261 ModuleDef::Static(it) => Some(it.module(db)),
262 ModuleDef::Trait(it) => Some(it.module(db)),
263 ModuleDef::TypeAlias(it) => Some(it.module(db)),
264 ModuleDef::BuiltinType(_) => None,
268 pub fn canonical_path(&self, db: &dyn HirDatabase) -> Option<String> {
269 let mut segments = vec![self.name(db)?.to_string()];
270 for m in self.module(db)?.path_to_root(db) {
271 segments.extend(m.name(db).map(|it| it.to_string()))
274 Some(segments.join("::"))
277 pub fn definition_visibility(&self, db: &dyn HirDatabase) -> Option<Visibility> {
278 let module = match self {
279 ModuleDef::Module(it) => it.parent(db)?,
280 ModuleDef::Function(it) => return Some(it.visibility(db)),
281 ModuleDef::Adt(it) => it.module(db),
282 ModuleDef::Variant(it) => {
283 let parent = it.parent_enum(db);
284 let module = it.module(db);
285 return module.visibility_of(db, &ModuleDef::Adt(Adt::Enum(parent)));
287 ModuleDef::Const(it) => return Some(it.visibility(db)),
288 ModuleDef::Static(it) => it.module(db),
289 ModuleDef::Trait(it) => it.module(db),
290 ModuleDef::TypeAlias(it) => return Some(it.visibility(db)),
291 ModuleDef::BuiltinType(_) => return None,
294 module.visibility_of(db, self)
297 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
299 ModuleDef::Adt(it) => Some(it.name(db)),
300 ModuleDef::Trait(it) => Some(it.name(db)),
301 ModuleDef::Function(it) => Some(it.name(db)),
302 ModuleDef::Variant(it) => Some(it.name(db)),
303 ModuleDef::TypeAlias(it) => Some(it.name(db)),
304 ModuleDef::Module(it) => it.name(db),
305 ModuleDef::Const(it) => it.name(db),
306 ModuleDef::Static(it) => it.name(db),
307 ModuleDef::BuiltinType(it) => Some(it.name()),
311 pub fn diagnostics(self, db: &dyn HirDatabase, sink: &mut DiagnosticSink) {
312 let id = match self {
313 ModuleDef::Adt(it) => match it {
314 Adt::Struct(it) => it.id.into(),
315 Adt::Enum(it) => it.id.into(),
316 Adt::Union(it) => it.id.into(),
318 ModuleDef::Trait(it) => it.id.into(),
319 ModuleDef::Function(it) => it.id.into(),
320 ModuleDef::TypeAlias(it) => it.id.into(),
321 ModuleDef::Module(it) => it.id.into(),
322 ModuleDef::Const(it) => it.id.into(),
323 ModuleDef::Static(it) => it.id.into(),
327 let module = match self.module(db) {
332 hir_ty::diagnostics::validate_module_item(db, module.id.krate(), id, sink)
337 /// Name of this module.
338 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
339 let def_map = self.id.def_map(db.upcast());
340 let parent = def_map[self.id.local_id].parent?;
341 def_map[parent].children.iter().find_map(|(name, module_id)| {
342 if *module_id == self.id.local_id {
350 /// Returns the crate this module is part of.
351 pub fn krate(self) -> Crate {
352 Crate { id: self.id.krate() }
355 /// Topmost parent of this module. Every module has a `crate_root`, but some
356 /// might be missing `krate`. This can happen if a module's file is not included
357 /// in the module tree of any target in `Cargo.toml`.
358 pub fn crate_root(self, db: &dyn HirDatabase) -> Module {
359 let def_map = db.crate_def_map(self.id.krate());
360 Module { id: def_map.module_id(def_map.root()) }
363 /// Iterates over all child modules.
364 pub fn children(self, db: &dyn HirDatabase) -> impl Iterator<Item = Module> {
365 let def_map = self.id.def_map(db.upcast());
366 let children = def_map[self.id.local_id]
369 .map(|(_, module_id)| Module { id: def_map.module_id(*module_id) })
370 .collect::<Vec<_>>();
374 /// Finds a parent module.
375 pub fn parent(self, db: &dyn HirDatabase) -> Option<Module> {
376 // FIXME: handle block expressions as modules (their parent is in a different DefMap)
377 let def_map = self.id.def_map(db.upcast());
378 let parent_id = def_map[self.id.local_id].parent?;
379 Some(Module { id: def_map.module_id(parent_id) })
382 pub fn path_to_root(self, db: &dyn HirDatabase) -> Vec<Module> {
383 let mut res = vec![self];
385 while let Some(next) = curr.parent(db) {
392 /// Returns a `ModuleScope`: a set of items, visible in this module.
395 db: &dyn HirDatabase,
396 visible_from: Option<Module>,
397 ) -> Vec<(Name, ScopeDef)> {
398 self.id.def_map(db.upcast())[self.id.local_id]
401 .filter_map(|(name, def)| {
402 if let Some(m) = visible_from {
404 def.filter_visibility(|vis| vis.is_visible_from(db.upcast(), m.id));
405 if filtered.is_none() && !def.is_none() {
408 Some((name, filtered))
414 .flat_map(|(name, def)| {
415 ScopeDef::all_items(def).into_iter().map(move |item| (name.clone(), item))
420 pub fn visibility_of(self, db: &dyn HirDatabase, def: &ModuleDef) -> Option<Visibility> {
421 self.id.def_map(db.upcast())[self.id.local_id].scope.visibility_of(def.clone().into())
424 pub fn diagnostics(self, db: &dyn HirDatabase, sink: &mut DiagnosticSink) {
425 let _p = profile::span("Module::diagnostics").detail(|| {
426 format!("{:?}", self.name(db).map_or("<unknown>".into(), |name| name.to_string()))
428 let def_map = self.id.def_map(db.upcast());
429 def_map.add_diagnostics(db.upcast(), self.id.local_id, sink);
430 for decl in self.declarations(db) {
432 crate::ModuleDef::Function(f) => f.diagnostics(db, sink),
433 crate::ModuleDef::Module(m) => {
434 // Only add diagnostics from inline modules
435 if def_map[m.id.local_id].origin.is_inline() {
436 m.diagnostics(db, sink)
440 decl.diagnostics(db, sink);
445 for impl_def in self.impl_defs(db) {
446 for item in impl_def.items(db) {
447 if let AssocItem::Function(f) = item {
448 f.diagnostics(db, sink);
454 pub fn declarations(self, db: &dyn HirDatabase) -> Vec<ModuleDef> {
455 let def_map = self.id.def_map(db.upcast());
456 def_map[self.id.local_id].scope.declarations().map(ModuleDef::from).collect()
459 pub fn impl_defs(self, db: &dyn HirDatabase) -> Vec<Impl> {
460 let def_map = self.id.def_map(db.upcast());
461 def_map[self.id.local_id].scope.impls().map(Impl::from).collect()
464 /// Finds a path that can be used to refer to the given item from within
465 /// this module, if possible.
466 pub fn find_use_path(self, db: &dyn DefDatabase, item: impl Into<ItemInNs>) -> Option<ModPath> {
467 hir_def::find_path::find_path(db, item.into(), self.into())
470 /// Finds a path that can be used to refer to the given item from within
471 /// this module, if possible. This is used for returning import paths for use-statements.
472 pub fn find_use_path_prefixed(
474 db: &dyn DefDatabase,
475 item: impl Into<ItemInNs>,
476 prefix_kind: PrefixKind,
477 ) -> Option<ModPath> {
478 hir_def::find_path::find_path_prefixed(db, item.into(), self.into(), prefix_kind)
482 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
484 pub(crate) parent: VariantDef,
485 pub(crate) id: LocalFieldId,
488 #[derive(Debug, PartialEq, Eq)]
489 pub enum FieldSource {
490 Named(ast::RecordField),
491 Pos(ast::TupleField),
495 pub fn name(&self, db: &dyn HirDatabase) -> Name {
496 self.parent.variant_data(db).fields()[self.id].name.clone()
499 /// Returns the type as in the signature of the struct (i.e., with
500 /// placeholder types for type parameters). This is good for showing
501 /// signature help, but not so good to actually get the type of the field
502 /// when you actually have a variable of the struct.
503 pub fn signature_ty(&self, db: &dyn HirDatabase) -> Type {
504 let var_id = self.parent.into();
505 let generic_def_id: GenericDefId = match self.parent {
506 VariantDef::Struct(it) => it.id.into(),
507 VariantDef::Union(it) => it.id.into(),
508 VariantDef::Variant(it) => it.parent.id.into(),
510 let substs = Substs::type_params(db, generic_def_id);
511 let ty = db.field_types(var_id)[self.id].clone().subst(&substs);
512 Type::new(db, self.parent.module(db).id.krate(), var_id, ty)
515 pub fn parent_def(&self, _db: &dyn HirDatabase) -> VariantDef {
520 impl HasVisibility for Field {
521 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
522 let variant_data = self.parent.variant_data(db);
523 let visibility = &variant_data.fields()[self.id].visibility;
524 let parent_id: hir_def::VariantId = self.parent.into();
525 visibility.resolve(db.upcast(), &parent_id.resolver(db.upcast()))
529 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
531 pub(crate) id: StructId,
535 pub fn module(self, db: &dyn HirDatabase) -> Module {
536 Module { id: self.id.lookup(db.upcast()).container }
539 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
540 Some(self.module(db).krate())
543 pub fn name(self, db: &dyn HirDatabase) -> Name {
544 db.struct_data(self.id).name.clone()
547 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
548 db.struct_data(self.id)
552 .map(|(id, _)| Field { parent: self.into(), id })
556 pub fn ty(self, db: &dyn HirDatabase) -> Type {
557 Type::from_def(db, self.id.lookup(db.upcast()).container.krate(), self.id)
560 pub fn repr(self, db: &dyn HirDatabase) -> Option<ReprKind> {
561 db.struct_data(self.id).repr.clone()
564 pub fn kind(self, db: &dyn HirDatabase) -> StructKind {
565 self.variant_data(db).kind()
568 fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
569 db.struct_data(self.id).variant_data.clone()
573 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
575 pub(crate) id: UnionId,
579 pub fn name(self, db: &dyn HirDatabase) -> Name {
580 db.union_data(self.id).name.clone()
583 pub fn module(self, db: &dyn HirDatabase) -> Module {
584 Module { id: self.id.lookup(db.upcast()).container }
587 pub fn ty(self, db: &dyn HirDatabase) -> Type {
588 Type::from_def(db, self.id.lookup(db.upcast()).container.krate(), self.id)
591 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
592 db.union_data(self.id)
596 .map(|(id, _)| Field { parent: self.into(), id })
600 fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
601 db.union_data(self.id).variant_data.clone()
605 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
607 pub(crate) id: EnumId,
611 pub fn module(self, db: &dyn HirDatabase) -> Module {
612 Module { id: self.id.lookup(db.upcast()).container }
615 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
616 Some(self.module(db).krate())
619 pub fn name(self, db: &dyn HirDatabase) -> Name {
620 db.enum_data(self.id).name.clone()
623 pub fn variants(self, db: &dyn HirDatabase) -> Vec<Variant> {
624 db.enum_data(self.id).variants.iter().map(|(id, _)| Variant { parent: self, id }).collect()
627 pub fn ty(self, db: &dyn HirDatabase) -> Type {
628 Type::from_def(db, self.id.lookup(db.upcast()).container.krate(), self.id)
632 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
634 pub(crate) parent: Enum,
635 pub(crate) id: LocalEnumVariantId,
639 pub fn module(self, db: &dyn HirDatabase) -> Module {
640 self.parent.module(db)
642 pub fn parent_enum(self, _db: &dyn HirDatabase) -> Enum {
646 pub fn name(self, db: &dyn HirDatabase) -> Name {
647 db.enum_data(self.parent.id).variants[self.id].name.clone()
650 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
651 self.variant_data(db)
654 .map(|(id, _)| Field { parent: self.into(), id })
658 pub fn kind(self, db: &dyn HirDatabase) -> StructKind {
659 self.variant_data(db).kind()
662 pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
663 db.enum_data(self.parent.id).variants[self.id].variant_data.clone()
668 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
674 impl_from!(Struct, Union, Enum for Adt);
677 pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
678 let subst = db.generic_defaults(self.into());
679 subst.iter().any(|ty| ty.value.is_unknown())
682 /// Turns this ADT into a type. Any type parameters of the ADT will be
683 /// turned into unknown types, which is good for e.g. finding the most
684 /// general set of completions, but will not look very nice when printed.
685 pub fn ty(self, db: &dyn HirDatabase) -> Type {
686 let id = AdtId::from(self);
687 Type::from_def(db, id.module(db.upcast()).krate(), id)
690 pub fn module(self, db: &dyn HirDatabase) -> Module {
692 Adt::Struct(s) => s.module(db),
693 Adt::Union(s) => s.module(db),
694 Adt::Enum(e) => e.module(db),
698 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
699 Some(self.module(db).krate())
702 pub fn name(self, db: &dyn HirDatabase) -> Name {
704 Adt::Struct(s) => s.name(db),
705 Adt::Union(u) => u.name(db),
706 Adt::Enum(e) => e.name(db),
711 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
712 pub enum VariantDef {
717 impl_from!(Struct, Union, Variant for VariantDef);
720 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
722 VariantDef::Struct(it) => it.fields(db),
723 VariantDef::Union(it) => it.fields(db),
724 VariantDef::Variant(it) => it.fields(db),
728 pub fn module(self, db: &dyn HirDatabase) -> Module {
730 VariantDef::Struct(it) => it.module(db),
731 VariantDef::Union(it) => it.module(db),
732 VariantDef::Variant(it) => it.module(db),
736 pub fn name(&self, db: &dyn HirDatabase) -> Name {
738 VariantDef::Struct(s) => s.name(db),
739 VariantDef::Union(u) => u.name(db),
740 VariantDef::Variant(e) => e.name(db),
744 pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
746 VariantDef::Struct(it) => it.variant_data(db),
747 VariantDef::Union(it) => it.variant_data(db),
748 VariantDef::Variant(it) => it.variant_data(db),
753 /// The defs which have a body.
754 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
755 pub enum DefWithBody {
760 impl_from!(Function, Const, Static for DefWithBody);
763 pub fn module(self, db: &dyn HirDatabase) -> Module {
765 DefWithBody::Const(c) => c.module(db),
766 DefWithBody::Function(f) => f.module(db),
767 DefWithBody::Static(s) => s.module(db),
771 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
773 DefWithBody::Function(f) => Some(f.name(db)),
774 DefWithBody::Static(s) => s.name(db),
775 DefWithBody::Const(c) => c.name(db),
780 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
781 pub struct Function {
782 pub(crate) id: FunctionId,
786 pub fn module(self, db: &dyn HirDatabase) -> Module {
787 self.id.lookup(db.upcast()).module(db.upcast()).into()
790 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
791 Some(self.module(db).krate())
794 pub fn name(self, db: &dyn HirDatabase) -> Name {
795 db.function_data(self.id).name.clone()
798 /// Get this function's return type
799 pub fn ret_type(self, db: &dyn HirDatabase) -> Type {
800 let resolver = self.id.resolver(db.upcast());
801 let krate = self.id.lookup(db.upcast()).container.module(db.upcast()).krate();
802 let ret_type = &db.function_data(self.id).ret_type;
803 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
804 let ty = ctx.lower_ty(ret_type);
805 Type::new_with_resolver_inner(db, krate, &resolver, ty)
808 pub fn self_param(self, db: &dyn HirDatabase) -> Option<SelfParam> {
809 if !db.function_data(self.id).has_self_param {
812 Some(SelfParam { func: self.id })
815 pub fn assoc_fn_params(self, db: &dyn HirDatabase) -> Vec<Param> {
816 let resolver = self.id.resolver(db.upcast());
817 let krate = self.id.lookup(db.upcast()).container.module(db.upcast()).krate();
818 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
819 let environment = db.trait_environment(self.id.into());
820 db.function_data(self.id)
827 value: ctx.lower_ty(type_ref),
828 environment: environment.clone(),
835 pub fn method_params(self, db: &dyn HirDatabase) -> Option<Vec<Param>> {
836 if self.self_param(db).is_none() {
839 let mut res = self.assoc_fn_params(db);
844 pub fn is_unsafe(self, db: &dyn HirDatabase) -> bool {
845 db.function_data(self.id).is_unsafe
848 pub fn diagnostics(self, db: &dyn HirDatabase, sink: &mut DiagnosticSink) {
849 let krate = self.module(db).id.krate();
850 hir_def::diagnostics::validate_body(db.upcast(), self.id.into(), sink);
851 hir_ty::diagnostics::validate_module_item(db, krate, self.id.into(), sink);
852 hir_ty::diagnostics::validate_body(db, self.id.into(), sink);
855 /// Whether this function declaration has a definition.
857 /// This is false in the case of required (not provided) trait methods.
858 pub fn has_body(self, db: &dyn HirDatabase) -> bool {
859 db.function_data(self.id).has_body
862 /// A textual representation of the HIR of this function for debugging purposes.
863 pub fn debug_hir(self, db: &dyn HirDatabase) -> String {
864 let body = db.body(self.id.into());
866 let mut result = String::new();
867 format_to!(result, "HIR expressions in the body of `{}`:\n", self.name(db));
868 for (id, expr) in body.exprs.iter() {
869 format_to!(result, "{:?}: {:?}\n", id, expr);
876 // Note: logically, this belongs to `hir_ty`, but we are not using it there yet.
883 impl From<hir_ty::Mutability> for Access {
884 fn from(mutability: hir_ty::Mutability) -> Access {
886 hir_ty::Mutability::Not => Access::Shared,
887 hir_ty::Mutability::Mut => Access::Exclusive,
898 pub fn ty(&self) -> &Type {
903 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
904 pub struct SelfParam {
909 pub fn access(self, db: &dyn HirDatabase) -> Access {
910 let func_data = db.function_data(self.func);
914 .map(|param| match *param {
915 TypeRef::Reference(.., mutability) => match mutability {
916 hir_def::type_ref::Mutability::Shared => Access::Shared,
917 hir_def::type_ref::Mutability::Mut => Access::Exclusive,
921 .unwrap_or(Access::Owned)
925 impl HasVisibility for Function {
926 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
927 let function_data = db.function_data(self.id);
928 let visibility = &function_data.visibility;
929 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
933 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
935 pub(crate) id: ConstId,
939 pub fn module(self, db: &dyn HirDatabase) -> Module {
940 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
943 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
944 Some(self.module(db).krate())
947 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
948 db.const_data(self.id).name.clone()
952 impl HasVisibility for Const {
953 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
954 let function_data = db.const_data(self.id);
955 let visibility = &function_data.visibility;
956 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
960 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
962 pub(crate) id: StaticId,
966 pub fn module(self, db: &dyn HirDatabase) -> Module {
967 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
970 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
971 Some(self.module(db).krate())
974 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
975 db.static_data(self.id).name.clone()
978 pub fn is_mut(self, db: &dyn HirDatabase) -> bool {
979 db.static_data(self.id).mutable
983 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
985 pub(crate) id: TraitId,
989 pub fn module(self, db: &dyn HirDatabase) -> Module {
990 Module { id: self.id.lookup(db.upcast()).container }
993 pub fn name(self, db: &dyn HirDatabase) -> Name {
994 db.trait_data(self.id).name.clone()
997 pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
998 db.trait_data(self.id).items.iter().map(|(_name, it)| (*it).into()).collect()
1001 pub fn is_auto(self, db: &dyn HirDatabase) -> bool {
1002 db.trait_data(self.id).auto
1006 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1007 pub struct TypeAlias {
1008 pub(crate) id: TypeAliasId,
1012 pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
1013 let subst = db.generic_defaults(self.id.into());
1014 subst.iter().any(|ty| ty.value.is_unknown())
1017 pub fn module(self, db: &dyn HirDatabase) -> Module {
1018 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
1021 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
1022 Some(self.module(db).krate())
1025 pub fn type_ref(self, db: &dyn HirDatabase) -> Option<TypeRef> {
1026 db.type_alias_data(self.id).type_ref.clone()
1029 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1030 Type::from_def(db, self.id.lookup(db.upcast()).module(db.upcast()).krate(), self.id)
1033 pub fn name(self, db: &dyn HirDatabase) -> Name {
1034 db.type_alias_data(self.id).name.clone()
1038 impl HasVisibility for TypeAlias {
1039 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1040 let function_data = db.type_alias_data(self.id);
1041 let visibility = &function_data.visibility;
1042 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1046 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1047 pub struct BuiltinType {
1048 pub(crate) inner: hir_def::builtin_type::BuiltinType,
1052 pub fn ty(self, db: &dyn HirDatabase, module: Module) -> Type {
1053 let resolver = module.id.resolver(db.upcast());
1054 Type::new_with_resolver(db, &resolver, Ty::builtin(self.inner))
1055 .expect("crate not present in resolver")
1058 pub fn name(self) -> Name {
1059 self.inner.as_name()
1063 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1064 pub struct MacroDef {
1065 pub(crate) id: MacroDefId,
1069 /// FIXME: right now, this just returns the root module of the crate that
1070 /// defines this macro. The reasons for this is that macros are expanded
1071 /// early, in `hir_expand`, where modules simply do not exist yet.
1072 pub fn module(self, db: &dyn HirDatabase) -> Option<Module> {
1073 let krate = self.id.krate;
1074 let def_map = db.crate_def_map(krate);
1075 let module_id = def_map.root();
1076 Some(Module { id: def_map.module_id(module_id) })
1079 /// XXX: this parses the file
1080 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1081 self.source(db)?.value.name().map(|it| it.as_name())
1084 /// Indicate it is a proc-macro
1085 pub fn is_proc_macro(&self) -> bool {
1086 matches!(self.id.kind, MacroDefKind::ProcMacro(_))
1089 /// Indicate it is a derive macro
1090 pub fn is_derive_macro(&self) -> bool {
1091 matches!(self.id.kind, MacroDefKind::ProcMacro(_) | MacroDefKind::BuiltInDerive(_))
1095 /// Invariant: `inner.as_assoc_item(db).is_some()`
1096 /// We do not actively enforce this invariant.
1097 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1098 pub enum AssocItem {
1101 TypeAlias(TypeAlias),
1104 pub enum AssocItemContainer {
1108 pub trait AsAssocItem {
1109 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem>;
1112 impl AsAssocItem for Function {
1113 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1114 as_assoc_item(db, AssocItem::Function, self.id)
1117 impl AsAssocItem for Const {
1118 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1119 as_assoc_item(db, AssocItem::Const, self.id)
1122 impl AsAssocItem for TypeAlias {
1123 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1124 as_assoc_item(db, AssocItem::TypeAlias, self.id)
1127 impl AsAssocItem for ModuleDef {
1128 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1130 ModuleDef::Function(it) => it.as_assoc_item(db),
1131 ModuleDef::Const(it) => it.as_assoc_item(db),
1132 ModuleDef::TypeAlias(it) => it.as_assoc_item(db),
1137 fn as_assoc_item<ID, DEF, CTOR, AST>(db: &dyn HirDatabase, ctor: CTOR, id: ID) -> Option<AssocItem>
1139 ID: Lookup<Data = AssocItemLoc<AST>>,
1141 CTOR: FnOnce(DEF) -> AssocItem,
1144 match id.lookup(db.upcast()).container {
1145 AssocContainerId::TraitId(_) | AssocContainerId::ImplId(_) => Some(ctor(DEF::from(id))),
1146 AssocContainerId::ModuleId(_) => None,
1151 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1153 AssocItem::Function(it) => Some(it.name(db)),
1154 AssocItem::Const(it) => it.name(db),
1155 AssocItem::TypeAlias(it) => Some(it.name(db)),
1158 pub fn module(self, db: &dyn HirDatabase) -> Module {
1160 AssocItem::Function(f) => f.module(db),
1161 AssocItem::Const(c) => c.module(db),
1162 AssocItem::TypeAlias(t) => t.module(db),
1165 pub fn container(self, db: &dyn HirDatabase) -> AssocItemContainer {
1166 let container = match self {
1167 AssocItem::Function(it) => it.id.lookup(db.upcast()).container,
1168 AssocItem::Const(it) => it.id.lookup(db.upcast()).container,
1169 AssocItem::TypeAlias(it) => it.id.lookup(db.upcast()).container,
1172 AssocContainerId::TraitId(id) => AssocItemContainer::Trait(id.into()),
1173 AssocContainerId::ImplId(id) => AssocItemContainer::Impl(id.into()),
1174 AssocContainerId::ModuleId(_) => panic!("invalid AssocItem"),
1178 pub fn containing_trait(self, db: &dyn HirDatabase) -> Option<Trait> {
1179 match self.container(db) {
1180 AssocItemContainer::Trait(t) => Some(t),
1186 impl HasVisibility for AssocItem {
1187 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1189 AssocItem::Function(f) => f.visibility(db),
1190 AssocItem::Const(c) => c.visibility(db),
1191 AssocItem::TypeAlias(t) => t.visibility(db),
1196 #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
1197 pub enum GenericDef {
1201 TypeAlias(TypeAlias),
1203 // enum variants cannot have generics themselves, but their parent enums
1204 // can, and this makes some code easier to write
1206 // consts can have type parameters from their parents (i.e. associated consts of traits)
1211 Adt(Struct, Enum, Union),
1221 pub fn params(self, db: &dyn HirDatabase) -> Vec<GenericParam> {
1222 let generics = db.generic_params(self.into());
1223 let ty_params = generics
1226 .map(|(local_id, _)| TypeParam { id: TypeParamId { parent: self.into(), local_id } })
1227 .map(GenericParam::TypeParam);
1228 let lt_params = generics
1231 .map(|(local_id, _)| LifetimeParam {
1232 id: LifetimeParamId { parent: self.into(), local_id },
1234 .map(GenericParam::LifetimeParam);
1235 let const_params = generics
1238 .map(|(local_id, _)| ConstParam { id: ConstParamId { parent: self.into(), local_id } })
1239 .map(GenericParam::ConstParam);
1240 ty_params.chain(lt_params).chain(const_params).collect()
1243 pub fn type_params(self, db: &dyn HirDatabase) -> Vec<TypeParam> {
1244 let generics = db.generic_params(self.into());
1248 .map(|(local_id, _)| TypeParam { id: TypeParamId { parent: self.into(), local_id } })
1253 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1255 pub(crate) parent: DefWithBodyId,
1256 pub(crate) pat_id: PatId,
1260 pub fn is_param(self, db: &dyn HirDatabase) -> bool {
1261 let src = self.source(db);
1263 Either::Left(bind_pat) => {
1264 bind_pat.syntax().ancestors().any(|it| ast::Param::can_cast(it.kind()))
1266 Either::Right(_self_param) => true,
1270 // FIXME: why is this an option? It shouldn't be?
1271 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1272 let body = db.body(self.parent.into());
1273 match &body[self.pat_id] {
1274 Pat::Bind { name, .. } => Some(name.clone()),
1279 pub fn is_self(self, db: &dyn HirDatabase) -> bool {
1280 self.name(db) == Some(name![self])
1283 pub fn is_mut(self, db: &dyn HirDatabase) -> bool {
1284 let body = db.body(self.parent.into());
1285 matches!(&body[self.pat_id], Pat::Bind { mode: BindingAnnotation::Mutable, .. })
1288 pub fn parent(self, _db: &dyn HirDatabase) -> DefWithBody {
1292 pub fn module(self, db: &dyn HirDatabase) -> Module {
1293 self.parent(db).module(db)
1296 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1297 let def = DefWithBodyId::from(self.parent);
1298 let infer = db.infer(def);
1299 let ty = infer[self.pat_id].clone();
1300 let krate = def.module(db.upcast()).krate();
1301 Type::new(db, krate, def, ty)
1304 pub fn source(self, db: &dyn HirDatabase) -> InFile<Either<ast::IdentPat, ast::SelfParam>> {
1305 let (_body, source_map) = db.body_with_source_map(self.parent.into());
1306 let src = source_map.pat_syntax(self.pat_id).unwrap(); // Hmm...
1307 let root = src.file_syntax(db.upcast());
1309 ast.map_left(|it| it.cast().unwrap().to_node(&root)).map_right(|it| it.to_node(&root))
1314 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1316 pub(crate) parent: DefWithBodyId,
1317 pub(crate) label_id: LabelId,
1321 pub fn module(self, db: &dyn HirDatabase) -> Module {
1322 self.parent(db).module(db)
1325 pub fn parent(self, _db: &dyn HirDatabase) -> DefWithBody {
1329 pub fn name(self, db: &dyn HirDatabase) -> Name {
1330 let body = db.body(self.parent.into());
1331 body[self.label_id].name.clone()
1334 pub fn source(self, db: &dyn HirDatabase) -> InFile<ast::Label> {
1335 let (_body, source_map) = db.body_with_source_map(self.parent.into());
1336 let src = source_map.label_syntax(self.label_id);
1337 let root = src.file_syntax(db.upcast());
1338 src.map(|ast| ast.to_node(&root))
1342 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1343 pub enum GenericParam {
1344 TypeParam(TypeParam),
1345 LifetimeParam(LifetimeParam),
1346 ConstParam(ConstParam),
1348 impl_from!(TypeParam, LifetimeParam, ConstParam for GenericParam);
1351 pub fn module(self, db: &dyn HirDatabase) -> Module {
1353 GenericParam::TypeParam(it) => it.module(db),
1354 GenericParam::LifetimeParam(it) => it.module(db),
1355 GenericParam::ConstParam(it) => it.module(db),
1359 pub fn name(self, db: &dyn HirDatabase) -> Name {
1361 GenericParam::TypeParam(it) => it.name(db),
1362 GenericParam::LifetimeParam(it) => it.name(db),
1363 GenericParam::ConstParam(it) => it.name(db),
1368 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1369 pub struct TypeParam {
1370 pub(crate) id: TypeParamId,
1374 pub fn name(self, db: &dyn HirDatabase) -> Name {
1375 let params = db.generic_params(self.id.parent);
1376 params.types[self.id.local_id].name.clone().unwrap_or_else(Name::missing)
1379 pub fn module(self, db: &dyn HirDatabase) -> Module {
1380 self.id.parent.module(db.upcast()).into()
1383 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1384 let resolver = self.id.parent.resolver(db.upcast());
1385 let krate = self.id.parent.module(db.upcast()).krate();
1386 let ty = TyKind::Placeholder(hir_ty::to_placeholder_idx(db, self.id)).intern(&Interner);
1387 Type::new_with_resolver_inner(db, krate, &resolver, ty)
1390 pub fn trait_bounds(self, db: &dyn HirDatabase) -> Vec<Trait> {
1391 db.generic_predicates_for_param(self.id)
1393 .filter_map(|pred| match &pred.value {
1394 hir_ty::GenericPredicate::Implemented(trait_ref) => {
1395 Some(Trait::from(trait_ref.trait_))
1402 pub fn default(self, db: &dyn HirDatabase) -> Option<Type> {
1403 let params = db.generic_defaults(self.id.parent);
1404 let local_idx = hir_ty::param_idx(db, self.id)?;
1405 let resolver = self.id.parent.resolver(db.upcast());
1406 let krate = self.id.parent.module(db.upcast()).krate();
1407 let ty = params.get(local_idx)?.clone();
1408 let subst = Substs::type_params(db, self.id.parent);
1409 let ty = ty.subst(&subst.prefix(local_idx));
1410 Some(Type::new_with_resolver_inner(db, krate, &resolver, ty))
1414 impl HirDisplay for TypeParam {
1415 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
1416 write!(f, "{}", self.name(f.db))?;
1417 let bounds = f.db.generic_predicates_for_param(self.id);
1418 let substs = Substs::type_params(f.db, self.id.parent);
1419 let predicates = bounds.iter().cloned().map(|b| b.subst(&substs)).collect::<Vec<_>>();
1420 if !(predicates.is_empty() || f.omit_verbose_types()) {
1421 write_bounds_like_dyn_trait_with_prefix(":", &predicates, f)?;
1427 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1428 pub struct LifetimeParam {
1429 pub(crate) id: LifetimeParamId,
1432 impl LifetimeParam {
1433 pub fn name(self, db: &dyn HirDatabase) -> Name {
1434 let params = db.generic_params(self.id.parent);
1435 params.lifetimes[self.id.local_id].name.clone()
1438 pub fn module(self, db: &dyn HirDatabase) -> Module {
1439 self.id.parent.module(db.upcast()).into()
1442 pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef {
1443 self.id.parent.into()
1447 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1448 pub struct ConstParam {
1449 pub(crate) id: ConstParamId,
1453 pub fn name(self, db: &dyn HirDatabase) -> Name {
1454 let params = db.generic_params(self.id.parent);
1455 params.consts[self.id.local_id].name.clone()
1458 pub fn module(self, db: &dyn HirDatabase) -> Module {
1459 self.id.parent.module(db.upcast()).into()
1462 pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef {
1463 self.id.parent.into()
1466 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1467 let def = self.id.parent;
1468 let krate = def.module(db.upcast()).krate();
1469 Type::new(db, krate, def, db.const_param_ty(self.id))
1473 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1475 pub(crate) id: ImplId,
1479 pub fn all_in_crate(db: &dyn HirDatabase, krate: Crate) -> Vec<Impl> {
1480 let inherent = db.inherent_impls_in_crate(krate.id);
1481 let trait_ = db.trait_impls_in_crate(krate.id);
1483 inherent.all_impls().chain(trait_.all_impls()).map(Self::from).collect()
1485 pub fn for_trait(db: &dyn HirDatabase, krate: Crate, trait_: Trait) -> Vec<Impl> {
1486 let impls = db.trait_impls_in_crate(krate.id);
1487 impls.for_trait(trait_.id).map(Self::from).collect()
1490 // FIXME: the return type is wrong. This should be a hir version of
1491 // `TraitRef` (ie, resolved `TypeRef`).
1492 pub fn target_trait(self, db: &dyn HirDatabase) -> Option<TypeRef> {
1493 db.impl_data(self.id).target_trait.clone()
1496 pub fn target_ty(self, db: &dyn HirDatabase) -> Type {
1497 let impl_data = db.impl_data(self.id);
1498 let resolver = self.id.resolver(db.upcast());
1499 let krate = self.id.lookup(db.upcast()).container.krate();
1500 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
1501 let ty = ctx.lower_ty(&impl_data.target_type);
1502 Type::new_with_resolver_inner(db, krate, &resolver, ty)
1505 pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
1506 db.impl_data(self.id).items.iter().map(|it| (*it).into()).collect()
1509 pub fn is_negative(self, db: &dyn HirDatabase) -> bool {
1510 db.impl_data(self.id).is_negative
1513 pub fn module(self, db: &dyn HirDatabase) -> Module {
1514 self.id.lookup(db.upcast()).container.into()
1517 pub fn krate(self, db: &dyn HirDatabase) -> Crate {
1518 Crate { id: self.module(db).id.krate() }
1521 pub fn is_builtin_derive(self, db: &dyn HirDatabase) -> Option<InFile<ast::Attr>> {
1522 let src = self.source(db)?;
1523 let item = src.file_id.is_builtin_derive(db.upcast())?;
1524 let hygenic = hir_expand::hygiene::Hygiene::new(db.upcast(), item.file_id);
1526 // FIXME: handle `cfg_attr`
1531 let path = ModPath::from_src(it.path()?, &hygenic)?;
1532 if path.as_ident()?.to_string() == "derive" {
1540 Some(item.with_value(attr))
1544 #[derive(Clone, PartialEq, Eq, Debug)]
1547 ty: InEnvironment<Ty>,
1551 pub(crate) fn new_with_resolver(
1552 db: &dyn HirDatabase,
1553 resolver: &Resolver,
1556 let krate = resolver.krate()?;
1557 Some(Type::new_with_resolver_inner(db, krate, resolver, ty))
1559 pub(crate) fn new_with_resolver_inner(
1560 db: &dyn HirDatabase,
1562 resolver: &Resolver,
1566 resolver.generic_def().map_or_else(Default::default, |d| db.trait_environment(d));
1567 Type { krate, ty: InEnvironment { value: ty, environment } }
1570 fn new(db: &dyn HirDatabase, krate: CrateId, lexical_env: impl HasResolver, ty: Ty) -> Type {
1571 let resolver = lexical_env.resolver(db.upcast());
1573 resolver.generic_def().map_or_else(Default::default, |d| db.trait_environment(d));
1574 Type { krate, ty: InEnvironment { value: ty, environment } }
1578 db: &dyn HirDatabase,
1580 def: impl HasResolver + Into<TyDefId> + Into<GenericDefId>,
1582 let substs = Substs::build_for_def(db, def).fill_with_unknown().build();
1583 let ty = db.ty(def.into()).subst(&substs);
1584 Type::new(db, krate, def, ty)
1587 pub fn is_unit(&self) -> bool {
1588 matches!(self.ty.value.interned(&Interner), TyKind::Tuple(0, ..))
1590 pub fn is_bool(&self) -> bool {
1591 matches!(self.ty.value.interned(&Interner), TyKind::Scalar(Scalar::Bool))
1594 pub fn is_mutable_reference(&self) -> bool {
1595 matches!(self.ty.value.interned(&Interner), TyKind::Ref(hir_ty::Mutability::Mut, ..))
1598 pub fn remove_ref(&self) -> Option<Type> {
1599 match &self.ty.value.interned(&Interner) {
1600 TyKind::Ref(.., substs) => Some(self.derived(substs[0].clone())),
1605 pub fn is_unknown(&self) -> bool {
1606 self.ty.value.is_unknown()
1609 /// Checks that particular type `ty` implements `std::future::Future`.
1610 /// This function is used in `.await` syntax completion.
1611 pub fn impls_future(&self, db: &dyn HirDatabase) -> bool {
1612 // No special case for the type of async block, since Chalk can figure it out.
1614 let krate = self.krate;
1616 let std_future_trait =
1617 db.lang_item(krate, "future_trait".into()).and_then(|it| it.as_trait());
1618 let std_future_trait = match std_future_trait {
1620 None => return false,
1623 let canonical_ty = Canonical { value: self.ty.value.clone(), kinds: Arc::new([]) };
1624 method_resolution::implements_trait(
1627 self.ty.environment.clone(),
1633 /// Checks that particular type `ty` implements `std::ops::FnOnce`.
1635 /// This function can be used to check if a particular type is callable, since FnOnce is a
1636 /// supertrait of Fn and FnMut, so all callable types implements at least FnOnce.
1637 pub fn impls_fnonce(&self, db: &dyn HirDatabase) -> bool {
1638 let krate = self.krate;
1640 let fnonce_trait = match FnTrait::FnOnce.get_id(db, krate) {
1642 None => return false,
1645 let canonical_ty = Canonical { value: self.ty.value.clone(), kinds: Arc::new([]) };
1646 method_resolution::implements_trait_unique(
1649 self.ty.environment.clone(),
1655 pub fn impls_trait(&self, db: &dyn HirDatabase, trait_: Trait, args: &[Type]) -> bool {
1656 let trait_ref = hir_ty::TraitRef {
1658 substs: Substs::build_for_def(db, trait_.id)
1659 .push(self.ty.value.clone())
1660 .fill(args.iter().map(|t| t.ty.value.clone()))
1664 let goal = Canonical {
1665 value: hir_ty::InEnvironment::new(
1666 self.ty.environment.clone(),
1667 hir_ty::Obligation::Trait(trait_ref),
1669 kinds: Arc::new([]),
1672 db.trait_solve(self.krate, goal).is_some()
1675 pub fn normalize_trait_assoc_type(
1677 db: &dyn HirDatabase,
1682 let subst = Substs::build_for_def(db, trait_.id)
1683 .push(self.ty.value.clone())
1684 .fill(args.iter().map(|t| t.ty.value.clone()))
1686 let predicate = ProjectionPredicate {
1687 projection_ty: ProjectionTy {
1688 associated_ty_id: to_assoc_type_id(alias.id),
1689 substitution: subst,
1691 ty: TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0)).intern(&Interner),
1693 let goal = Canonical {
1694 value: InEnvironment::new(
1695 self.ty.environment.clone(),
1696 Obligation::Projection(predicate),
1698 kinds: Arc::new([TyVariableKind::General]),
1701 match db.trait_solve(self.krate, goal)? {
1702 Solution::Unique(SolutionVariables(subst)) => {
1703 subst.value.first().map(|ty| self.derived(ty.clone()))
1705 Solution::Ambig(_) => None,
1709 pub fn is_copy(&self, db: &dyn HirDatabase) -> bool {
1710 let lang_item = db.lang_item(self.krate, SmolStr::new("copy"));
1711 let copy_trait = match lang_item {
1712 Some(LangItemTarget::TraitId(it)) => it,
1715 self.impls_trait(db, copy_trait.into(), &[])
1718 pub fn as_callable(&self, db: &dyn HirDatabase) -> Option<Callable> {
1719 let def = self.ty.value.callable_def(db);
1721 let sig = self.ty.value.callable_sig(db)?;
1722 Some(Callable { ty: self.clone(), sig, def, is_bound_method: false })
1725 pub fn is_closure(&self) -> bool {
1726 matches!(&self.ty.value.interned(&Interner), TyKind::Closure { .. })
1729 pub fn is_fn(&self) -> bool {
1730 matches!(&self.ty.value.interned(&Interner), TyKind::FnDef(..) | TyKind::Function { .. })
1733 pub fn is_packed(&self, db: &dyn HirDatabase) -> bool {
1734 let adt_id = match self.ty.value.interned(&Interner) {
1735 &TyKind::Adt(hir_ty::AdtId(adt_id), ..) => adt_id,
1739 let adt = adt_id.into();
1741 Adt::Struct(s) => matches!(s.repr(db), Some(ReprKind::Packed)),
1746 pub fn is_raw_ptr(&self) -> bool {
1747 matches!(&self.ty.value.interned(&Interner), TyKind::Raw(..))
1750 pub fn contains_unknown(&self) -> bool {
1751 return go(&self.ty.value);
1753 fn go(ty: &Ty) -> bool {
1754 if ty.is_unknown() {
1757 ty.substs().map_or(false, |substs| substs.iter().any(go))
1762 pub fn fields(&self, db: &dyn HirDatabase) -> Vec<(Field, Type)> {
1763 let (variant_id, substs) = match self.ty.value.interned(&Interner) {
1764 &TyKind::Adt(hir_ty::AdtId(AdtId::StructId(s)), ref substs) => (s.into(), substs),
1765 &TyKind::Adt(hir_ty::AdtId(AdtId::UnionId(u)), ref substs) => (u.into(), substs),
1766 _ => return Vec::new(),
1769 db.field_types(variant_id)
1771 .map(|(local_id, ty)| {
1772 let def = Field { parent: variant_id.into(), id: local_id };
1773 let ty = ty.clone().subst(substs);
1774 (def, self.derived(ty))
1779 pub fn tuple_fields(&self, _db: &dyn HirDatabase) -> Vec<Type> {
1780 if let TyKind::Tuple(_, substs) = &self.ty.value.interned(&Interner) {
1781 substs.iter().map(|ty| self.derived(ty.clone())).collect()
1787 pub fn autoderef<'a>(&'a self, db: &'a dyn HirDatabase) -> impl Iterator<Item = Type> + 'a {
1788 // There should be no inference vars in types passed here
1789 // FIXME check that?
1790 let canonical = Canonical { value: self.ty.value.clone(), kinds: Arc::new([]) };
1791 let environment = self.ty.environment.clone();
1792 let ty = InEnvironment { value: canonical, environment };
1793 autoderef(db, Some(self.krate), ty)
1794 .map(|canonical| canonical.value)
1795 .map(move |ty| self.derived(ty))
1798 // This would be nicer if it just returned an iterator, but that runs into
1799 // lifetime problems, because we need to borrow temp `CrateImplDefs`.
1800 pub fn iterate_assoc_items<T>(
1802 db: &dyn HirDatabase,
1804 mut callback: impl FnMut(AssocItem) -> Option<T>,
1806 for krate in self.ty.value.def_crates(db, krate.id)? {
1807 let impls = db.inherent_impls_in_crate(krate);
1809 for impl_def in impls.for_self_ty(&self.ty.value) {
1810 for &item in db.impl_data(*impl_def).items.iter() {
1811 if let Some(result) = callback(item.into()) {
1812 return Some(result);
1820 pub fn type_parameters(&self) -> impl Iterator<Item = Type> + '_ {
1826 .flat_map(|substs| substs.iter())
1827 .map(move |ty| self.derived(ty.clone()))
1830 pub fn iterate_method_candidates<T>(
1832 db: &dyn HirDatabase,
1834 traits_in_scope: &FxHashSet<TraitId>,
1835 name: Option<&Name>,
1836 mut callback: impl FnMut(&Ty, Function) -> Option<T>,
1838 // There should be no inference vars in types passed here
1839 // FIXME check that?
1840 // FIXME replace Unknown by bound vars here
1841 let canonical = Canonical { value: self.ty.value.clone(), kinds: Arc::new([]) };
1843 let env = self.ty.environment.clone();
1844 let krate = krate.id;
1846 method_resolution::iterate_method_candidates(
1853 method_resolution::LookupMode::MethodCall,
1855 AssocItemId::FunctionId(f) => callback(ty, f.into()),
1861 pub fn iterate_path_candidates<T>(
1863 db: &dyn HirDatabase,
1865 traits_in_scope: &FxHashSet<TraitId>,
1866 name: Option<&Name>,
1867 mut callback: impl FnMut(&Ty, AssocItem) -> Option<T>,
1869 // There should be no inference vars in types passed here
1870 // FIXME check that?
1871 // FIXME replace Unknown by bound vars here
1872 let canonical = Canonical { value: self.ty.value.clone(), kinds: Arc::new([]) };
1874 let env = self.ty.environment.clone();
1875 let krate = krate.id;
1877 method_resolution::iterate_method_candidates(
1884 method_resolution::LookupMode::Path,
1885 |ty, it| callback(ty, it.into()),
1889 pub fn as_adt(&self) -> Option<Adt> {
1890 let (adt, _subst) = self.ty.value.as_adt()?;
1894 pub fn as_dyn_trait(&self) -> Option<Trait> {
1895 self.ty.value.dyn_trait().map(Into::into)
1898 pub fn as_impl_traits(&self, db: &dyn HirDatabase) -> Option<Vec<Trait>> {
1899 self.ty.value.impl_trait_bounds(db).map(|it| {
1901 .filter_map(|pred| match pred {
1902 hir_ty::GenericPredicate::Implemented(trait_ref) => {
1903 Some(Trait::from(trait_ref.trait_))
1911 pub fn as_associated_type_parent_trait(&self, db: &dyn HirDatabase) -> Option<Trait> {
1912 self.ty.value.associated_type_parent_trait(db).map(Into::into)
1915 // FIXME: provide required accessors such that it becomes implementable from outside.
1916 pub fn is_equal_for_find_impls(&self, other: &Type) -> bool {
1917 let rref = other.remove_ref();
1918 self.ty.value.equals_ctor(rref.as_ref().map_or(&other.ty.value, |it| &it.ty.value))
1921 fn derived(&self, ty: Ty) -> Type {
1924 ty: InEnvironment { value: ty, environment: self.ty.environment.clone() },
1928 pub fn walk(&self, db: &dyn HirDatabase, mut cb: impl FnMut(Type)) {
1929 // TypeWalk::walk for a Ty at first visits parameters and only after that the Ty itself.
1930 // We need a different order here.
1933 db: &dyn HirDatabase,
1936 cb: &mut impl FnMut(Type),
1938 for ty in substs.iter() {
1939 walk_type(db, &type_.derived(ty.clone()), cb);
1944 db: &dyn HirDatabase,
1946 bounds: &[GenericPredicate],
1947 cb: &mut impl FnMut(Type),
1949 for pred in bounds {
1951 GenericPredicate::Implemented(trait_ref) => {
1953 walk_substs(db, type_, &trait_ref.substs, cb);
1960 fn walk_type(db: &dyn HirDatabase, type_: &Type, cb: &mut impl FnMut(Type)) {
1961 let ty = type_.ty.value.strip_references();
1962 match ty.interned(&Interner) {
1963 TyKind::Adt(..) => {
1964 cb(type_.derived(ty.clone()));
1966 TyKind::AssociatedType(..) => {
1967 if let Some(_) = ty.associated_type_parent_trait(db) {
1968 cb(type_.derived(ty.clone()));
1971 TyKind::OpaqueType(..) => {
1972 if let Some(bounds) = ty.impl_trait_bounds(db) {
1973 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
1976 TyKind::Alias(AliasTy::Opaque(opaque_ty)) => {
1977 if let Some(bounds) = ty.impl_trait_bounds(db) {
1978 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
1981 walk_substs(db, type_, &opaque_ty.substitution, cb);
1983 TyKind::Placeholder(_) => {
1984 if let Some(bounds) = ty.impl_trait_bounds(db) {
1985 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
1988 TyKind::Dyn(bounds) => {
1989 walk_bounds(db, &type_.derived(ty.clone()), bounds.as_ref(), cb);
1994 if let Some(substs) = ty.substs() {
1995 walk_substs(db, type_, &substs, cb);
1999 walk_type(db, self, &mut cb);
2003 impl HirDisplay for Type {
2004 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
2005 self.ty.value.hir_fmt(f)
2011 pub struct Callable {
2014 def: Option<CallableDefId>,
2015 pub(crate) is_bound_method: bool,
2018 pub enum CallableKind {
2020 TupleStruct(Struct),
2021 TupleEnumVariant(Variant),
2026 pub fn kind(&self) -> CallableKind {
2028 Some(CallableDefId::FunctionId(it)) => CallableKind::Function(it.into()),
2029 Some(CallableDefId::StructId(it)) => CallableKind::TupleStruct(it.into()),
2030 Some(CallableDefId::EnumVariantId(it)) => CallableKind::TupleEnumVariant(it.into()),
2031 None => CallableKind::Closure,
2034 pub fn receiver_param(&self, db: &dyn HirDatabase) -> Option<ast::SelfParam> {
2035 let func = match self.def {
2036 Some(CallableDefId::FunctionId(it)) if self.is_bound_method => it,
2039 let src = func.lookup(db.upcast()).source(db.upcast());
2040 let param_list = src.value.param_list()?;
2041 param_list.self_param()
2043 pub fn n_params(&self) -> usize {
2044 self.sig.params().len() - if self.is_bound_method { 1 } else { 0 }
2048 db: &dyn HirDatabase,
2049 ) -> Vec<(Option<Either<ast::SelfParam, ast::Pat>>, Type)> {
2054 .skip(if self.is_bound_method { 1 } else { 0 })
2055 .map(|ty| self.ty.derived(ty.clone()));
2056 let patterns = match self.def {
2057 Some(CallableDefId::FunctionId(func)) => {
2058 let src = func.lookup(db.upcast()).source(db.upcast());
2059 src.value.param_list().map(|param_list| {
2062 .map(|it| Some(Either::Left(it)))
2063 .filter(|_| !self.is_bound_method)
2065 .chain(param_list.params().map(|it| it.pat().map(Either::Right)))
2070 patterns.into_iter().flatten().chain(iter::repeat(None)).zip(types).collect()
2072 pub fn return_type(&self) -> Type {
2073 self.ty.derived(self.sig.ret().clone())
2078 #[derive(Debug, PartialEq, Eq, Hash)]
2080 ModuleDef(ModuleDef),
2082 GenericParam(GenericParam),
2090 pub fn all_items(def: PerNs) -> ArrayVec<[Self; 3]> {
2091 let mut items = ArrayVec::new();
2093 match (def.take_types(), def.take_values()) {
2094 (Some(m1), None) => items.push(ScopeDef::ModuleDef(m1.into())),
2095 (None, Some(m2)) => items.push(ScopeDef::ModuleDef(m2.into())),
2096 (Some(m1), Some(m2)) => {
2097 // Some items, like unit structs and enum variants, are
2098 // returned as both a type and a value. Here we want
2099 // to de-duplicate them.
2101 items.push(ScopeDef::ModuleDef(m1.into()));
2102 items.push(ScopeDef::ModuleDef(m2.into()));
2104 items.push(ScopeDef::ModuleDef(m1.into()));
2110 if let Some(macro_def_id) = def.take_macros() {
2111 items.push(ScopeDef::MacroDef(macro_def_id.into()));
2114 if items.is_empty() {
2115 items.push(ScopeDef::Unknown);
2122 impl From<ItemInNs> for ScopeDef {
2123 fn from(item: ItemInNs) -> Self {
2125 ItemInNs::Types(id) => ScopeDef::ModuleDef(id.into()),
2126 ItemInNs::Values(id) => ScopeDef::ModuleDef(id.into()),
2127 ItemInNs::Macros(id) => ScopeDef::MacroDef(id.into()),
2132 pub trait HasVisibility {
2133 fn visibility(&self, db: &dyn HirDatabase) -> Visibility;
2134 fn is_visible_from(&self, db: &dyn HirDatabase, module: Module) -> bool {
2135 let vis = self.visibility(db);
2136 vis.is_visible_from(db.upcast(), module.id)