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},
55 traits::{FnTrait, Solution, SolutionVariables},
56 AliasTy, BoundVar, CallableDefId, CallableSig, Canonical, DebruijnIndex, GenericPredicate,
57 InEnvironment, Obligation, ProjectionPredicate, ProjectionTy, Scalar, Substs, TraitEnvironment,
58 Ty, TyDefId, 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::new();
270 segments.push(self.name(db)?.to_string());
271 for m in self.module(db)?.path_to_root(db) {
272 segments.extend(m.name(db).map(|it| it.to_string()))
275 Some(segments.join("::"))
278 pub fn definition_visibility(&self, db: &dyn HirDatabase) -> Option<Visibility> {
279 let module = match self {
280 ModuleDef::Module(it) => it.parent(db)?,
281 ModuleDef::Function(it) => return Some(it.visibility(db)),
282 ModuleDef::Adt(it) => it.module(db),
283 ModuleDef::Variant(it) => {
284 let parent = it.parent_enum(db);
285 let module = it.module(db);
286 return module.visibility_of(db, &ModuleDef::Adt(Adt::Enum(parent)));
288 ModuleDef::Const(it) => return Some(it.visibility(db)),
289 ModuleDef::Static(it) => it.module(db),
290 ModuleDef::Trait(it) => it.module(db),
291 ModuleDef::TypeAlias(it) => return Some(it.visibility(db)),
292 ModuleDef::BuiltinType(_) => return None,
295 module.visibility_of(db, self)
298 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
300 ModuleDef::Adt(it) => Some(it.name(db)),
301 ModuleDef::Trait(it) => Some(it.name(db)),
302 ModuleDef::Function(it) => Some(it.name(db)),
303 ModuleDef::Variant(it) => Some(it.name(db)),
304 ModuleDef::TypeAlias(it) => Some(it.name(db)),
305 ModuleDef::Module(it) => it.name(db),
306 ModuleDef::Const(it) => it.name(db),
307 ModuleDef::Static(it) => it.name(db),
309 ModuleDef::BuiltinType(it) => Some(it.name()),
313 pub fn diagnostics(self, db: &dyn HirDatabase, sink: &mut DiagnosticSink) {
314 let id = match self {
315 ModuleDef::Adt(it) => match it {
316 Adt::Struct(it) => it.id.into(),
317 Adt::Enum(it) => it.id.into(),
318 Adt::Union(it) => it.id.into(),
320 ModuleDef::Trait(it) => it.id.into(),
321 ModuleDef::Function(it) => it.id.into(),
322 ModuleDef::TypeAlias(it) => it.id.into(),
323 ModuleDef::Module(it) => it.id.into(),
324 ModuleDef::Const(it) => it.id.into(),
325 ModuleDef::Static(it) => it.id.into(),
329 let module = match self.module(db) {
334 hir_ty::diagnostics::validate_module_item(db, module.id.krate(), id, sink)
339 /// Name of this module.
340 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
341 let def_map = self.id.def_map(db.upcast());
342 let parent = def_map[self.id.local_id].parent?;
343 def_map[parent].children.iter().find_map(|(name, module_id)| {
344 if *module_id == self.id.local_id {
352 /// Returns the crate this module is part of.
353 pub fn krate(self) -> Crate {
354 Crate { id: self.id.krate() }
357 /// Topmost parent of this module. Every module has a `crate_root`, but some
358 /// might be missing `krate`. This can happen if a module's file is not included
359 /// in the module tree of any target in `Cargo.toml`.
360 pub fn crate_root(self, db: &dyn HirDatabase) -> Module {
361 let def_map = db.crate_def_map(self.id.krate());
362 Module { id: def_map.module_id(def_map.root()) }
365 /// Iterates over all child modules.
366 pub fn children(self, db: &dyn HirDatabase) -> impl Iterator<Item = Module> {
367 let def_map = self.id.def_map(db.upcast());
368 let children = def_map[self.id.local_id]
371 .map(|(_, module_id)| Module { id: def_map.module_id(*module_id) })
372 .collect::<Vec<_>>();
376 /// Finds a parent module.
377 pub fn parent(self, db: &dyn HirDatabase) -> Option<Module> {
378 // FIXME: handle block expressions as modules (their parent is in a different DefMap)
379 let def_map = self.id.def_map(db.upcast());
380 let parent_id = def_map[self.id.local_id].parent?;
381 Some(Module { id: def_map.module_id(parent_id) })
384 pub fn path_to_root(self, db: &dyn HirDatabase) -> Vec<Module> {
385 let mut res = vec![self];
387 while let Some(next) = curr.parent(db) {
394 /// Returns a `ModuleScope`: a set of items, visible in this module.
397 db: &dyn HirDatabase,
398 visible_from: Option<Module>,
399 ) -> Vec<(Name, ScopeDef)> {
400 self.id.def_map(db.upcast())[self.id.local_id]
403 .filter_map(|(name, def)| {
404 if let Some(m) = visible_from {
406 def.filter_visibility(|vis| vis.is_visible_from(db.upcast(), m.id));
407 if filtered.is_none() && !def.is_none() {
410 Some((name, filtered))
416 .flat_map(|(name, def)| {
417 ScopeDef::all_items(def).into_iter().map(move |item| (name.clone(), item))
422 pub fn visibility_of(self, db: &dyn HirDatabase, def: &ModuleDef) -> Option<Visibility> {
423 self.id.def_map(db.upcast())[self.id.local_id].scope.visibility_of(def.clone().into())
426 pub fn diagnostics(self, db: &dyn HirDatabase, sink: &mut DiagnosticSink) {
427 let _p = profile::span("Module::diagnostics").detail(|| {
428 format!("{:?}", self.name(db).map_or("<unknown>".into(), |name| name.to_string()))
430 let def_map = self.id.def_map(db.upcast());
431 def_map.add_diagnostics(db.upcast(), self.id.local_id, sink);
432 for decl in self.declarations(db) {
434 crate::ModuleDef::Function(f) => f.diagnostics(db, sink),
435 crate::ModuleDef::Module(m) => {
436 // Only add diagnostics from inline modules
437 if def_map[m.id.local_id].origin.is_inline() {
438 m.diagnostics(db, sink)
442 decl.diagnostics(db, sink);
447 for impl_def in self.impl_defs(db) {
448 for item in impl_def.items(db) {
449 if let AssocItem::Function(f) = item {
450 f.diagnostics(db, sink);
456 pub fn declarations(self, db: &dyn HirDatabase) -> Vec<ModuleDef> {
457 let def_map = self.id.def_map(db.upcast());
458 def_map[self.id.local_id].scope.declarations().map(ModuleDef::from).collect()
461 pub fn impl_defs(self, db: &dyn HirDatabase) -> Vec<Impl> {
462 let def_map = self.id.def_map(db.upcast());
463 def_map[self.id.local_id].scope.impls().map(Impl::from).collect()
466 /// Finds a path that can be used to refer to the given item from within
467 /// this module, if possible.
468 pub fn find_use_path(self, db: &dyn DefDatabase, item: impl Into<ItemInNs>) -> Option<ModPath> {
469 hir_def::find_path::find_path(db, item.into(), self.into())
472 /// Finds a path that can be used to refer to the given item from within
473 /// this module, if possible. This is used for returning import paths for use-statements.
474 pub fn find_use_path_prefixed(
476 db: &dyn DefDatabase,
477 item: impl Into<ItemInNs>,
478 prefix_kind: PrefixKind,
479 ) -> Option<ModPath> {
480 hir_def::find_path::find_path_prefixed(db, item.into(), self.into(), prefix_kind)
484 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
486 pub(crate) parent: VariantDef,
487 pub(crate) id: LocalFieldId,
490 #[derive(Debug, PartialEq, Eq)]
491 pub enum FieldSource {
492 Named(ast::RecordField),
493 Pos(ast::TupleField),
497 pub fn name(&self, db: &dyn HirDatabase) -> Name {
498 self.parent.variant_data(db).fields()[self.id].name.clone()
501 /// Returns the type as in the signature of the struct (i.e., with
502 /// placeholder types for type parameters). This is good for showing
503 /// signature help, but not so good to actually get the type of the field
504 /// when you actually have a variable of the struct.
505 pub fn signature_ty(&self, db: &dyn HirDatabase) -> Type {
506 let var_id = self.parent.into();
507 let generic_def_id: GenericDefId = match self.parent {
508 VariantDef::Struct(it) => it.id.into(),
509 VariantDef::Union(it) => it.id.into(),
510 VariantDef::Variant(it) => it.parent.id.into(),
512 let substs = Substs::type_params(db, generic_def_id);
513 let ty = db.field_types(var_id)[self.id].clone().subst(&substs);
514 Type::new(db, self.parent.module(db).id.krate(), var_id, ty)
517 pub fn parent_def(&self, _db: &dyn HirDatabase) -> VariantDef {
522 impl HasVisibility for Field {
523 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
524 let variant_data = self.parent.variant_data(db);
525 let visibility = &variant_data.fields()[self.id].visibility;
526 let parent_id: hir_def::VariantId = self.parent.into();
527 visibility.resolve(db.upcast(), &parent_id.resolver(db.upcast()))
531 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
533 pub(crate) id: StructId,
537 pub fn module(self, db: &dyn HirDatabase) -> Module {
538 Module { id: self.id.lookup(db.upcast()).container.module(db.upcast()) }
541 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
542 Some(self.module(db).krate())
545 pub fn name(self, db: &dyn HirDatabase) -> Name {
546 db.struct_data(self.id).name.clone()
549 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
550 db.struct_data(self.id)
554 .map(|(id, _)| Field { parent: self.into(), id })
558 pub fn ty(self, db: &dyn HirDatabase) -> Type {
561 self.id.lookup(db.upcast()).container.module(db.upcast()).krate(),
566 pub fn repr(self, db: &dyn HirDatabase) -> Option<ReprKind> {
567 db.struct_data(self.id).repr.clone()
570 pub fn kind(self, db: &dyn HirDatabase) -> StructKind {
571 self.variant_data(db).kind()
574 fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
575 db.struct_data(self.id).variant_data.clone()
579 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
581 pub(crate) id: UnionId,
585 pub fn name(self, db: &dyn HirDatabase) -> Name {
586 db.union_data(self.id).name.clone()
589 pub fn module(self, db: &dyn HirDatabase) -> Module {
590 Module { id: self.id.lookup(db.upcast()).container.module(db.upcast()) }
593 pub fn ty(self, db: &dyn HirDatabase) -> Type {
596 self.id.lookup(db.upcast()).container.module(db.upcast()).krate(),
601 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
602 db.union_data(self.id)
606 .map(|(id, _)| Field { parent: self.into(), id })
610 fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
611 db.union_data(self.id).variant_data.clone()
615 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
617 pub(crate) id: EnumId,
621 pub fn module(self, db: &dyn HirDatabase) -> Module {
622 Module { id: self.id.lookup(db.upcast()).container.module(db.upcast()) }
625 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
626 Some(self.module(db).krate())
629 pub fn name(self, db: &dyn HirDatabase) -> Name {
630 db.enum_data(self.id).name.clone()
633 pub fn variants(self, db: &dyn HirDatabase) -> Vec<Variant> {
634 db.enum_data(self.id).variants.iter().map(|(id, _)| Variant { parent: self, id }).collect()
637 pub fn ty(self, db: &dyn HirDatabase) -> Type {
640 self.id.lookup(db.upcast()).container.module(db.upcast()).krate(),
646 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
648 pub(crate) parent: Enum,
649 pub(crate) id: LocalEnumVariantId,
653 pub fn module(self, db: &dyn HirDatabase) -> Module {
654 self.parent.module(db)
656 pub fn parent_enum(self, _db: &dyn HirDatabase) -> Enum {
660 pub fn name(self, db: &dyn HirDatabase) -> Name {
661 db.enum_data(self.parent.id).variants[self.id].name.clone()
664 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
665 self.variant_data(db)
668 .map(|(id, _)| Field { parent: self.into(), id })
672 pub fn kind(self, db: &dyn HirDatabase) -> StructKind {
673 self.variant_data(db).kind()
676 pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
677 db.enum_data(self.parent.id).variants[self.id].variant_data.clone()
682 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
688 impl_from!(Struct, Union, Enum for Adt);
691 pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
692 let subst = db.generic_defaults(self.into());
693 subst.iter().any(|ty| &ty.value == &Ty::Unknown)
696 /// Turns this ADT into a type. Any type parameters of the ADT will be
697 /// turned into unknown types, which is good for e.g. finding the most
698 /// general set of completions, but will not look very nice when printed.
699 pub fn ty(self, db: &dyn HirDatabase) -> Type {
700 let id = AdtId::from(self);
701 Type::from_def(db, id.module(db.upcast()).krate(), id)
704 pub fn module(self, db: &dyn HirDatabase) -> Module {
706 Adt::Struct(s) => s.module(db),
707 Adt::Union(s) => s.module(db),
708 Adt::Enum(e) => e.module(db),
712 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
713 Some(self.module(db).krate())
716 pub fn name(self, db: &dyn HirDatabase) -> Name {
718 Adt::Struct(s) => s.name(db),
719 Adt::Union(u) => u.name(db),
720 Adt::Enum(e) => e.name(db),
725 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
726 pub enum VariantDef {
731 impl_from!(Struct, Union, Variant for VariantDef);
734 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
736 VariantDef::Struct(it) => it.fields(db),
737 VariantDef::Union(it) => it.fields(db),
738 VariantDef::Variant(it) => it.fields(db),
742 pub fn module(self, db: &dyn HirDatabase) -> Module {
744 VariantDef::Struct(it) => it.module(db),
745 VariantDef::Union(it) => it.module(db),
746 VariantDef::Variant(it) => it.module(db),
750 pub fn name(&self, db: &dyn HirDatabase) -> Name {
752 VariantDef::Struct(s) => s.name(db),
753 VariantDef::Union(u) => u.name(db),
754 VariantDef::Variant(e) => e.name(db),
758 pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
760 VariantDef::Struct(it) => it.variant_data(db),
761 VariantDef::Union(it) => it.variant_data(db),
762 VariantDef::Variant(it) => it.variant_data(db),
767 /// The defs which have a body.
768 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
769 pub enum DefWithBody {
774 impl_from!(Function, Const, Static for DefWithBody);
777 pub fn module(self, db: &dyn HirDatabase) -> Module {
779 DefWithBody::Const(c) => c.module(db),
780 DefWithBody::Function(f) => f.module(db),
781 DefWithBody::Static(s) => s.module(db),
785 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
787 DefWithBody::Function(f) => Some(f.name(db)),
788 DefWithBody::Static(s) => s.name(db),
789 DefWithBody::Const(c) => c.name(db),
794 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
795 pub struct Function {
796 pub(crate) id: FunctionId,
800 pub fn module(self, db: &dyn HirDatabase) -> Module {
801 self.id.lookup(db.upcast()).module(db.upcast()).into()
804 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
805 Some(self.module(db).krate())
808 pub fn name(self, db: &dyn HirDatabase) -> Name {
809 db.function_data(self.id).name.clone()
812 /// Get this function's return type
813 pub fn ret_type(self, db: &dyn HirDatabase) -> Type {
814 let resolver = self.id.resolver(db.upcast());
815 let krate = self.id.lookup(db.upcast()).container.module(db.upcast()).krate();
816 let ret_type = &db.function_data(self.id).ret_type;
817 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
818 let ty = Ty::from_hir_ext(&ctx, ret_type).0;
819 Type::new_with_resolver_inner(db, krate, &resolver, ty)
822 pub fn self_param(self, db: &dyn HirDatabase) -> Option<SelfParam> {
823 if !db.function_data(self.id).has_self_param {
826 Some(SelfParam { func: self.id })
829 pub fn assoc_fn_params(self, db: &dyn HirDatabase) -> Vec<Param> {
830 let resolver = self.id.resolver(db.upcast());
831 let krate = self.id.lookup(db.upcast()).container.module(db.upcast()).krate();
832 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
833 let environment = TraitEnvironment::lower(db, &resolver);
834 db.function_data(self.id)
841 value: Ty::from_hir_ext(&ctx, type_ref).0,
842 environment: environment.clone(),
849 pub fn method_params(self, db: &dyn HirDatabase) -> Option<Vec<Param>> {
850 if self.self_param(db).is_none() {
853 let mut res = self.assoc_fn_params(db);
858 pub fn is_unsafe(self, db: &dyn HirDatabase) -> bool {
859 db.function_data(self.id).is_unsafe
862 pub fn diagnostics(self, db: &dyn HirDatabase, sink: &mut DiagnosticSink) {
863 let krate = self.module(db).id.krate();
864 hir_def::diagnostics::validate_body(db.upcast(), self.id.into(), sink);
865 hir_ty::diagnostics::validate_module_item(db, krate, self.id.into(), sink);
866 hir_ty::diagnostics::validate_body(db, self.id.into(), sink);
869 /// Whether this function declaration has a definition.
871 /// This is false in the case of required (not provided) trait methods.
872 pub fn has_body(self, db: &dyn HirDatabase) -> bool {
873 db.function_data(self.id).has_body
876 /// A textual representation of the HIR of this function for debugging purposes.
877 pub fn debug_hir(self, db: &dyn HirDatabase) -> String {
878 let body = db.body(self.id.into());
880 let mut result = String::new();
881 format_to!(result, "HIR expressions in the body of `{}`:\n", self.name(db));
882 for (id, expr) in body.exprs.iter() {
883 format_to!(result, "{:?}: {:?}\n", id, expr);
890 // Note: logically, this belongs to `hir_ty`, but we are not using it there yet.
897 impl From<hir_ty::Mutability> for Access {
898 fn from(mutability: hir_ty::Mutability) -> Access {
900 hir_ty::Mutability::Not => Access::Shared,
901 hir_ty::Mutability::Mut => Access::Exclusive,
912 pub fn ty(&self) -> &Type {
917 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
918 pub struct SelfParam {
923 pub fn access(self, db: &dyn HirDatabase) -> Access {
924 let func_data = db.function_data(self.func);
928 .map(|param| match *param {
929 TypeRef::Reference(.., mutability) => match mutability {
930 hir_def::type_ref::Mutability::Shared => Access::Shared,
931 hir_def::type_ref::Mutability::Mut => Access::Exclusive,
935 .unwrap_or(Access::Owned)
939 impl HasVisibility for Function {
940 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
941 let function_data = db.function_data(self.id);
942 let visibility = &function_data.visibility;
943 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
947 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
949 pub(crate) id: ConstId,
953 pub fn module(self, db: &dyn HirDatabase) -> Module {
954 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
957 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
958 Some(self.module(db).krate())
961 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
962 db.const_data(self.id).name.clone()
966 impl HasVisibility for Const {
967 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
968 let function_data = db.const_data(self.id);
969 let visibility = &function_data.visibility;
970 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
974 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
976 pub(crate) id: StaticId,
980 pub fn module(self, db: &dyn HirDatabase) -> Module {
981 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
984 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
985 Some(self.module(db).krate())
988 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
989 db.static_data(self.id).name.clone()
992 pub fn is_mut(self, db: &dyn HirDatabase) -> bool {
993 db.static_data(self.id).mutable
997 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
999 pub(crate) id: TraitId,
1003 pub fn module(self, db: &dyn HirDatabase) -> Module {
1004 Module { id: self.id.lookup(db.upcast()).container.module(db.upcast()) }
1007 pub fn name(self, db: &dyn HirDatabase) -> Name {
1008 db.trait_data(self.id).name.clone()
1011 pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
1012 db.trait_data(self.id).items.iter().map(|(_name, it)| (*it).into()).collect()
1015 pub fn is_auto(self, db: &dyn HirDatabase) -> bool {
1016 db.trait_data(self.id).auto
1020 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1021 pub struct TypeAlias {
1022 pub(crate) id: TypeAliasId,
1026 pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
1027 let subst = db.generic_defaults(self.id.into());
1028 subst.iter().any(|ty| &ty.value == &Ty::Unknown)
1031 pub fn module(self, db: &dyn HirDatabase) -> Module {
1032 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
1035 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
1036 Some(self.module(db).krate())
1039 pub fn type_ref(self, db: &dyn HirDatabase) -> Option<TypeRef> {
1040 db.type_alias_data(self.id).type_ref.clone()
1043 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1044 Type::from_def(db, self.id.lookup(db.upcast()).module(db.upcast()).krate(), self.id)
1047 pub fn name(self, db: &dyn HirDatabase) -> Name {
1048 db.type_alias_data(self.id).name.clone()
1052 impl HasVisibility for TypeAlias {
1053 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1054 let function_data = db.type_alias_data(self.id);
1055 let visibility = &function_data.visibility;
1056 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1060 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1061 pub struct BuiltinType {
1062 pub(crate) inner: hir_def::builtin_type::BuiltinType,
1066 pub fn ty(self, db: &dyn HirDatabase, module: Module) -> Type {
1067 let resolver = module.id.resolver(db.upcast());
1068 Type::new_with_resolver(db, &resolver, Ty::builtin(self.inner))
1069 .expect("crate not present in resolver")
1072 pub fn name(self) -> Name {
1073 self.inner.as_name()
1077 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1078 pub struct MacroDef {
1079 pub(crate) id: MacroDefId,
1083 /// FIXME: right now, this just returns the root module of the crate that
1084 /// defines this macro. The reasons for this is that macros are expanded
1085 /// early, in `hir_expand`, where modules simply do not exist yet.
1086 pub fn module(self, db: &dyn HirDatabase) -> Option<Module> {
1087 let krate = self.id.krate;
1088 let def_map = db.crate_def_map(krate);
1089 let module_id = def_map.root();
1090 Some(Module { id: def_map.module_id(module_id) })
1093 /// XXX: this parses the file
1094 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1095 self.source(db)?.value.name().map(|it| it.as_name())
1098 /// Indicate it is a proc-macro
1099 pub fn is_proc_macro(&self) -> bool {
1100 matches!(self.id.kind, MacroDefKind::ProcMacro(_))
1103 /// Indicate it is a derive macro
1104 pub fn is_derive_macro(&self) -> bool {
1105 matches!(self.id.kind, MacroDefKind::ProcMacro(_) | MacroDefKind::BuiltInDerive(_))
1109 /// Invariant: `inner.as_assoc_item(db).is_some()`
1110 /// We do not actively enforce this invariant.
1111 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1112 pub enum AssocItem {
1115 TypeAlias(TypeAlias),
1118 pub enum AssocItemContainer {
1122 pub trait AsAssocItem {
1123 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem>;
1126 impl AsAssocItem for Function {
1127 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1128 as_assoc_item(db, AssocItem::Function, self.id)
1131 impl AsAssocItem for Const {
1132 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1133 as_assoc_item(db, AssocItem::Const, self.id)
1136 impl AsAssocItem for TypeAlias {
1137 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1138 as_assoc_item(db, AssocItem::TypeAlias, self.id)
1141 impl AsAssocItem for ModuleDef {
1142 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1144 ModuleDef::Function(it) => it.as_assoc_item(db),
1145 ModuleDef::Const(it) => it.as_assoc_item(db),
1146 ModuleDef::TypeAlias(it) => it.as_assoc_item(db),
1151 fn as_assoc_item<ID, DEF, CTOR, AST>(db: &dyn HirDatabase, ctor: CTOR, id: ID) -> Option<AssocItem>
1153 ID: Lookup<Data = AssocItemLoc<AST>>,
1155 CTOR: FnOnce(DEF) -> AssocItem,
1158 match id.lookup(db.upcast()).container {
1159 AssocContainerId::TraitId(_) | AssocContainerId::ImplId(_) => Some(ctor(DEF::from(id))),
1160 AssocContainerId::ContainerId(_) => None,
1165 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1167 AssocItem::Function(it) => Some(it.name(db)),
1168 AssocItem::Const(it) => it.name(db),
1169 AssocItem::TypeAlias(it) => Some(it.name(db)),
1172 pub fn module(self, db: &dyn HirDatabase) -> Module {
1174 AssocItem::Function(f) => f.module(db),
1175 AssocItem::Const(c) => c.module(db),
1176 AssocItem::TypeAlias(t) => t.module(db),
1179 pub fn container(self, db: &dyn HirDatabase) -> AssocItemContainer {
1180 let container = match self {
1181 AssocItem::Function(it) => it.id.lookup(db.upcast()).container,
1182 AssocItem::Const(it) => it.id.lookup(db.upcast()).container,
1183 AssocItem::TypeAlias(it) => it.id.lookup(db.upcast()).container,
1186 AssocContainerId::TraitId(id) => AssocItemContainer::Trait(id.into()),
1187 AssocContainerId::ImplId(id) => AssocItemContainer::Impl(id.into()),
1188 AssocContainerId::ContainerId(_) => panic!("invalid AssocItem"),
1192 pub fn containing_trait(self, db: &dyn HirDatabase) -> Option<Trait> {
1193 match self.container(db) {
1194 AssocItemContainer::Trait(t) => Some(t),
1200 impl HasVisibility for AssocItem {
1201 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1203 AssocItem::Function(f) => f.visibility(db),
1204 AssocItem::Const(c) => c.visibility(db),
1205 AssocItem::TypeAlias(t) => t.visibility(db),
1210 #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
1211 pub enum GenericDef {
1215 TypeAlias(TypeAlias),
1217 // enum variants cannot have generics themselves, but their parent enums
1218 // can, and this makes some code easier to write
1220 // consts can have type parameters from their parents (i.e. associated consts of traits)
1225 Adt(Struct, Enum, Union),
1235 pub fn params(self, db: &dyn HirDatabase) -> Vec<GenericParam> {
1236 let generics = db.generic_params(self.into());
1237 let ty_params = generics
1240 .map(|(local_id, _)| TypeParam { id: TypeParamId { parent: self.into(), local_id } })
1241 .map(GenericParam::TypeParam);
1242 let lt_params = generics
1245 .map(|(local_id, _)| LifetimeParam {
1246 id: LifetimeParamId { parent: self.into(), local_id },
1248 .map(GenericParam::LifetimeParam);
1249 let const_params = generics
1252 .map(|(local_id, _)| ConstParam { id: ConstParamId { parent: self.into(), local_id } })
1253 .map(GenericParam::ConstParam);
1254 ty_params.chain(lt_params).chain(const_params).collect()
1257 pub fn type_params(self, db: &dyn HirDatabase) -> Vec<TypeParam> {
1258 let generics = db.generic_params(self.into());
1262 .map(|(local_id, _)| TypeParam { id: TypeParamId { parent: self.into(), local_id } })
1267 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1269 pub(crate) parent: DefWithBodyId,
1270 pub(crate) pat_id: PatId,
1274 pub fn is_param(self, db: &dyn HirDatabase) -> bool {
1275 let src = self.source(db);
1277 Either::Left(bind_pat) => {
1278 bind_pat.syntax().ancestors().any(|it| ast::Param::can_cast(it.kind()))
1280 Either::Right(_self_param) => true,
1284 // FIXME: why is this an option? It shouldn't be?
1285 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1286 let body = db.body(self.parent.into());
1287 match &body[self.pat_id] {
1288 Pat::Bind { name, .. } => Some(name.clone()),
1293 pub fn is_self(self, db: &dyn HirDatabase) -> bool {
1294 self.name(db) == Some(name![self])
1297 pub fn is_mut(self, db: &dyn HirDatabase) -> bool {
1298 let body = db.body(self.parent.into());
1299 match &body[self.pat_id] {
1300 Pat::Bind { mode, .. } => match mode {
1301 BindingAnnotation::Mutable | BindingAnnotation::RefMut => true,
1308 pub fn parent(self, _db: &dyn HirDatabase) -> DefWithBody {
1312 pub fn module(self, db: &dyn HirDatabase) -> Module {
1313 self.parent(db).module(db)
1316 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1317 let def = DefWithBodyId::from(self.parent);
1318 let infer = db.infer(def);
1319 let ty = infer[self.pat_id].clone();
1320 let krate = def.module(db.upcast()).krate();
1321 Type::new(db, krate, def, ty)
1324 pub fn source(self, db: &dyn HirDatabase) -> InFile<Either<ast::IdentPat, ast::SelfParam>> {
1325 let (_body, source_map) = db.body_with_source_map(self.parent.into());
1326 let src = source_map.pat_syntax(self.pat_id).unwrap(); // Hmm...
1327 let root = src.file_syntax(db.upcast());
1329 ast.map_left(|it| it.cast().unwrap().to_node(&root)).map_right(|it| it.to_node(&root))
1334 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1336 pub(crate) parent: DefWithBodyId,
1337 pub(crate) label_id: LabelId,
1341 pub fn module(self, db: &dyn HirDatabase) -> Module {
1342 self.parent(db).module(db)
1345 pub fn parent(self, _db: &dyn HirDatabase) -> DefWithBody {
1349 pub fn name(self, db: &dyn HirDatabase) -> Name {
1350 let body = db.body(self.parent.into());
1351 body[self.label_id].name.clone()
1354 pub fn source(self, db: &dyn HirDatabase) -> InFile<ast::Label> {
1355 let (_body, source_map) = db.body_with_source_map(self.parent.into());
1356 let src = source_map.label_syntax(self.label_id);
1357 let root = src.file_syntax(db.upcast());
1358 src.map(|ast| ast.to_node(&root))
1362 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1363 pub enum GenericParam {
1364 TypeParam(TypeParam),
1365 LifetimeParam(LifetimeParam),
1366 ConstParam(ConstParam),
1368 impl_from!(TypeParam, LifetimeParam, ConstParam for GenericParam);
1371 pub fn module(self, db: &dyn HirDatabase) -> Module {
1373 GenericParam::TypeParam(it) => it.module(db),
1374 GenericParam::LifetimeParam(it) => it.module(db),
1375 GenericParam::ConstParam(it) => it.module(db),
1379 pub fn name(self, db: &dyn HirDatabase) -> Name {
1381 GenericParam::TypeParam(it) => it.name(db),
1382 GenericParam::LifetimeParam(it) => it.name(db),
1383 GenericParam::ConstParam(it) => it.name(db),
1388 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1389 pub struct TypeParam {
1390 pub(crate) id: TypeParamId,
1394 pub fn name(self, db: &dyn HirDatabase) -> Name {
1395 let params = db.generic_params(self.id.parent);
1396 params.types[self.id.local_id].name.clone().unwrap_or_else(Name::missing)
1399 pub fn module(self, db: &dyn HirDatabase) -> Module {
1400 self.id.parent.module(db.upcast()).into()
1403 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1404 let resolver = self.id.parent.resolver(db.upcast());
1405 let krate = self.id.parent.module(db.upcast()).krate();
1406 let ty = Ty::Placeholder(self.id);
1407 Type::new_with_resolver_inner(db, krate, &resolver, ty)
1410 pub fn trait_bounds(self, db: &dyn HirDatabase) -> Vec<Trait> {
1411 db.generic_predicates_for_param(self.id)
1413 .filter_map(|pred| match &pred.value {
1414 hir_ty::GenericPredicate::Implemented(trait_ref) => {
1415 Some(Trait::from(trait_ref.trait_))
1422 pub fn default(self, db: &dyn HirDatabase) -> Option<Type> {
1423 let params = db.generic_defaults(self.id.parent);
1424 let local_idx = hir_ty::param_idx(db, self.id)?;
1425 let resolver = self.id.parent.resolver(db.upcast());
1426 let krate = self.id.parent.module(db.upcast()).krate();
1427 let ty = params.get(local_idx)?.clone();
1428 let subst = Substs::type_params(db, self.id.parent);
1429 let ty = ty.subst(&subst.prefix(local_idx));
1430 Some(Type::new_with_resolver_inner(db, krate, &resolver, ty))
1434 impl HirDisplay for TypeParam {
1435 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
1436 write!(f, "{}", self.name(f.db))?;
1437 let bounds = f.db.generic_predicates_for_param(self.id);
1438 let substs = Substs::type_params(f.db, self.id.parent);
1439 let predicates = bounds.iter().cloned().map(|b| b.subst(&substs)).collect::<Vec<_>>();
1440 if !(predicates.is_empty() || f.omit_verbose_types()) {
1441 write_bounds_like_dyn_trait_with_prefix(":", &predicates, f)?;
1447 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1448 pub struct LifetimeParam {
1449 pub(crate) id: LifetimeParamId,
1452 impl LifetimeParam {
1453 pub fn name(self, db: &dyn HirDatabase) -> Name {
1454 let params = db.generic_params(self.id.parent);
1455 params.lifetimes[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()
1467 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1468 pub struct ConstParam {
1469 pub(crate) id: ConstParamId,
1473 pub fn name(self, db: &dyn HirDatabase) -> Name {
1474 let params = db.generic_params(self.id.parent);
1475 params.consts[self.id.local_id].name.clone()
1478 pub fn module(self, db: &dyn HirDatabase) -> Module {
1479 self.id.parent.module(db.upcast()).into()
1482 pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef {
1483 self.id.parent.into()
1486 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1487 let def = self.id.parent;
1488 let krate = def.module(db.upcast()).krate();
1489 Type::new(db, krate, def, db.const_param_ty(self.id))
1493 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1495 pub(crate) id: ImplId,
1499 pub fn all_in_crate(db: &dyn HirDatabase, krate: Crate) -> Vec<Impl> {
1500 let inherent = db.inherent_impls_in_crate(krate.id);
1501 let trait_ = db.trait_impls_in_crate(krate.id);
1503 inherent.all_impls().chain(trait_.all_impls()).map(Self::from).collect()
1505 pub fn for_trait(db: &dyn HirDatabase, krate: Crate, trait_: Trait) -> Vec<Impl> {
1506 let impls = db.trait_impls_in_crate(krate.id);
1507 impls.for_trait(trait_.id).map(Self::from).collect()
1510 // FIXME: the return type is wrong. This should be a hir version of
1511 // `TraitRef` (ie, resolved `TypeRef`).
1512 pub fn target_trait(self, db: &dyn HirDatabase) -> Option<TypeRef> {
1513 db.impl_data(self.id).target_trait.clone()
1516 pub fn target_ty(self, db: &dyn HirDatabase) -> Type {
1517 let impl_data = db.impl_data(self.id);
1518 let resolver = self.id.resolver(db.upcast());
1519 let krate = self.id.lookup(db.upcast()).container.module(db.upcast()).krate();
1520 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
1521 let ty = Ty::from_hir(&ctx, &impl_data.target_type);
1522 Type::new_with_resolver_inner(db, krate, &resolver, ty)
1525 pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
1526 db.impl_data(self.id).items.iter().map(|it| (*it).into()).collect()
1529 pub fn is_negative(self, db: &dyn HirDatabase) -> bool {
1530 db.impl_data(self.id).is_negative
1533 pub fn module(self, db: &dyn HirDatabase) -> Module {
1534 self.id.lookup(db.upcast()).container.module(db.upcast()).into()
1537 pub fn krate(self, db: &dyn HirDatabase) -> Crate {
1538 Crate { id: self.module(db).id.krate() }
1541 pub fn is_builtin_derive(self, db: &dyn HirDatabase) -> Option<InFile<ast::Attr>> {
1542 let src = self.source(db)?;
1543 let item = src.file_id.is_builtin_derive(db.upcast())?;
1544 let hygenic = hir_expand::hygiene::Hygiene::new(db.upcast(), item.file_id);
1546 // FIXME: handle `cfg_attr`
1551 let path = ModPath::from_src(it.path()?, &hygenic)?;
1552 if path.as_ident()?.to_string() == "derive" {
1560 Some(item.with_value(attr))
1564 #[derive(Clone, PartialEq, Eq, Debug)]
1567 ty: InEnvironment<Ty>,
1571 pub(crate) fn new_with_resolver(
1572 db: &dyn HirDatabase,
1573 resolver: &Resolver,
1576 let krate = resolver.krate()?;
1577 Some(Type::new_with_resolver_inner(db, krate, resolver, ty))
1579 pub(crate) fn new_with_resolver_inner(
1580 db: &dyn HirDatabase,
1582 resolver: &Resolver,
1585 let environment = TraitEnvironment::lower(db, &resolver);
1586 Type { krate, ty: InEnvironment { value: ty, environment } }
1589 fn new(db: &dyn HirDatabase, krate: CrateId, lexical_env: impl HasResolver, ty: Ty) -> Type {
1590 let resolver = lexical_env.resolver(db.upcast());
1591 let environment = TraitEnvironment::lower(db, &resolver);
1592 Type { krate, ty: InEnvironment { value: ty, environment } }
1596 db: &dyn HirDatabase,
1598 def: impl HasResolver + Into<TyDefId> + Into<GenericDefId>,
1600 let substs = Substs::build_for_def(db, def).fill_with_unknown().build();
1601 let ty = db.ty(def.into()).subst(&substs);
1602 Type::new(db, krate, def, ty)
1605 pub fn is_unit(&self) -> bool {
1606 matches!(self.ty.value, Ty::Tuple(0, ..))
1608 pub fn is_bool(&self) -> bool {
1609 matches!(self.ty.value, Ty::Scalar(Scalar::Bool))
1612 pub fn is_mutable_reference(&self) -> bool {
1613 matches!(self.ty.value, Ty::Ref(hir_ty::Mutability::Mut, ..))
1616 pub fn remove_ref(&self) -> Option<Type> {
1617 match &self.ty.value {
1618 Ty::Ref(.., substs) => Some(self.derived(substs[0].clone())),
1623 pub fn is_unknown(&self) -> bool {
1624 matches!(self.ty.value, Ty::Unknown)
1627 /// Checks that particular type `ty` implements `std::future::Future`.
1628 /// This function is used in `.await` syntax completion.
1629 pub fn impls_future(&self, db: &dyn HirDatabase) -> bool {
1630 // No special case for the type of async block, since Chalk can figure it out.
1632 let krate = self.krate;
1634 let std_future_trait =
1635 db.lang_item(krate, "future_trait".into()).and_then(|it| it.as_trait());
1636 let std_future_trait = match std_future_trait {
1638 None => return false,
1641 let canonical_ty = Canonical { value: self.ty.value.clone(), kinds: Arc::new([]) };
1642 method_resolution::implements_trait(
1645 self.ty.environment.clone(),
1651 /// Checks that particular type `ty` implements `std::ops::FnOnce`.
1653 /// This function can be used to check if a particular type is callable, since FnOnce is a
1654 /// supertrait of Fn and FnMut, so all callable types implements at least FnOnce.
1655 pub fn impls_fnonce(&self, db: &dyn HirDatabase) -> bool {
1656 let krate = self.krate;
1658 let fnonce_trait = match FnTrait::FnOnce.get_id(db, krate) {
1660 None => return false,
1663 let canonical_ty = Canonical { value: self.ty.value.clone(), kinds: Arc::new([]) };
1664 method_resolution::implements_trait_unique(
1667 self.ty.environment.clone(),
1673 pub fn impls_trait(&self, db: &dyn HirDatabase, trait_: Trait, args: &[Type]) -> bool {
1674 let trait_ref = hir_ty::TraitRef {
1676 substs: Substs::build_for_def(db, trait_.id)
1677 .push(self.ty.value.clone())
1678 .fill(args.iter().map(|t| t.ty.value.clone()))
1682 let goal = Canonical {
1683 value: hir_ty::InEnvironment::new(
1684 self.ty.environment.clone(),
1685 hir_ty::Obligation::Trait(trait_ref),
1687 kinds: Arc::new([]),
1690 db.trait_solve(self.krate, goal).is_some()
1693 pub fn normalize_trait_assoc_type(
1695 db: &dyn HirDatabase,
1700 let subst = Substs::build_for_def(db, trait_.id)
1701 .push(self.ty.value.clone())
1702 .fill(args.iter().map(|t| t.ty.value.clone()))
1704 let predicate = ProjectionPredicate {
1705 projection_ty: ProjectionTy { associated_ty: alias.id, parameters: subst },
1706 ty: Ty::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0)),
1708 let goal = Canonical {
1709 value: InEnvironment::new(
1710 self.ty.environment.clone(),
1711 Obligation::Projection(predicate),
1713 kinds: Arc::new([TyVariableKind::General]),
1716 match db.trait_solve(self.krate, goal)? {
1717 Solution::Unique(SolutionVariables(subst)) => {
1718 subst.value.first().map(|ty| self.derived(ty.clone()))
1720 Solution::Ambig(_) => None,
1724 pub fn is_copy(&self, db: &dyn HirDatabase) -> bool {
1725 let lang_item = db.lang_item(self.krate, SmolStr::new("copy"));
1726 let copy_trait = match lang_item {
1727 Some(LangItemTarget::TraitId(it)) => it,
1730 self.impls_trait(db, copy_trait.into(), &[])
1733 pub fn as_callable(&self, db: &dyn HirDatabase) -> Option<Callable> {
1734 let def = match self.ty.value {
1735 Ty::FnDef(def, _) => Some(def),
1739 let sig = self.ty.value.callable_sig(db)?;
1740 Some(Callable { ty: self.clone(), sig, def, is_bound_method: false })
1743 pub fn is_closure(&self) -> bool {
1744 matches!(&self.ty.value, Ty::Closure { .. })
1747 pub fn is_fn(&self) -> bool {
1748 matches!(&self.ty.value, Ty::FnDef(..) | Ty::Function { .. })
1751 pub fn is_packed(&self, db: &dyn HirDatabase) -> bool {
1752 let adt_id = match self.ty.value {
1753 Ty::Adt(hir_ty::AdtId(adt_id), ..) => adt_id,
1757 let adt = adt_id.into();
1759 Adt::Struct(s) => matches!(s.repr(db), Some(ReprKind::Packed)),
1764 pub fn is_raw_ptr(&self) -> bool {
1765 matches!(&self.ty.value, Ty::Raw(..))
1768 pub fn contains_unknown(&self) -> bool {
1769 return go(&self.ty.value);
1771 fn go(ty: &Ty) -> bool {
1773 Ty::Unknown => true,
1774 _ => ty.substs().map_or(false, |substs| substs.iter().any(go)),
1779 pub fn fields(&self, db: &dyn HirDatabase) -> Vec<(Field, Type)> {
1780 let (variant_id, substs) = match self.ty.value {
1781 Ty::Adt(hir_ty::AdtId(AdtId::StructId(s)), ref substs) => (s.into(), substs),
1782 Ty::Adt(hir_ty::AdtId(AdtId::UnionId(u)), ref substs) => (u.into(), substs),
1783 _ => return Vec::new(),
1786 db.field_types(variant_id)
1788 .map(|(local_id, ty)| {
1789 let def = Field { parent: variant_id.into(), id: local_id };
1790 let ty = ty.clone().subst(substs);
1791 (def, self.derived(ty))
1796 pub fn tuple_fields(&self, _db: &dyn HirDatabase) -> Vec<Type> {
1797 if let Ty::Tuple(_, substs) = &self.ty.value {
1798 substs.iter().map(|ty| self.derived(ty.clone())).collect()
1804 pub fn autoderef<'a>(&'a self, db: &'a dyn HirDatabase) -> impl Iterator<Item = Type> + 'a {
1805 // There should be no inference vars in types passed here
1806 // FIXME check that?
1807 let canonical = Canonical { value: self.ty.value.clone(), kinds: Arc::new([]) };
1808 let environment = self.ty.environment.clone();
1809 let ty = InEnvironment { value: canonical, environment };
1810 autoderef(db, Some(self.krate), ty)
1811 .map(|canonical| canonical.value)
1812 .map(move |ty| self.derived(ty))
1815 // This would be nicer if it just returned an iterator, but that runs into
1816 // lifetime problems, because we need to borrow temp `CrateImplDefs`.
1817 pub fn iterate_assoc_items<T>(
1819 db: &dyn HirDatabase,
1821 mut callback: impl FnMut(AssocItem) -> Option<T>,
1823 for krate in self.ty.value.def_crates(db, krate.id)? {
1824 let impls = db.inherent_impls_in_crate(krate);
1826 for impl_def in impls.for_self_ty(&self.ty.value) {
1827 for &item in db.impl_data(*impl_def).items.iter() {
1828 if let Some(result) = callback(item.into()) {
1829 return Some(result);
1837 pub fn type_parameters(&self) -> impl Iterator<Item = Type> + '_ {
1843 .flat_map(|substs| substs.iter())
1844 .map(move |ty| self.derived(ty.clone()))
1847 pub fn iterate_method_candidates<T>(
1849 db: &dyn HirDatabase,
1851 traits_in_scope: &FxHashSet<TraitId>,
1852 name: Option<&Name>,
1853 mut callback: impl FnMut(&Ty, Function) -> Option<T>,
1855 // There should be no inference vars in types passed here
1856 // FIXME check that?
1857 // FIXME replace Unknown by bound vars here
1858 let canonical = Canonical { value: self.ty.value.clone(), kinds: Arc::new([]) };
1860 let env = self.ty.environment.clone();
1861 let krate = krate.id;
1863 method_resolution::iterate_method_candidates(
1870 method_resolution::LookupMode::MethodCall,
1872 AssocItemId::FunctionId(f) => callback(ty, f.into()),
1878 pub fn iterate_path_candidates<T>(
1880 db: &dyn HirDatabase,
1882 traits_in_scope: &FxHashSet<TraitId>,
1883 name: Option<&Name>,
1884 mut callback: impl FnMut(&Ty, AssocItem) -> Option<T>,
1886 // There should be no inference vars in types passed here
1887 // FIXME check that?
1888 // FIXME replace Unknown by bound vars here
1889 let canonical = Canonical { value: self.ty.value.clone(), kinds: Arc::new([]) };
1891 let env = self.ty.environment.clone();
1892 let krate = krate.id;
1894 method_resolution::iterate_method_candidates(
1901 method_resolution::LookupMode::Path,
1902 |ty, it| callback(ty, it.into()),
1906 pub fn as_adt(&self) -> Option<Adt> {
1907 let (adt, _subst) = self.ty.value.as_adt()?;
1911 pub fn as_dyn_trait(&self) -> Option<Trait> {
1912 self.ty.value.dyn_trait().map(Into::into)
1915 pub fn as_impl_traits(&self, db: &dyn HirDatabase) -> Option<Vec<Trait>> {
1916 self.ty.value.impl_trait_bounds(db).map(|it| {
1918 .filter_map(|pred| match pred {
1919 hir_ty::GenericPredicate::Implemented(trait_ref) => {
1920 Some(Trait::from(trait_ref.trait_))
1928 pub fn as_associated_type_parent_trait(&self, db: &dyn HirDatabase) -> Option<Trait> {
1929 self.ty.value.associated_type_parent_trait(db).map(Into::into)
1932 // FIXME: provide required accessors such that it becomes implementable from outside.
1933 pub fn is_equal_for_find_impls(&self, other: &Type) -> bool {
1934 let rref = other.remove_ref();
1935 self.ty.value.equals_ctor(rref.as_ref().map_or(&other.ty.value, |it| &it.ty.value))
1938 fn derived(&self, ty: Ty) -> Type {
1941 ty: InEnvironment { value: ty, environment: self.ty.environment.clone() },
1945 pub fn walk(&self, db: &dyn HirDatabase, mut cb: impl FnMut(Type)) {
1946 // TypeWalk::walk for a Ty at first visits parameters and only after that the Ty itself.
1947 // We need a different order here.
1950 db: &dyn HirDatabase,
1953 cb: &mut impl FnMut(Type),
1955 for ty in substs.iter() {
1956 walk_type(db, &type_.derived(ty.clone()), cb);
1961 db: &dyn HirDatabase,
1963 bounds: &[GenericPredicate],
1964 cb: &mut impl FnMut(Type),
1966 for pred in bounds {
1968 GenericPredicate::Implemented(trait_ref) => {
1970 walk_substs(db, type_, &trait_ref.substs, cb);
1977 fn walk_type(db: &dyn HirDatabase, type_: &Type, cb: &mut impl FnMut(Type)) {
1978 let ty = type_.ty.value.strip_references();
1981 cb(type_.derived(ty.clone()));
1983 Ty::AssociatedType(..) => {
1984 if let Some(_) = ty.associated_type_parent_trait(db) {
1985 cb(type_.derived(ty.clone()));
1988 Ty::OpaqueType(..) => {
1989 if let Some(bounds) = ty.impl_trait_bounds(db) {
1990 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
1993 Ty::Alias(AliasTy::Opaque(opaque_ty)) => {
1994 if let Some(bounds) = ty.impl_trait_bounds(db) {
1995 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
1998 walk_substs(db, type_, &opaque_ty.parameters, cb);
2000 Ty::Placeholder(_) => {
2001 if let Some(bounds) = ty.impl_trait_bounds(db) {
2002 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
2005 Ty::Dyn(bounds) => {
2006 walk_bounds(db, &type_.derived(ty.clone()), bounds.as_ref(), cb);
2011 if let Some(substs) = ty.substs() {
2012 walk_substs(db, type_, &substs, cb);
2016 walk_type(db, self, &mut cb);
2020 impl HirDisplay for Type {
2021 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
2022 self.ty.value.hir_fmt(f)
2028 pub struct Callable {
2031 def: Option<CallableDefId>,
2032 pub(crate) is_bound_method: bool,
2035 pub enum CallableKind {
2037 TupleStruct(Struct),
2038 TupleEnumVariant(Variant),
2043 pub fn kind(&self) -> CallableKind {
2045 Some(CallableDefId::FunctionId(it)) => CallableKind::Function(it.into()),
2046 Some(CallableDefId::StructId(it)) => CallableKind::TupleStruct(it.into()),
2047 Some(CallableDefId::EnumVariantId(it)) => CallableKind::TupleEnumVariant(it.into()),
2048 None => CallableKind::Closure,
2051 pub fn receiver_param(&self, db: &dyn HirDatabase) -> Option<ast::SelfParam> {
2052 let func = match self.def {
2053 Some(CallableDefId::FunctionId(it)) if self.is_bound_method => it,
2056 let src = func.lookup(db.upcast()).source(db.upcast());
2057 let param_list = src.value.param_list()?;
2058 param_list.self_param()
2060 pub fn n_params(&self) -> usize {
2061 self.sig.params().len() - if self.is_bound_method { 1 } else { 0 }
2065 db: &dyn HirDatabase,
2066 ) -> Vec<(Option<Either<ast::SelfParam, ast::Pat>>, Type)> {
2071 .skip(if self.is_bound_method { 1 } else { 0 })
2072 .map(|ty| self.ty.derived(ty.clone()));
2073 let patterns = match self.def {
2074 Some(CallableDefId::FunctionId(func)) => {
2075 let src = func.lookup(db.upcast()).source(db.upcast());
2076 src.value.param_list().map(|param_list| {
2079 .map(|it| Some(Either::Left(it)))
2080 .filter(|_| !self.is_bound_method)
2082 .chain(param_list.params().map(|it| it.pat().map(Either::Right)))
2087 patterns.into_iter().flatten().chain(iter::repeat(None)).zip(types).collect()
2089 pub fn return_type(&self) -> Type {
2090 self.ty.derived(self.sig.ret().clone())
2095 #[derive(Debug, PartialEq, Eq, Hash)]
2097 ModuleDef(ModuleDef),
2099 GenericParam(GenericParam),
2107 pub fn all_items(def: PerNs) -> ArrayVec<[Self; 3]> {
2108 let mut items = ArrayVec::new();
2110 match (def.take_types(), def.take_values()) {
2111 (Some(m1), None) => items.push(ScopeDef::ModuleDef(m1.into())),
2112 (None, Some(m2)) => items.push(ScopeDef::ModuleDef(m2.into())),
2113 (Some(m1), Some(m2)) => {
2114 // Some items, like unit structs and enum variants, are
2115 // returned as both a type and a value. Here we want
2116 // to de-duplicate them.
2118 items.push(ScopeDef::ModuleDef(m1.into()));
2119 items.push(ScopeDef::ModuleDef(m2.into()));
2121 items.push(ScopeDef::ModuleDef(m1.into()));
2127 if let Some(macro_def_id) = def.take_macros() {
2128 items.push(ScopeDef::MacroDef(macro_def_id.into()));
2131 if items.is_empty() {
2132 items.push(ScopeDef::Unknown);
2139 impl From<ItemInNs> for ScopeDef {
2140 fn from(item: ItemInNs) -> Self {
2142 ItemInNs::Types(id) => ScopeDef::ModuleDef(id.into()),
2143 ItemInNs::Values(id) => ScopeDef::ModuleDef(id.into()),
2144 ItemInNs::Macros(id) => ScopeDef::MacroDef(id.into()),
2149 pub trait HasVisibility {
2150 fn visibility(&self, db: &dyn HirDatabase) -> Visibility;
2151 fn is_visible_from(&self, db: &dyn HirDatabase, module: Module) -> bool {
2152 let vis = self.visibility(db);
2153 vis.is_visible_from(db.upcast(), module.id)