1 //! HIR (previously known as descriptors) provides a high-level object oriented
2 //! access to Rust code.
4 //! The principal difference between HIR and syntax trees is that HIR is bound
5 //! to a particular crate instance. That is, it has cfg flags and features
6 //! applied. So, the relation between syntax and HIR is many-to-one.
8 //! HIR is the public API of the all of the compiler logic above syntax trees.
9 //! It is written in "OO" style. Each type is self contained (as in, it knows it's
10 //! parents and full context). It should be "clean code".
12 //! `hir_*` crates are the implementation of the compiler logic.
13 //! They are written in "ECS" style, with relatively little abstractions.
14 //! Many types are not self-contained, and explicitly use local indexes, arenas, etc.
16 //! `hir` is what insulates the "we don't know how to actually write an incremental compiler"
17 //! from the ide with completions, hovers, etc. It is a (soft, internal) boundary:
18 //! https://www.tedinski.com/2018/02/06/system-boundaries.html.
20 #![recursion_limit = "512"]
34 use std::{iter, sync::Arc};
36 use arrayvec::ArrayVec;
37 use base_db::{CrateDisplayName, CrateId, Edition, FileId};
40 adt::{ReprKind, VariantData},
41 expr::{BindingAnnotation, LabelId, Pat, PatId},
42 item_tree::ItemTreeNode,
43 lang_item::LangItemTarget,
45 resolver::{HasResolver, Resolver},
47 AdtId, AssocContainerId, AssocItemId, AssocItemLoc, AttrDefId, ConstId, ConstParamId,
48 DefWithBodyId, EnumId, FunctionId, GenericDefId, HasModule, ImplId, LifetimeParamId,
49 LocalEnumVariantId, LocalFieldId, Lookup, ModuleId, StaticId, StructId, TraitId, TypeAliasId,
52 use hir_expand::{diagnostics::DiagnosticSink, name::name, MacroDefKind};
55 method_resolution::{self, TyFingerprint},
58 traits::{FnTrait, Solution, SolutionVariables},
59 AliasEq, AliasTy, BoundVar, CallableDefId, CallableSig, Canonical, CanonicalVarKinds, Cast,
60 DebruijnIndex, InEnvironment, Interner, ProjectionTy, QuantifiedWhereClause, Scalar,
61 Substitution, TraitEnvironment, Ty, TyDefId, TyKind, TyVariableKind, WhereClause,
63 use itertools::Itertools;
64 use rustc_hash::FxHashSet;
65 use stdx::{format_to, impl_from};
67 ast::{self, AttrsOwner, NameOwner},
70 use tt::{Ident, Leaf, Literal, TokenTree};
72 use crate::db::{DefDatabase, HirDatabase};
75 attrs::{HasAttrs, Namespace},
76 has_source::HasSource,
77 semantics::{PathResolution, Semantics, SemanticsScope},
80 // Be careful with these re-exports.
82 // `hir` is the boundary between the compiler and the IDE. It should try hard to
83 // isolate the compiler from the ide, to allow the two to be refactored
84 // independently. Re-exporting something from the compiler is the sure way to
85 // breach the boundary.
87 // Generally, a refactoring which *removes* a name from this list is a good
92 attr::{Attr, Attrs, AttrsWithOwner, Documentation},
93 body::scope::ExprScopes,
94 find_path::PrefixKind,
97 nameres::ModuleSource,
98 path::{ModPath, PathKind},
99 type_ref::{Mutability, TypeRef},
100 visibility::Visibility,
104 ExpandResult, HirFileId, InFile, MacroCallId, MacroCallLoc, /* FIXME */ MacroDefId,
107 hir_ty::display::HirDisplay,
110 // These are negative re-exports: pub using these names is forbidden, they
111 // should remain private to hir internals.
115 hir_expand::{hygiene::Hygiene, name::AsName},
118 /// hir::Crate describes a single crate. It's the main interface with which
119 /// a crate's dependencies interact. Mostly, it should be just a proxy for the
121 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
123 pub(crate) id: CrateId,
127 pub struct CrateDependency {
133 pub fn dependencies(self, db: &dyn HirDatabase) -> Vec<CrateDependency> {
134 db.crate_graph()[self.id]
138 let krate = Crate { id: dep.crate_id };
139 let name = dep.as_name();
140 CrateDependency { krate, name }
145 pub fn reverse_dependencies(self, db: &dyn HirDatabase) -> Vec<Crate> {
146 let crate_graph = db.crate_graph();
150 crate_graph[krate].dependencies.iter().any(|it| it.crate_id == self.id)
152 .map(|id| Crate { id })
156 pub fn transitive_reverse_dependencies(self, db: &dyn HirDatabase) -> Vec<Crate> {
157 db.crate_graph().transitive_rev_deps(self.id).into_iter().map(|id| Crate { id }).collect()
160 pub fn root_module(self, db: &dyn HirDatabase) -> Module {
161 let def_map = db.crate_def_map(self.id);
162 Module { id: def_map.module_id(def_map.root()) }
165 pub fn root_file(self, db: &dyn HirDatabase) -> FileId {
166 db.crate_graph()[self.id].root_file_id
169 pub fn edition(self, db: &dyn HirDatabase) -> Edition {
170 db.crate_graph()[self.id].edition
173 pub fn display_name(self, db: &dyn HirDatabase) -> Option<CrateDisplayName> {
174 db.crate_graph()[self.id].display_name.clone()
177 pub fn query_external_importables(
179 db: &dyn DefDatabase,
180 query: import_map::Query,
181 ) -> impl Iterator<Item = Either<ModuleDef, MacroDef>> {
182 import_map::search_dependencies(db, self.into(), query).into_iter().map(|item| match item {
183 ItemInNs::Types(mod_id) | ItemInNs::Values(mod_id) => Either::Left(mod_id.into()),
184 ItemInNs::Macros(mac_id) => Either::Right(mac_id.into()),
188 pub fn all(db: &dyn HirDatabase) -> Vec<Crate> {
189 db.crate_graph().iter().map(|id| Crate { id }).collect()
192 /// Try to get the root URL of the documentation of a crate.
193 pub fn get_html_root_url(self: &Crate, db: &dyn HirDatabase) -> Option<String> {
194 // Look for #![doc(html_root_url = "...")]
195 let attrs = db.attrs(AttrDefId::ModuleId(self.root_module(db).into()));
196 let doc_attr_q = attrs.by_key("doc");
198 if !doc_attr_q.exists() {
202 let doc_url = doc_attr_q.tt_values().map(|tt| {
203 let name = tt.token_trees.iter()
204 .skip_while(|tt| !matches!(tt, TokenTree::Leaf(Leaf::Ident(Ident{text: ref ident, ..})) if ident == "html_root_url"))
209 Some(TokenTree::Leaf(Leaf::Literal(Literal{ref text, ..}))) => Some(text),
214 doc_url.map(|s| s.trim_matches('"').trim_end_matches('/').to_owned() + "/")
218 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
220 pub(crate) id: ModuleId,
223 /// The defs which can be visible in the module.
224 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
229 // Can't be directly declared, but can be imported.
234 TypeAlias(TypeAlias),
235 BuiltinType(BuiltinType),
240 Adt(Struct, Enum, Union),
250 impl From<VariantDef> for ModuleDef {
251 fn from(var: VariantDef) -> Self {
253 VariantDef::Struct(t) => Adt::from(t).into(),
254 VariantDef::Union(t) => Adt::from(t).into(),
255 VariantDef::Variant(t) => t.into(),
261 pub fn module(self, db: &dyn HirDatabase) -> Option<Module> {
263 ModuleDef::Module(it) => it.parent(db),
264 ModuleDef::Function(it) => Some(it.module(db)),
265 ModuleDef::Adt(it) => Some(it.module(db)),
266 ModuleDef::Variant(it) => Some(it.module(db)),
267 ModuleDef::Const(it) => Some(it.module(db)),
268 ModuleDef::Static(it) => Some(it.module(db)),
269 ModuleDef::Trait(it) => Some(it.module(db)),
270 ModuleDef::TypeAlias(it) => Some(it.module(db)),
271 ModuleDef::BuiltinType(_) => None,
275 pub fn canonical_path(&self, db: &dyn HirDatabase) -> Option<String> {
276 let mut segments = vec![self.name(db)?.to_string()];
277 for m in self.module(db)?.path_to_root(db) {
278 segments.extend(m.name(db).map(|it| it.to_string()))
281 Some(segments.join("::"))
284 pub fn definition_visibility(&self, db: &dyn HirDatabase) -> Option<Visibility> {
285 let module = match self {
286 ModuleDef::Module(it) => it.parent(db)?,
287 ModuleDef::Function(it) => return Some(it.visibility(db)),
288 ModuleDef::Adt(it) => it.module(db),
289 ModuleDef::Variant(it) => {
290 let parent = it.parent_enum(db);
291 let module = it.module(db);
292 return module.visibility_of(db, &ModuleDef::Adt(Adt::Enum(parent)));
294 ModuleDef::Const(it) => return Some(it.visibility(db)),
295 ModuleDef::Static(it) => it.module(db),
296 ModuleDef::Trait(it) => it.module(db),
297 ModuleDef::TypeAlias(it) => return Some(it.visibility(db)),
298 ModuleDef::BuiltinType(_) => return None,
301 module.visibility_of(db, self)
304 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
306 ModuleDef::Adt(it) => Some(it.name(db)),
307 ModuleDef::Trait(it) => Some(it.name(db)),
308 ModuleDef::Function(it) => Some(it.name(db)),
309 ModuleDef::Variant(it) => Some(it.name(db)),
310 ModuleDef::TypeAlias(it) => Some(it.name(db)),
311 ModuleDef::Module(it) => it.name(db),
312 ModuleDef::Const(it) => it.name(db),
313 ModuleDef::Static(it) => it.name(db),
314 ModuleDef::BuiltinType(it) => Some(it.name()),
318 pub fn diagnostics(self, db: &dyn HirDatabase, sink: &mut DiagnosticSink) {
319 let id = match self {
320 ModuleDef::Adt(it) => match it {
321 Adt::Struct(it) => it.id.into(),
322 Adt::Enum(it) => it.id.into(),
323 Adt::Union(it) => it.id.into(),
325 ModuleDef::Trait(it) => it.id.into(),
326 ModuleDef::Function(it) => it.id.into(),
327 ModuleDef::TypeAlias(it) => it.id.into(),
328 ModuleDef::Module(it) => it.id.into(),
329 ModuleDef::Const(it) => it.id.into(),
330 ModuleDef::Static(it) => it.id.into(),
334 let module = match self.module(db) {
339 hir_ty::diagnostics::validate_module_item(db, module.id.krate(), id, sink)
344 /// Name of this module.
345 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
346 let def_map = self.id.def_map(db.upcast());
347 let parent = def_map[self.id.local_id].parent?;
348 def_map[parent].children.iter().find_map(|(name, module_id)| {
349 if *module_id == self.id.local_id {
357 /// Returns the crate this module is part of.
358 pub fn krate(self) -> Crate {
359 Crate { id: self.id.krate() }
362 /// Topmost parent of this module. Every module has a `crate_root`, but some
363 /// might be missing `krate`. This can happen if a module's file is not included
364 /// in the module tree of any target in `Cargo.toml`.
365 pub fn crate_root(self, db: &dyn HirDatabase) -> Module {
366 let def_map = db.crate_def_map(self.id.krate());
367 Module { id: def_map.module_id(def_map.root()) }
370 /// Iterates over all child modules.
371 pub fn children(self, db: &dyn HirDatabase) -> impl Iterator<Item = Module> {
372 let def_map = self.id.def_map(db.upcast());
373 let children = def_map[self.id.local_id]
376 .map(|(_, module_id)| Module { id: def_map.module_id(*module_id) })
377 .collect::<Vec<_>>();
381 /// Finds a parent module.
382 pub fn parent(self, db: &dyn HirDatabase) -> Option<Module> {
383 // FIXME: handle block expressions as modules (their parent is in a different DefMap)
384 let def_map = self.id.def_map(db.upcast());
385 let parent_id = def_map[self.id.local_id].parent?;
386 Some(Module { id: def_map.module_id(parent_id) })
389 pub fn path_to_root(self, db: &dyn HirDatabase) -> Vec<Module> {
390 let mut res = vec![self];
392 while let Some(next) = curr.parent(db) {
399 /// Returns a `ModuleScope`: a set of items, visible in this module.
402 db: &dyn HirDatabase,
403 visible_from: Option<Module>,
404 ) -> Vec<(Name, ScopeDef)> {
405 self.id.def_map(db.upcast())[self.id.local_id]
408 .filter_map(|(name, def)| {
409 if let Some(m) = visible_from {
411 def.filter_visibility(|vis| vis.is_visible_from(db.upcast(), m.id));
412 if filtered.is_none() && !def.is_none() {
415 Some((name, filtered))
421 .flat_map(|(name, def)| {
422 ScopeDef::all_items(def).into_iter().map(move |item| (name.clone(), item))
427 pub fn visibility_of(self, db: &dyn HirDatabase, def: &ModuleDef) -> Option<Visibility> {
428 self.id.def_map(db.upcast())[self.id.local_id].scope.visibility_of(def.clone().into())
431 pub fn diagnostics(self, db: &dyn HirDatabase, sink: &mut DiagnosticSink) {
432 let _p = profile::span("Module::diagnostics").detail(|| {
433 format!("{:?}", self.name(db).map_or("<unknown>".into(), |name| name.to_string()))
435 let def_map = self.id.def_map(db.upcast());
436 def_map.add_diagnostics(db.upcast(), self.id.local_id, sink);
437 for decl in self.declarations(db) {
439 crate::ModuleDef::Function(f) => f.diagnostics(db, sink),
440 crate::ModuleDef::Module(m) => {
441 // Only add diagnostics from inline modules
442 if def_map[m.id.local_id].origin.is_inline() {
443 m.diagnostics(db, sink)
447 decl.diagnostics(db, sink);
452 for impl_def in self.impl_defs(db) {
453 for item in impl_def.items(db) {
454 if let AssocItem::Function(f) = item {
455 f.diagnostics(db, sink);
461 pub fn declarations(self, db: &dyn HirDatabase) -> Vec<ModuleDef> {
462 let def_map = self.id.def_map(db.upcast());
463 def_map[self.id.local_id].scope.declarations().map(ModuleDef::from).collect()
466 pub fn impl_defs(self, db: &dyn HirDatabase) -> Vec<Impl> {
467 let def_map = self.id.def_map(db.upcast());
468 def_map[self.id.local_id].scope.impls().map(Impl::from).collect()
471 /// Finds a path that can be used to refer to the given item from within
472 /// this module, if possible.
473 pub fn find_use_path(self, db: &dyn DefDatabase, item: impl Into<ItemInNs>) -> Option<ModPath> {
474 hir_def::find_path::find_path(db, item.into(), self.into())
477 /// Finds a path that can be used to refer to the given item from within
478 /// this module, if possible. This is used for returning import paths for use-statements.
479 pub fn find_use_path_prefixed(
481 db: &dyn DefDatabase,
482 item: impl Into<ItemInNs>,
483 prefix_kind: PrefixKind,
484 ) -> Option<ModPath> {
485 hir_def::find_path::find_path_prefixed(db, item.into(), self.into(), prefix_kind)
489 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
491 pub(crate) parent: VariantDef,
492 pub(crate) id: LocalFieldId,
495 #[derive(Debug, PartialEq, Eq)]
496 pub enum FieldSource {
497 Named(ast::RecordField),
498 Pos(ast::TupleField),
502 pub fn name(&self, db: &dyn HirDatabase) -> Name {
503 self.parent.variant_data(db).fields()[self.id].name.clone()
506 /// Returns the type as in the signature of the struct (i.e., with
507 /// placeholder types for type parameters). This is good for showing
508 /// signature help, but not so good to actually get the type of the field
509 /// when you actually have a variable of the struct.
510 pub fn signature_ty(&self, db: &dyn HirDatabase) -> Type {
511 let var_id = self.parent.into();
512 let generic_def_id: GenericDefId = match self.parent {
513 VariantDef::Struct(it) => it.id.into(),
514 VariantDef::Union(it) => it.id.into(),
515 VariantDef::Variant(it) => it.parent.id.into(),
517 let substs = Substitution::type_params(db, generic_def_id);
518 let ty = db.field_types(var_id)[self.id].clone().subst(&substs);
519 Type::new(db, self.parent.module(db).id.krate(), var_id, ty)
522 pub fn parent_def(&self, _db: &dyn HirDatabase) -> VariantDef {
527 impl HasVisibility for Field {
528 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
529 let variant_data = self.parent.variant_data(db);
530 let visibility = &variant_data.fields()[self.id].visibility;
531 let parent_id: hir_def::VariantId = self.parent.into();
532 visibility.resolve(db.upcast(), &parent_id.resolver(db.upcast()))
536 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
538 pub(crate) id: StructId,
542 pub fn module(self, db: &dyn HirDatabase) -> Module {
543 Module { id: self.id.lookup(db.upcast()).container }
546 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
547 Some(self.module(db).krate())
550 pub fn name(self, db: &dyn HirDatabase) -> Name {
551 db.struct_data(self.id).name.clone()
554 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
555 db.struct_data(self.id)
559 .map(|(id, _)| Field { parent: self.into(), id })
563 pub fn ty(self, db: &dyn HirDatabase) -> Type {
564 Type::from_def(db, self.id.lookup(db.upcast()).container.krate(), self.id)
567 pub fn repr(self, db: &dyn HirDatabase) -> Option<ReprKind> {
568 db.struct_data(self.id).repr.clone()
571 pub fn kind(self, db: &dyn HirDatabase) -> StructKind {
572 self.variant_data(db).kind()
575 fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
576 db.struct_data(self.id).variant_data.clone()
580 impl HasVisibility for Struct {
581 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
582 db.struct_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
586 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
588 pub(crate) id: UnionId,
592 pub fn name(self, db: &dyn HirDatabase) -> Name {
593 db.union_data(self.id).name.clone()
596 pub fn module(self, db: &dyn HirDatabase) -> Module {
597 Module { id: self.id.lookup(db.upcast()).container }
600 pub fn ty(self, db: &dyn HirDatabase) -> Type {
601 Type::from_def(db, self.id.lookup(db.upcast()).container.krate(), self.id)
604 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
605 db.union_data(self.id)
609 .map(|(id, _)| Field { parent: self.into(), id })
613 fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
614 db.union_data(self.id).variant_data.clone()
618 impl HasVisibility for Union {
619 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
620 db.union_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
624 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
626 pub(crate) id: EnumId,
630 pub fn module(self, db: &dyn HirDatabase) -> Module {
631 Module { id: self.id.lookup(db.upcast()).container }
634 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
635 Some(self.module(db).krate())
638 pub fn name(self, db: &dyn HirDatabase) -> Name {
639 db.enum_data(self.id).name.clone()
642 pub fn variants(self, db: &dyn HirDatabase) -> Vec<Variant> {
643 db.enum_data(self.id).variants.iter().map(|(id, _)| Variant { parent: self, id }).collect()
646 pub fn ty(self, db: &dyn HirDatabase) -> Type {
647 Type::from_def(db, self.id.lookup(db.upcast()).container.krate(), self.id)
651 impl HasVisibility for Enum {
652 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
653 db.enum_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
657 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
659 pub(crate) parent: Enum,
660 pub(crate) id: LocalEnumVariantId,
664 pub fn module(self, db: &dyn HirDatabase) -> Module {
665 self.parent.module(db)
667 pub fn parent_enum(self, _db: &dyn HirDatabase) -> Enum {
671 pub fn name(self, db: &dyn HirDatabase) -> Name {
672 db.enum_data(self.parent.id).variants[self.id].name.clone()
675 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
676 self.variant_data(db)
679 .map(|(id, _)| Field { parent: self.into(), id })
683 pub fn kind(self, db: &dyn HirDatabase) -> StructKind {
684 self.variant_data(db).kind()
687 pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
688 db.enum_data(self.parent.id).variants[self.id].variant_data.clone()
693 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
699 impl_from!(Struct, Union, Enum for Adt);
702 pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
703 let subst = db.generic_defaults(self.into());
704 subst.iter().any(|ty| ty.value.is_unknown())
707 /// Turns this ADT into a type. Any type parameters of the ADT will be
708 /// turned into unknown types, which is good for e.g. finding the most
709 /// general set of completions, but will not look very nice when printed.
710 pub fn ty(self, db: &dyn HirDatabase) -> Type {
711 let id = AdtId::from(self);
712 Type::from_def(db, id.module(db.upcast()).krate(), id)
715 pub fn module(self, db: &dyn HirDatabase) -> Module {
717 Adt::Struct(s) => s.module(db),
718 Adt::Union(s) => s.module(db),
719 Adt::Enum(e) => e.module(db),
723 pub fn krate(self, db: &dyn HirDatabase) -> Crate {
724 self.module(db).krate()
727 pub fn name(self, db: &dyn HirDatabase) -> Name {
729 Adt::Struct(s) => s.name(db),
730 Adt::Union(u) => u.name(db),
731 Adt::Enum(e) => e.name(db),
736 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
737 pub enum VariantDef {
742 impl_from!(Struct, Union, Variant for VariantDef);
745 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
747 VariantDef::Struct(it) => it.fields(db),
748 VariantDef::Union(it) => it.fields(db),
749 VariantDef::Variant(it) => it.fields(db),
753 pub fn module(self, db: &dyn HirDatabase) -> Module {
755 VariantDef::Struct(it) => it.module(db),
756 VariantDef::Union(it) => it.module(db),
757 VariantDef::Variant(it) => it.module(db),
761 pub fn name(&self, db: &dyn HirDatabase) -> Name {
763 VariantDef::Struct(s) => s.name(db),
764 VariantDef::Union(u) => u.name(db),
765 VariantDef::Variant(e) => e.name(db),
769 pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
771 VariantDef::Struct(it) => it.variant_data(db),
772 VariantDef::Union(it) => it.variant_data(db),
773 VariantDef::Variant(it) => it.variant_data(db),
778 /// The defs which have a body.
779 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
780 pub enum DefWithBody {
785 impl_from!(Function, Const, Static for DefWithBody);
788 pub fn module(self, db: &dyn HirDatabase) -> Module {
790 DefWithBody::Const(c) => c.module(db),
791 DefWithBody::Function(f) => f.module(db),
792 DefWithBody::Static(s) => s.module(db),
796 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
798 DefWithBody::Function(f) => Some(f.name(db)),
799 DefWithBody::Static(s) => s.name(db),
800 DefWithBody::Const(c) => c.name(db),
805 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
806 pub struct Function {
807 pub(crate) id: FunctionId,
811 pub fn module(self, db: &dyn HirDatabase) -> Module {
812 self.id.lookup(db.upcast()).module(db.upcast()).into()
815 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
816 Some(self.module(db).krate())
819 pub fn name(self, db: &dyn HirDatabase) -> Name {
820 db.function_data(self.id).name.clone()
823 /// Get this function's return type
824 pub fn ret_type(self, db: &dyn HirDatabase) -> Type {
825 let resolver = self.id.resolver(db.upcast());
826 let krate = self.id.lookup(db.upcast()).container.module(db.upcast()).krate();
827 let ret_type = &db.function_data(self.id).ret_type;
828 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
829 let ty = ctx.lower_ty(ret_type);
830 Type::new_with_resolver_inner(db, krate, &resolver, ty)
833 pub fn self_param(self, db: &dyn HirDatabase) -> Option<SelfParam> {
834 if !db.function_data(self.id).has_self_param {
837 Some(SelfParam { func: self.id })
840 pub fn assoc_fn_params(self, db: &dyn HirDatabase) -> Vec<Param> {
841 let resolver = self.id.resolver(db.upcast());
842 let krate = self.id.lookup(db.upcast()).container.module(db.upcast()).krate();
843 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
844 let environment = db.trait_environment(self.id.into());
845 db.function_data(self.id)
849 .map(|(idx, type_ref)| {
850 let ty = Type { krate, env: environment.clone(), ty: ctx.lower_ty(type_ref) };
851 Param { func: self, ty, idx }
855 pub fn method_params(self, db: &dyn HirDatabase) -> Option<Vec<Param>> {
856 if self.self_param(db).is_none() {
859 let mut res = self.assoc_fn_params(db);
864 pub fn is_unsafe(self, db: &dyn HirDatabase) -> bool {
865 db.function_data(self.id).qualifier.is_unsafe
868 pub fn diagnostics(self, db: &dyn HirDatabase, sink: &mut DiagnosticSink) {
869 let krate = self.module(db).id.krate();
870 hir_def::diagnostics::validate_body(db.upcast(), self.id.into(), sink);
871 hir_ty::diagnostics::validate_module_item(db, krate, self.id.into(), sink);
872 hir_ty::diagnostics::validate_body(db, self.id.into(), sink);
875 /// Whether this function declaration has a definition.
877 /// This is false in the case of required (not provided) trait methods.
878 pub fn has_body(self, db: &dyn HirDatabase) -> bool {
879 db.function_data(self.id).has_body
882 /// A textual representation of the HIR of this function for debugging purposes.
883 pub fn debug_hir(self, db: &dyn HirDatabase) -> String {
884 let body = db.body(self.id.into());
886 let mut result = String::new();
887 format_to!(result, "HIR expressions in the body of `{}`:\n", self.name(db));
888 for (id, expr) in body.exprs.iter() {
889 format_to!(result, "{:?}: {:?}\n", id, expr);
896 // Note: logically, this belongs to `hir_ty`, but we are not using it there yet.
903 impl From<hir_ty::Mutability> for Access {
904 fn from(mutability: hir_ty::Mutability) -> Access {
906 hir_ty::Mutability::Not => Access::Shared,
907 hir_ty::Mutability::Mut => Access::Exclusive,
915 /// The index in parameter list, including self parameter.
921 pub fn ty(&self) -> &Type {
925 pub fn pattern_source(&self, db: &dyn HirDatabase) -> Option<ast::Pat> {
926 let params = self.func.source(db)?.value.param_list()?;
927 if params.self_param().is_some() {
928 params.params().nth(self.idx.checked_sub(1)?)?.pat()
930 params.params().nth(self.idx)?.pat()
935 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
936 pub struct SelfParam {
941 pub fn access(self, db: &dyn HirDatabase) -> Access {
942 let func_data = db.function_data(self.func);
946 .map(|param| match *param {
947 TypeRef::Reference(.., mutability) => match mutability {
948 hir_def::type_ref::Mutability::Shared => Access::Shared,
949 hir_def::type_ref::Mutability::Mut => Access::Exclusive,
953 .unwrap_or(Access::Owned)
956 pub fn display(self, db: &dyn HirDatabase) -> &'static str {
957 match self.access(db) {
958 Access::Shared => "&self",
959 Access::Exclusive => "&mut self",
960 Access::Owned => "self",
965 impl HasVisibility for Function {
966 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
967 let function_data = db.function_data(self.id);
968 let visibility = &function_data.visibility;
969 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
973 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
975 pub(crate) id: ConstId,
979 pub fn module(self, db: &dyn HirDatabase) -> Module {
980 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
983 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
984 Some(self.module(db).krate())
987 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
988 db.const_data(self.id).name.clone()
991 pub fn type_ref(self, db: &dyn HirDatabase) -> TypeRef {
992 db.const_data(self.id).type_ref.clone()
996 impl HasVisibility for Const {
997 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
998 let function_data = db.const_data(self.id);
999 let visibility = &function_data.visibility;
1000 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1004 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1006 pub(crate) id: StaticId,
1010 pub fn module(self, db: &dyn HirDatabase) -> Module {
1011 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
1014 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
1015 Some(self.module(db).krate())
1018 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1019 db.static_data(self.id).name.clone()
1022 pub fn is_mut(self, db: &dyn HirDatabase) -> bool {
1023 db.static_data(self.id).mutable
1027 impl HasVisibility for Static {
1028 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1029 db.static_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1033 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1035 pub(crate) id: TraitId,
1039 pub fn module(self, db: &dyn HirDatabase) -> Module {
1040 Module { id: self.id.lookup(db.upcast()).container }
1043 pub fn name(self, db: &dyn HirDatabase) -> Name {
1044 db.trait_data(self.id).name.clone()
1047 pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
1048 db.trait_data(self.id).items.iter().map(|(_name, it)| (*it).into()).collect()
1051 pub fn is_auto(self, db: &dyn HirDatabase) -> bool {
1052 db.trait_data(self.id).is_auto
1056 impl HasVisibility for Trait {
1057 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1058 db.trait_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1062 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1063 pub struct TypeAlias {
1064 pub(crate) id: TypeAliasId,
1068 pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
1069 let subst = db.generic_defaults(self.id.into());
1070 subst.iter().any(|ty| ty.value.is_unknown())
1073 pub fn module(self, db: &dyn HirDatabase) -> Module {
1074 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
1077 pub fn krate(self, db: &dyn HirDatabase) -> Crate {
1078 self.module(db).krate()
1081 pub fn type_ref(self, db: &dyn HirDatabase) -> Option<TypeRef> {
1082 db.type_alias_data(self.id).type_ref.clone()
1085 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1086 Type::from_def(db, self.id.lookup(db.upcast()).module(db.upcast()).krate(), self.id)
1089 pub fn name(self, db: &dyn HirDatabase) -> Name {
1090 db.type_alias_data(self.id).name.clone()
1094 impl HasVisibility for TypeAlias {
1095 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1096 let function_data = db.type_alias_data(self.id);
1097 let visibility = &function_data.visibility;
1098 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1102 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1103 pub struct BuiltinType {
1104 pub(crate) inner: hir_def::builtin_type::BuiltinType,
1108 pub fn ty(self, db: &dyn HirDatabase, module: Module) -> Type {
1109 let resolver = module.id.resolver(db.upcast());
1110 Type::new_with_resolver(db, &resolver, Ty::builtin(self.inner))
1111 .expect("crate not present in resolver")
1114 pub fn name(self) -> Name {
1115 self.inner.as_name()
1119 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1120 pub enum MacroKind {
1127 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1128 pub struct MacroDef {
1129 pub(crate) id: MacroDefId,
1133 /// FIXME: right now, this just returns the root module of the crate that
1134 /// defines this macro. The reasons for this is that macros are expanded
1135 /// early, in `hir_expand`, where modules simply do not exist yet.
1136 pub fn module(self, db: &dyn HirDatabase) -> Option<Module> {
1137 let krate = self.id.krate;
1138 let def_map = db.crate_def_map(krate);
1139 let module_id = def_map.root();
1140 Some(Module { id: def_map.module_id(module_id) })
1143 /// XXX: this parses the file
1144 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1145 match self.source(db)?.value {
1146 Either::Left(it) => it.name().map(|it| it.as_name()),
1147 Either::Right(it) => it.name().map(|it| it.as_name()),
1151 pub fn kind(&self) -> MacroKind {
1152 match self.id.kind {
1153 MacroDefKind::Declarative(_) => MacroKind::Declarative,
1154 MacroDefKind::BuiltIn(_, _) => MacroKind::BuiltIn,
1155 MacroDefKind::BuiltInDerive(_, _) => MacroKind::Derive,
1156 MacroDefKind::BuiltInEager(_, _) => MacroKind::BuiltIn,
1157 // FIXME might be a derive
1158 MacroDefKind::ProcMacro(_, _) => MacroKind::ProcMacro,
1163 /// Invariant: `inner.as_assoc_item(db).is_some()`
1164 /// We do not actively enforce this invariant.
1165 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1166 pub enum AssocItem {
1169 TypeAlias(TypeAlias),
1172 pub enum AssocItemContainer {
1176 pub trait AsAssocItem {
1177 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem>;
1180 impl AsAssocItem for Function {
1181 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1182 as_assoc_item(db, AssocItem::Function, self.id)
1185 impl AsAssocItem for Const {
1186 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1187 as_assoc_item(db, AssocItem::Const, self.id)
1190 impl AsAssocItem for TypeAlias {
1191 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1192 as_assoc_item(db, AssocItem::TypeAlias, self.id)
1195 impl AsAssocItem for ModuleDef {
1196 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1198 ModuleDef::Function(it) => it.as_assoc_item(db),
1199 ModuleDef::Const(it) => it.as_assoc_item(db),
1200 ModuleDef::TypeAlias(it) => it.as_assoc_item(db),
1205 fn as_assoc_item<ID, DEF, CTOR, AST>(db: &dyn HirDatabase, ctor: CTOR, id: ID) -> Option<AssocItem>
1207 ID: Lookup<Data = AssocItemLoc<AST>>,
1209 CTOR: FnOnce(DEF) -> AssocItem,
1212 match id.lookup(db.upcast()).container {
1213 AssocContainerId::TraitId(_) | AssocContainerId::ImplId(_) => Some(ctor(DEF::from(id))),
1214 AssocContainerId::ModuleId(_) => None,
1219 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1221 AssocItem::Function(it) => Some(it.name(db)),
1222 AssocItem::Const(it) => it.name(db),
1223 AssocItem::TypeAlias(it) => Some(it.name(db)),
1226 pub fn module(self, db: &dyn HirDatabase) -> Module {
1228 AssocItem::Function(f) => f.module(db),
1229 AssocItem::Const(c) => c.module(db),
1230 AssocItem::TypeAlias(t) => t.module(db),
1233 pub fn container(self, db: &dyn HirDatabase) -> AssocItemContainer {
1234 let container = match self {
1235 AssocItem::Function(it) => it.id.lookup(db.upcast()).container,
1236 AssocItem::Const(it) => it.id.lookup(db.upcast()).container,
1237 AssocItem::TypeAlias(it) => it.id.lookup(db.upcast()).container,
1240 AssocContainerId::TraitId(id) => AssocItemContainer::Trait(id.into()),
1241 AssocContainerId::ImplId(id) => AssocItemContainer::Impl(id.into()),
1242 AssocContainerId::ModuleId(_) => panic!("invalid AssocItem"),
1246 pub fn containing_trait(self, db: &dyn HirDatabase) -> Option<Trait> {
1247 match self.container(db) {
1248 AssocItemContainer::Trait(t) => Some(t),
1254 impl HasVisibility for AssocItem {
1255 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1257 AssocItem::Function(f) => f.visibility(db),
1258 AssocItem::Const(c) => c.visibility(db),
1259 AssocItem::TypeAlias(t) => t.visibility(db),
1264 #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
1265 pub enum GenericDef {
1269 TypeAlias(TypeAlias),
1271 // enum variants cannot have generics themselves, but their parent enums
1272 // can, and this makes some code easier to write
1274 // consts can have type parameters from their parents (i.e. associated consts of traits)
1279 Adt(Struct, Enum, Union),
1289 pub fn params(self, db: &dyn HirDatabase) -> Vec<GenericParam> {
1290 let generics = db.generic_params(self.into());
1291 let ty_params = generics
1294 .map(|(local_id, _)| TypeParam { id: TypeParamId { parent: self.into(), local_id } })
1295 .map(GenericParam::TypeParam);
1296 let lt_params = generics
1299 .map(|(local_id, _)| LifetimeParam {
1300 id: LifetimeParamId { parent: self.into(), local_id },
1302 .map(GenericParam::LifetimeParam);
1303 let const_params = generics
1306 .map(|(local_id, _)| ConstParam { id: ConstParamId { parent: self.into(), local_id } })
1307 .map(GenericParam::ConstParam);
1308 ty_params.chain(lt_params).chain(const_params).collect()
1311 pub fn type_params(self, db: &dyn HirDatabase) -> Vec<TypeParam> {
1312 let generics = db.generic_params(self.into());
1316 .map(|(local_id, _)| TypeParam { id: TypeParamId { parent: self.into(), local_id } })
1321 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1323 pub(crate) parent: DefWithBodyId,
1324 pub(crate) pat_id: PatId,
1328 pub fn is_param(self, db: &dyn HirDatabase) -> bool {
1329 let src = self.source(db);
1331 Either::Left(bind_pat) => {
1332 bind_pat.syntax().ancestors().any(|it| ast::Param::can_cast(it.kind()))
1334 Either::Right(_self_param) => true,
1338 // FIXME: why is this an option? It shouldn't be?
1339 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1340 let body = db.body(self.parent);
1341 match &body[self.pat_id] {
1342 Pat::Bind { name, .. } => Some(name.clone()),
1347 pub fn is_self(self, db: &dyn HirDatabase) -> bool {
1348 self.name(db) == Some(name![self])
1351 pub fn is_mut(self, db: &dyn HirDatabase) -> bool {
1352 let body = db.body(self.parent);
1353 matches!(&body[self.pat_id], Pat::Bind { mode: BindingAnnotation::Mutable, .. })
1356 pub fn parent(self, _db: &dyn HirDatabase) -> DefWithBody {
1360 pub fn module(self, db: &dyn HirDatabase) -> Module {
1361 self.parent(db).module(db)
1364 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1365 let def = self.parent;
1366 let infer = db.infer(def);
1367 let ty = infer[self.pat_id].clone();
1368 let krate = def.module(db.upcast()).krate();
1369 Type::new(db, krate, def, ty)
1372 pub fn source(self, db: &dyn HirDatabase) -> InFile<Either<ast::IdentPat, ast::SelfParam>> {
1373 let (_body, source_map) = db.body_with_source_map(self.parent);
1374 let src = source_map.pat_syntax(self.pat_id).unwrap(); // Hmm...
1375 let root = src.file_syntax(db.upcast());
1377 ast.map_left(|it| it.cast().unwrap().to_node(&root)).map_right(|it| it.to_node(&root))
1382 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1384 pub(crate) parent: DefWithBodyId,
1385 pub(crate) label_id: LabelId,
1389 pub fn module(self, db: &dyn HirDatabase) -> Module {
1390 self.parent(db).module(db)
1393 pub fn parent(self, _db: &dyn HirDatabase) -> DefWithBody {
1397 pub fn name(self, db: &dyn HirDatabase) -> Name {
1398 let body = db.body(self.parent);
1399 body[self.label_id].name.clone()
1402 pub fn source(self, db: &dyn HirDatabase) -> InFile<ast::Label> {
1403 let (_body, source_map) = db.body_with_source_map(self.parent);
1404 let src = source_map.label_syntax(self.label_id);
1405 let root = src.file_syntax(db.upcast());
1406 src.map(|ast| ast.to_node(&root))
1410 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1411 pub enum GenericParam {
1412 TypeParam(TypeParam),
1413 LifetimeParam(LifetimeParam),
1414 ConstParam(ConstParam),
1416 impl_from!(TypeParam, LifetimeParam, ConstParam for GenericParam);
1419 pub fn module(self, db: &dyn HirDatabase) -> Module {
1421 GenericParam::TypeParam(it) => it.module(db),
1422 GenericParam::LifetimeParam(it) => it.module(db),
1423 GenericParam::ConstParam(it) => it.module(db),
1427 pub fn name(self, db: &dyn HirDatabase) -> Name {
1429 GenericParam::TypeParam(it) => it.name(db),
1430 GenericParam::LifetimeParam(it) => it.name(db),
1431 GenericParam::ConstParam(it) => it.name(db),
1436 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1437 pub struct TypeParam {
1438 pub(crate) id: TypeParamId,
1442 pub fn name(self, db: &dyn HirDatabase) -> Name {
1443 let params = db.generic_params(self.id.parent);
1444 params.types[self.id.local_id].name.clone().unwrap_or_else(Name::missing)
1447 pub fn module(self, db: &dyn HirDatabase) -> Module {
1448 self.id.parent.module(db.upcast()).into()
1451 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1452 let resolver = self.id.parent.resolver(db.upcast());
1453 let krate = self.id.parent.module(db.upcast()).krate();
1454 let ty = TyKind::Placeholder(hir_ty::to_placeholder_idx(db, self.id)).intern(&Interner);
1455 Type::new_with_resolver_inner(db, krate, &resolver, ty)
1458 pub fn trait_bounds(self, db: &dyn HirDatabase) -> Vec<Trait> {
1459 db.generic_predicates_for_param(self.id)
1461 .filter_map(|pred| match &pred.skip_binders().skip_binders() {
1462 hir_ty::WhereClause::Implemented(trait_ref) => {
1463 Some(Trait::from(trait_ref.hir_trait_id()))
1470 pub fn default(self, db: &dyn HirDatabase) -> Option<Type> {
1471 let params = db.generic_defaults(self.id.parent);
1472 let local_idx = hir_ty::param_idx(db, self.id)?;
1473 let resolver = self.id.parent.resolver(db.upcast());
1474 let krate = self.id.parent.module(db.upcast()).krate();
1475 let ty = params.get(local_idx)?.clone();
1476 let subst = Substitution::type_params(db, self.id.parent);
1477 let ty = ty.subst(&subst.prefix(local_idx));
1478 Some(Type::new_with_resolver_inner(db, krate, &resolver, ty))
1482 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1483 pub struct LifetimeParam {
1484 pub(crate) id: LifetimeParamId,
1487 impl LifetimeParam {
1488 pub fn name(self, db: &dyn HirDatabase) -> Name {
1489 let params = db.generic_params(self.id.parent);
1490 params.lifetimes[self.id.local_id].name.clone()
1493 pub fn module(self, db: &dyn HirDatabase) -> Module {
1494 self.id.parent.module(db.upcast()).into()
1497 pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef {
1498 self.id.parent.into()
1502 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1503 pub struct ConstParam {
1504 pub(crate) id: ConstParamId,
1508 pub fn name(self, db: &dyn HirDatabase) -> Name {
1509 let params = db.generic_params(self.id.parent);
1510 params.consts[self.id.local_id].name.clone()
1513 pub fn module(self, db: &dyn HirDatabase) -> Module {
1514 self.id.parent.module(db.upcast()).into()
1517 pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef {
1518 self.id.parent.into()
1521 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1522 let def = self.id.parent;
1523 let krate = def.module(db.upcast()).krate();
1524 Type::new(db, krate, def, db.const_param_ty(self.id))
1528 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1530 pub(crate) id: ImplId,
1534 pub fn all_in_crate(db: &dyn HirDatabase, krate: Crate) -> Vec<Impl> {
1535 let inherent = db.inherent_impls_in_crate(krate.id);
1536 let trait_ = db.trait_impls_in_crate(krate.id);
1538 inherent.all_impls().chain(trait_.all_impls()).map(Self::from).collect()
1541 pub fn all_for_type(db: &dyn HirDatabase, Type { krate, ty, .. }: Type) -> Vec<Impl> {
1542 let def_crates = match ty.def_crates(db, krate) {
1543 Some(def_crates) => def_crates,
1544 None => return Vec::new(),
1547 let filter = |impl_def: &Impl| {
1548 let target_ty = impl_def.target_ty(db);
1549 let rref = target_ty.remove_ref();
1550 ty.equals_ctor(rref.as_ref().map_or(&target_ty.ty, |it| &it.ty))
1553 let mut all = Vec::new();
1554 def_crates.iter().for_each(|&id| {
1555 all.extend(db.inherent_impls_in_crate(id).all_impls().map(Self::from).filter(filter))
1557 let fp = TyFingerprint::for_impl(&ty);
1558 for id in def_crates
1560 .flat_map(|&id| Crate { id }.transitive_reverse_dependencies(db))
1561 .map(|Crate { id }| id)
1562 .chain(def_crates.iter().copied())
1566 Some(fp) => all.extend(
1567 db.trait_impls_in_crate(id).for_self_ty(fp).map(Self::from).filter(filter),
1570 .extend(db.trait_impls_in_crate(id).all_impls().map(Self::from).filter(filter)),
1576 pub fn all_for_trait(db: &dyn HirDatabase, trait_: Trait) -> Vec<Impl> {
1577 let krate = trait_.module(db).krate();
1578 let mut all = Vec::new();
1579 for Crate { id } in krate.transitive_reverse_dependencies(db).into_iter() {
1580 let impls = db.trait_impls_in_crate(id);
1581 all.extend(impls.for_trait(trait_.id).map(Self::from))
1586 // FIXME: the return type is wrong. This should be a hir version of
1587 // `TraitRef` (ie, resolved `TypeRef`).
1588 pub fn target_trait(self, db: &dyn HirDatabase) -> Option<TypeRef> {
1589 db.impl_data(self.id).target_trait.clone()
1592 pub fn target_ty(self, db: &dyn HirDatabase) -> Type {
1593 let impl_data = db.impl_data(self.id);
1594 let resolver = self.id.resolver(db.upcast());
1595 let krate = self.id.lookup(db.upcast()).container.krate();
1596 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
1597 let ty = ctx.lower_ty(&impl_data.target_type);
1598 Type::new_with_resolver_inner(db, krate, &resolver, ty)
1601 pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
1602 db.impl_data(self.id).items.iter().map(|it| (*it).into()).collect()
1605 pub fn is_negative(self, db: &dyn HirDatabase) -> bool {
1606 db.impl_data(self.id).is_negative
1609 pub fn module(self, db: &dyn HirDatabase) -> Module {
1610 self.id.lookup(db.upcast()).container.into()
1613 pub fn krate(self, db: &dyn HirDatabase) -> Crate {
1614 Crate { id: self.module(db).id.krate() }
1617 pub fn is_builtin_derive(self, db: &dyn HirDatabase) -> Option<InFile<ast::Attr>> {
1618 let src = self.source(db)?;
1619 let item = src.file_id.is_builtin_derive(db.upcast())?;
1620 let hygenic = hir_expand::hygiene::Hygiene::new(db.upcast(), item.file_id);
1622 // FIXME: handle `cfg_attr`
1627 let path = ModPath::from_src(it.path()?, &hygenic)?;
1628 if path.as_ident()?.to_string() == "derive" {
1636 Some(item.with_value(attr))
1640 #[derive(Clone, PartialEq, Eq, Debug)]
1643 env: Arc<TraitEnvironment>,
1648 pub(crate) fn new_with_resolver(
1649 db: &dyn HirDatabase,
1650 resolver: &Resolver,
1653 let krate = resolver.krate()?;
1654 Some(Type::new_with_resolver_inner(db, krate, resolver, ty))
1656 pub(crate) fn new_with_resolver_inner(
1657 db: &dyn HirDatabase,
1659 resolver: &Resolver,
1663 resolver.generic_def().map_or_else(Default::default, |d| db.trait_environment(d));
1664 Type { krate, env: environment, ty }
1667 fn new(db: &dyn HirDatabase, krate: CrateId, lexical_env: impl HasResolver, ty: Ty) -> Type {
1668 let resolver = lexical_env.resolver(db.upcast());
1670 resolver.generic_def().map_or_else(Default::default, |d| db.trait_environment(d));
1671 Type { krate, env: environment, ty }
1675 db: &dyn HirDatabase,
1677 def: impl HasResolver + Into<TyDefId> + Into<GenericDefId>,
1679 let substs = Substitution::build_for_def(db, def).fill_with_unknown().build();
1680 let ty = db.ty(def.into()).subst(&substs);
1681 Type::new(db, krate, def, ty)
1684 pub fn is_unit(&self) -> bool {
1685 matches!(self.ty.interned(&Interner), TyKind::Tuple(0, ..))
1687 pub fn is_bool(&self) -> bool {
1688 matches!(self.ty.interned(&Interner), TyKind::Scalar(Scalar::Bool))
1691 pub fn is_mutable_reference(&self) -> bool {
1692 matches!(self.ty.interned(&Interner), TyKind::Ref(hir_ty::Mutability::Mut, ..))
1695 pub fn is_usize(&self) -> bool {
1696 matches!(self.ty.interned(&Interner), TyKind::Scalar(Scalar::Uint(UintTy::Usize)))
1699 pub fn remove_ref(&self) -> Option<Type> {
1700 match &self.ty.interned(&Interner) {
1701 TyKind::Ref(.., ty) => Some(self.derived(ty.clone())),
1706 pub fn is_unknown(&self) -> bool {
1707 self.ty.is_unknown()
1710 /// Checks that particular type `ty` implements `std::future::Future`.
1711 /// This function is used in `.await` syntax completion.
1712 pub fn impls_future(&self, db: &dyn HirDatabase) -> bool {
1713 // No special case for the type of async block, since Chalk can figure it out.
1715 let krate = self.krate;
1717 let std_future_trait =
1718 db.lang_item(krate, "future_trait".into()).and_then(|it| it.as_trait());
1719 let std_future_trait = match std_future_trait {
1721 None => return false,
1725 Canonical { value: self.ty.clone(), binders: CanonicalVarKinds::empty(&Interner) };
1726 method_resolution::implements_trait(
1735 /// Checks that particular type `ty` implements `std::ops::FnOnce`.
1737 /// This function can be used to check if a particular type is callable, since FnOnce is a
1738 /// supertrait of Fn and FnMut, so all callable types implements at least FnOnce.
1739 pub fn impls_fnonce(&self, db: &dyn HirDatabase) -> bool {
1740 let krate = self.krate;
1742 let fnonce_trait = match FnTrait::FnOnce.get_id(db, krate) {
1744 None => return false,
1748 Canonical { value: self.ty.clone(), binders: CanonicalVarKinds::empty(&Interner) };
1749 method_resolution::implements_trait_unique(
1758 pub fn impls_trait(&self, db: &dyn HirDatabase, trait_: Trait, args: &[Type]) -> bool {
1759 let trait_ref = hir_ty::TraitRef {
1760 trait_id: hir_ty::to_chalk_trait_id(trait_.id),
1761 substitution: Substitution::build_for_def(db, trait_.id)
1762 .push(self.ty.clone())
1763 .fill(args.iter().map(|t| t.ty.clone()))
1767 let goal = Canonical {
1768 value: hir_ty::InEnvironment::new(self.env.env.clone(), trait_ref.cast(&Interner)),
1769 binders: CanonicalVarKinds::empty(&Interner),
1772 db.trait_solve(self.krate, goal).is_some()
1775 pub fn normalize_trait_assoc_type(
1777 db: &dyn HirDatabase,
1782 let subst = Substitution::build_for_def(db, trait_.id)
1783 .push(self.ty.clone())
1784 .fill(args.iter().map(|t| t.ty.clone()))
1786 let goal = Canonical::new(
1788 self.env.env.clone(),
1790 alias: AliasTy::Projection(ProjectionTy {
1791 associated_ty_id: to_assoc_type_id(alias.id),
1792 substitution: subst,
1794 ty: TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0))
1799 [TyVariableKind::General].iter().copied(),
1802 match db.trait_solve(self.krate, goal)? {
1803 Solution::Unique(SolutionVariables(subst)) => {
1804 subst.value.first().map(|ty| self.derived(ty.clone()))
1806 Solution::Ambig(_) => None,
1810 pub fn is_copy(&self, db: &dyn HirDatabase) -> bool {
1811 let lang_item = db.lang_item(self.krate, SmolStr::new("copy"));
1812 let copy_trait = match lang_item {
1813 Some(LangItemTarget::TraitId(it)) => it,
1816 self.impls_trait(db, copy_trait.into(), &[])
1819 pub fn as_callable(&self, db: &dyn HirDatabase) -> Option<Callable> {
1820 let def = self.ty.callable_def(db);
1822 let sig = self.ty.callable_sig(db)?;
1823 Some(Callable { ty: self.clone(), sig, def, is_bound_method: false })
1826 pub fn is_closure(&self) -> bool {
1827 matches!(&self.ty.interned(&Interner), TyKind::Closure { .. })
1830 pub fn is_fn(&self) -> bool {
1831 matches!(&self.ty.interned(&Interner), TyKind::FnDef(..) | TyKind::Function { .. })
1834 pub fn is_packed(&self, db: &dyn HirDatabase) -> bool {
1835 let adt_id = match self.ty.interned(&Interner) {
1836 &TyKind::Adt(hir_ty::AdtId(adt_id), ..) => adt_id,
1840 let adt = adt_id.into();
1842 Adt::Struct(s) => matches!(s.repr(db), Some(ReprKind::Packed)),
1847 pub fn is_raw_ptr(&self) -> bool {
1848 matches!(&self.ty.interned(&Interner), TyKind::Raw(..))
1851 pub fn contains_unknown(&self) -> bool {
1852 return go(&self.ty);
1854 fn go(ty: &Ty) -> bool {
1855 match ty.interned(&Interner) {
1856 TyKind::Unknown => true,
1858 TyKind::Adt(_, substs)
1859 | TyKind::AssociatedType(_, substs)
1860 | TyKind::Tuple(_, substs)
1861 | TyKind::OpaqueType(_, substs)
1862 | TyKind::FnDef(_, substs)
1863 | TyKind::Closure(_, substs) => substs.iter().any(go),
1865 TyKind::Array(ty) | TyKind::Slice(ty) | TyKind::Raw(_, ty) | TyKind::Ref(_, ty) => {
1872 | TyKind::Placeholder(_)
1873 | TyKind::BoundVar(_)
1874 | TyKind::InferenceVar(_, _)
1876 | TyKind::Function(_)
1878 | TyKind::ForeignType(_) => false,
1883 pub fn fields(&self, db: &dyn HirDatabase) -> Vec<(Field, Type)> {
1884 let (variant_id, substs) = match self.ty.interned(&Interner) {
1885 &TyKind::Adt(hir_ty::AdtId(AdtId::StructId(s)), ref substs) => (s.into(), substs),
1886 &TyKind::Adt(hir_ty::AdtId(AdtId::UnionId(u)), ref substs) => (u.into(), substs),
1887 _ => return Vec::new(),
1890 db.field_types(variant_id)
1892 .map(|(local_id, ty)| {
1893 let def = Field { parent: variant_id.into(), id: local_id };
1894 let ty = ty.clone().subst(substs);
1895 (def, self.derived(ty))
1900 pub fn tuple_fields(&self, _db: &dyn HirDatabase) -> Vec<Type> {
1901 if let TyKind::Tuple(_, substs) = &self.ty.interned(&Interner) {
1902 substs.iter().map(|ty| self.derived(ty.clone())).collect()
1908 pub fn autoderef<'a>(&'a self, db: &'a dyn HirDatabase) -> impl Iterator<Item = Type> + 'a {
1909 // There should be no inference vars in types passed here
1910 // FIXME check that?
1912 Canonical { value: self.ty.clone(), binders: CanonicalVarKinds::empty(&Interner) };
1913 let environment = self.env.env.clone();
1914 let ty = InEnvironment { goal: canonical, environment };
1915 autoderef(db, Some(self.krate), ty)
1916 .map(|canonical| canonical.value)
1917 .map(move |ty| self.derived(ty))
1920 // This would be nicer if it just returned an iterator, but that runs into
1921 // lifetime problems, because we need to borrow temp `CrateImplDefs`.
1922 pub fn iterate_assoc_items<T>(
1924 db: &dyn HirDatabase,
1926 mut callback: impl FnMut(AssocItem) -> Option<T>,
1928 for krate in self.ty.def_crates(db, krate.id)? {
1929 let impls = db.inherent_impls_in_crate(krate);
1931 for impl_def in impls.for_self_ty(&self.ty) {
1932 for &item in db.impl_data(*impl_def).items.iter() {
1933 if let Some(result) = callback(item.into()) {
1934 return Some(result);
1942 pub fn type_parameters(&self) -> impl Iterator<Item = Type> + '_ {
1947 .flat_map(|substs| substs.iter())
1948 .map(move |ty| self.derived(ty.clone()))
1951 pub fn iterate_method_candidates<T>(
1953 db: &dyn HirDatabase,
1955 traits_in_scope: &FxHashSet<TraitId>,
1956 name: Option<&Name>,
1957 mut callback: impl FnMut(&Ty, Function) -> Option<T>,
1959 // There should be no inference vars in types passed here
1960 // FIXME check that?
1961 // FIXME replace Unknown by bound vars here
1963 Canonical { value: self.ty.clone(), binders: CanonicalVarKinds::empty(&Interner) };
1965 let env = self.env.clone();
1966 let krate = krate.id;
1968 method_resolution::iterate_method_candidates(
1975 method_resolution::LookupMode::MethodCall,
1977 AssocItemId::FunctionId(f) => callback(ty, f.into()),
1983 pub fn iterate_path_candidates<T>(
1985 db: &dyn HirDatabase,
1987 traits_in_scope: &FxHashSet<TraitId>,
1988 name: Option<&Name>,
1989 mut callback: impl FnMut(&Ty, AssocItem) -> Option<T>,
1991 // There should be no inference vars in types passed here
1992 // FIXME check that?
1993 // FIXME replace Unknown by bound vars here
1995 Canonical { value: self.ty.clone(), binders: CanonicalVarKinds::empty(&Interner) };
1997 let env = self.env.clone();
1998 let krate = krate.id;
2000 method_resolution::iterate_method_candidates(
2007 method_resolution::LookupMode::Path,
2008 |ty, it| callback(ty, it.into()),
2012 pub fn as_adt(&self) -> Option<Adt> {
2013 let (adt, _subst) = self.ty.as_adt()?;
2017 pub fn as_dyn_trait(&self) -> Option<Trait> {
2018 self.ty.dyn_trait().map(Into::into)
2021 pub fn as_impl_traits(&self, db: &dyn HirDatabase) -> Option<Vec<Trait>> {
2022 self.ty.impl_trait_bounds(db).map(|it| {
2024 .filter_map(|pred| match pred.skip_binders() {
2025 hir_ty::WhereClause::Implemented(trait_ref) => {
2026 Some(Trait::from(trait_ref.hir_trait_id()))
2034 pub fn as_associated_type_parent_trait(&self, db: &dyn HirDatabase) -> Option<Trait> {
2035 self.ty.associated_type_parent_trait(db).map(Into::into)
2038 fn derived(&self, ty: Ty) -> Type {
2039 Type { krate: self.krate, env: self.env.clone(), ty }
2042 pub fn walk(&self, db: &dyn HirDatabase, mut cb: impl FnMut(Type)) {
2043 // TypeWalk::walk for a Ty at first visits parameters and only after that the Ty itself.
2044 // We need a different order here.
2047 db: &dyn HirDatabase,
2049 substs: &Substitution,
2050 cb: &mut impl FnMut(Type),
2052 for ty in substs.iter() {
2053 walk_type(db, &type_.derived(ty.clone()), cb);
2058 db: &dyn HirDatabase,
2060 bounds: &[QuantifiedWhereClause],
2061 cb: &mut impl FnMut(Type),
2063 for pred in bounds {
2064 match pred.skip_binders() {
2065 WhereClause::Implemented(trait_ref) => {
2067 // skip the self type. it's likely the type we just got the bounds from
2068 for ty in trait_ref.substitution.iter().skip(1) {
2069 walk_type(db, &type_.derived(ty.clone()), cb);
2077 fn walk_type(db: &dyn HirDatabase, type_: &Type, cb: &mut impl FnMut(Type)) {
2078 let ty = type_.ty.strip_references();
2079 match ty.interned(&Interner) {
2080 TyKind::Adt(..) => {
2081 cb(type_.derived(ty.clone()));
2083 TyKind::AssociatedType(..) => {
2084 if let Some(_) = ty.associated_type_parent_trait(db) {
2085 cb(type_.derived(ty.clone()));
2088 TyKind::OpaqueType(..) => {
2089 if let Some(bounds) = ty.impl_trait_bounds(db) {
2090 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
2093 TyKind::Alias(AliasTy::Opaque(opaque_ty)) => {
2094 if let Some(bounds) = ty.impl_trait_bounds(db) {
2095 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
2098 walk_substs(db, type_, &opaque_ty.substitution, cb);
2100 TyKind::Placeholder(_) => {
2101 if let Some(bounds) = ty.impl_trait_bounds(db) {
2102 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
2105 TyKind::Dyn(bounds) => {
2108 &type_.derived(ty.clone()),
2109 bounds.bounds.skip_binders().interned(),
2114 TyKind::Ref(_, ty) | TyKind::Raw(_, ty) | TyKind::Array(ty) | TyKind::Slice(ty) => {
2115 walk_type(db, &type_.derived(ty.clone()), cb);
2120 if let Some(substs) = ty.substs() {
2121 walk_substs(db, type_, &substs, cb);
2125 walk_type(db, self, &mut cb);
2131 pub struct Callable {
2134 def: Option<CallableDefId>,
2135 pub(crate) is_bound_method: bool,
2138 pub enum CallableKind {
2140 TupleStruct(Struct),
2141 TupleEnumVariant(Variant),
2146 pub fn kind(&self) -> CallableKind {
2148 Some(CallableDefId::FunctionId(it)) => CallableKind::Function(it.into()),
2149 Some(CallableDefId::StructId(it)) => CallableKind::TupleStruct(it.into()),
2150 Some(CallableDefId::EnumVariantId(it)) => CallableKind::TupleEnumVariant(it.into()),
2151 None => CallableKind::Closure,
2154 pub fn receiver_param(&self, db: &dyn HirDatabase) -> Option<ast::SelfParam> {
2155 let func = match self.def {
2156 Some(CallableDefId::FunctionId(it)) if self.is_bound_method => it,
2159 let src = func.lookup(db.upcast()).source(db.upcast());
2160 let param_list = src.value.param_list()?;
2161 param_list.self_param()
2163 pub fn n_params(&self) -> usize {
2164 self.sig.params().len() - if self.is_bound_method { 1 } else { 0 }
2168 db: &dyn HirDatabase,
2169 ) -> Vec<(Option<Either<ast::SelfParam, ast::Pat>>, Type)> {
2174 .skip(if self.is_bound_method { 1 } else { 0 })
2175 .map(|ty| self.ty.derived(ty.clone()));
2176 let patterns = match self.def {
2177 Some(CallableDefId::FunctionId(func)) => {
2178 let src = func.lookup(db.upcast()).source(db.upcast());
2179 src.value.param_list().map(|param_list| {
2182 .map(|it| Some(Either::Left(it)))
2183 .filter(|_| !self.is_bound_method)
2185 .chain(param_list.params().map(|it| it.pat().map(Either::Right)))
2190 patterns.into_iter().flatten().chain(iter::repeat(None)).zip(types).collect()
2192 pub fn return_type(&self) -> Type {
2193 self.ty.derived(self.sig.ret().clone())
2198 #[derive(Debug, PartialEq, Eq, Hash)]
2200 ModuleDef(ModuleDef),
2202 GenericParam(GenericParam),
2211 pub fn all_items(def: PerNs) -> ArrayVec<[Self; 3]> {
2212 let mut items = ArrayVec::new();
2214 match (def.take_types(), def.take_values()) {
2215 (Some(m1), None) => items.push(ScopeDef::ModuleDef(m1.into())),
2216 (None, Some(m2)) => items.push(ScopeDef::ModuleDef(m2.into())),
2217 (Some(m1), Some(m2)) => {
2218 // Some items, like unit structs and enum variants, are
2219 // returned as both a type and a value. Here we want
2220 // to de-duplicate them.
2222 items.push(ScopeDef::ModuleDef(m1.into()));
2223 items.push(ScopeDef::ModuleDef(m2.into()));
2225 items.push(ScopeDef::ModuleDef(m1.into()));
2231 if let Some(macro_def_id) = def.take_macros() {
2232 items.push(ScopeDef::MacroDef(macro_def_id.into()));
2235 if items.is_empty() {
2236 items.push(ScopeDef::Unknown);
2243 impl From<ItemInNs> for ScopeDef {
2244 fn from(item: ItemInNs) -> Self {
2246 ItemInNs::Types(id) => ScopeDef::ModuleDef(id.into()),
2247 ItemInNs::Values(id) => ScopeDef::ModuleDef(id.into()),
2248 ItemInNs::Macros(id) => ScopeDef::MacroDef(id.into()),
2253 pub trait HasVisibility {
2254 fn visibility(&self, db: &dyn HirDatabase) -> Visibility;
2255 fn is_visible_from(&self, db: &dyn HirDatabase, module: Module) -> bool {
2256 let vis = self.visibility(db);
2257 vis.is_visible_from(db.upcast(), module.id)