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::{collections::HashMap, iter, ops::ControlFlow, sync::Arc};
36 use arrayvec::ArrayVec;
37 use base_db::{CrateDisplayName, CrateId, CrateOrigin, Edition, FileId};
40 adt::{ReprKind, VariantData},
41 body::{BodyDiagnostic, SyntheticSyntax},
42 expr::{BindingAnnotation, LabelId, Pat, PatId},
43 lang_item::LangItemTarget,
46 resolver::{HasResolver, Resolver},
47 AttrDefId, ConstId, ConstParamId, EnumId, FunctionId, GenericDefId, HasModule, LifetimeParamId,
48 LocalEnumVariantId, LocalFieldId, StaticId, StructId, TypeAliasId, TypeParamId, UnionId,
50 use hir_expand::{name::name, MacroCallKind, MacroDefKind};
53 consteval::{eval_const, ComputedExpr, ConstEvalCtx, ConstEvalError, ConstExt},
55 diagnostics::BodyValidationDiagnostic,
56 method_resolution::{self, TyFingerprint},
60 AliasEq, AliasTy, BoundVar, CallableDefId, CallableSig, Canonical, CanonicalVarKinds, Cast,
61 DebruijnIndex, InEnvironment, Interner, QuantifiedWhereClause, Scalar, Solution, Substitution,
62 TraitEnvironment, TraitRefExt, Ty, TyBuilder, TyDefId, TyExt, TyKind, TyVariableKind,
65 use itertools::Itertools;
66 use nameres::diagnostics::DefDiagnosticKind;
67 use once_cell::unsync::Lazy;
68 use rustc_hash::FxHashSet;
69 use stdx::{format_to, impl_from};
71 ast::{self, HasAttrs as _, HasDocComments, HasName},
72 AstNode, AstPtr, SmolStr, SyntaxKind, SyntaxNodePtr,
74 use tt::{Ident, Leaf, Literal, TokenTree};
76 use crate::db::{DefDatabase, HirDatabase};
79 attrs::{HasAttrs, Namespace},
81 AddReferenceHere, AnyDiagnostic, BreakOutsideOfLoop, InactiveCode, IncorrectCase,
82 InvalidDeriveTarget, MacroError, MalformedDerive, MismatchedArgCount, MissingFields,
83 MissingMatchArms, MissingOkOrSomeInTailExpr, MissingUnsafe, NoSuchField,
84 RemoveThisSemicolon, ReplaceFilterMapNextWithFindMap, UnimplementedBuiltinMacro,
85 UnresolvedExternCrate, UnresolvedImport, UnresolvedMacroCall, UnresolvedModule,
88 has_source::HasSource,
89 semantics::{PathResolution, Semantics, SemanticsScope, TypeInfo},
92 // Be careful with these re-exports.
94 // `hir` is the boundary between the compiler and the IDE. It should try hard to
95 // isolate the compiler from the ide, to allow the two to be refactored
96 // independently. Re-exporting something from the compiler is the sure way to
97 // breach the boundary.
99 // Generally, a refactoring which *removes* a name from this list is a good
102 cfg::{CfgAtom, CfgExpr, CfgOptions},
105 attr::{Attr, Attrs, AttrsWithOwner, Documentation},
106 builtin_attr::AttributeTemplate,
107 find_path::PrefixKind,
109 item_scope::ItemScope,
110 item_tree::ItemTreeNode,
111 nameres::{DefMap, ModuleData, ModuleOrigin, ModuleSource},
112 path::{ModPath, PathKind},
113 src::HasSource as DefHasSource, // xx: I don't like this shadowing of HasSource... :(
114 type_ref::{Mutability, TypeRef},
115 visibility::Visibility,
130 ExpandResult, HirFileId, InFile, MacroDefId, MacroFile, Origin,
132 hir_ty::display::HirDisplay,
135 // These are negative re-exports: pub using these names is forbidden, they
136 // should remain private to hir internals.
140 hir_expand::{hygiene::Hygiene, name::AsName},
143 /// hir::Crate describes a single crate. It's the main interface with which
144 /// a crate's dependencies interact. Mostly, it should be just a proxy for the
146 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
148 pub(crate) id: CrateId,
152 pub struct CrateDependency {
158 pub fn origin(self, db: &dyn HirDatabase) -> CrateOrigin {
159 db.crate_graph()[self.id].origin.clone()
162 pub fn dependencies(self, db: &dyn HirDatabase) -> Vec<CrateDependency> {
163 db.crate_graph()[self.id]
167 let krate = Crate { id: dep.crate_id };
168 let name = dep.as_name();
169 CrateDependency { krate, name }
174 pub fn reverse_dependencies(self, db: &dyn HirDatabase) -> Vec<Crate> {
175 let crate_graph = db.crate_graph();
179 crate_graph[krate].dependencies.iter().any(|it| it.crate_id == self.id)
181 .map(|id| Crate { id })
185 pub fn transitive_reverse_dependencies(self, db: &dyn HirDatabase) -> Vec<Crate> {
186 db.crate_graph().transitive_rev_deps(self.id).into_iter().map(|id| Crate { id }).collect()
189 pub fn root_module(self, db: &dyn HirDatabase) -> Module {
190 let def_map = db.crate_def_map(self.id);
191 Module { id: def_map.module_id(def_map.root()) }
194 pub fn root_file(self, db: &dyn HirDatabase) -> FileId {
195 db.crate_graph()[self.id].root_file_id
198 pub fn edition(self, db: &dyn HirDatabase) -> Edition {
199 db.crate_graph()[self.id].edition
202 pub fn version(self, db: &dyn HirDatabase) -> Option<String> {
203 db.crate_graph()[self.id].version.clone()
206 pub fn display_name(self, db: &dyn HirDatabase) -> Option<CrateDisplayName> {
207 db.crate_graph()[self.id].display_name.clone()
210 pub fn query_external_importables(
212 db: &dyn DefDatabase,
213 query: import_map::Query,
214 ) -> impl Iterator<Item = Either<ModuleDef, MacroDef>> {
215 let _p = profile::span("query_external_importables");
216 import_map::search_dependencies(db, self.into(), query).into_iter().map(|item| {
217 match ItemInNs::from(item) {
218 ItemInNs::Types(mod_id) | ItemInNs::Values(mod_id) => Either::Left(mod_id),
219 ItemInNs::Macros(mac_id) => Either::Right(mac_id),
224 pub fn all(db: &dyn HirDatabase) -> Vec<Crate> {
225 db.crate_graph().iter().map(|id| Crate { id }).collect()
228 /// Try to get the root URL of the documentation of a crate.
229 pub fn get_html_root_url(self: &Crate, db: &dyn HirDatabase) -> Option<String> {
230 // Look for #![doc(html_root_url = "...")]
231 let attrs = db.attrs(AttrDefId::ModuleId(self.root_module(db).into()));
232 let doc_attr_q = attrs.by_key("doc");
234 if !doc_attr_q.exists() {
238 let doc_url = doc_attr_q.tt_values().map(|tt| {
239 let name = tt.token_trees.iter()
240 .skip_while(|tt| !matches!(tt, TokenTree::Leaf(Leaf::Ident(Ident { text, ..} )) if text == "html_root_url"))
244 Some(TokenTree::Leaf(Leaf::Literal(Literal{ref text, ..}))) => Some(text),
249 doc_url.map(|s| s.trim_matches('"').trim_end_matches('/').to_owned() + "/")
252 pub fn cfg(&self, db: &dyn HirDatabase) -> CfgOptions {
253 db.crate_graph()[self.id].cfg_options.clone()
256 pub fn potential_cfg(&self, db: &dyn HirDatabase) -> CfgOptions {
257 db.crate_graph()[self.id].potential_cfg_options.clone()
261 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
263 pub(crate) id: ModuleId,
266 /// The defs which can be visible in the module.
267 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
272 // Can't be directly declared, but can be imported.
277 TypeAlias(TypeAlias),
278 BuiltinType(BuiltinType),
283 Adt(Struct, Enum, Union),
293 impl From<VariantDef> for ModuleDef {
294 fn from(var: VariantDef) -> Self {
296 VariantDef::Struct(t) => Adt::from(t).into(),
297 VariantDef::Union(t) => Adt::from(t).into(),
298 VariantDef::Variant(t) => t.into(),
304 pub fn module(self, db: &dyn HirDatabase) -> Option<Module> {
306 ModuleDef::Module(it) => it.parent(db),
307 ModuleDef::Function(it) => Some(it.module(db)),
308 ModuleDef::Adt(it) => Some(it.module(db)),
309 ModuleDef::Variant(it) => Some(it.module(db)),
310 ModuleDef::Const(it) => Some(it.module(db)),
311 ModuleDef::Static(it) => Some(it.module(db)),
312 ModuleDef::Trait(it) => Some(it.module(db)),
313 ModuleDef::TypeAlias(it) => Some(it.module(db)),
314 ModuleDef::BuiltinType(_) => None,
318 pub fn canonical_path(&self, db: &dyn HirDatabase) -> Option<String> {
319 let mut segments = vec![self.name(db)?];
320 for m in self.module(db)?.path_to_root(db) {
321 segments.extend(m.name(db))
324 Some(segments.into_iter().join("::"))
327 pub fn canonical_module_path(
329 db: &dyn HirDatabase,
330 ) -> Option<impl Iterator<Item = Module>> {
331 self.module(db).map(|it| it.path_to_root(db).into_iter().rev())
334 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
335 let name = match self {
336 ModuleDef::Module(it) => it.name(db)?,
337 ModuleDef::Const(it) => it.name(db)?,
338 ModuleDef::Adt(it) => it.name(db),
339 ModuleDef::Trait(it) => it.name(db),
340 ModuleDef::Function(it) => it.name(db),
341 ModuleDef::Variant(it) => it.name(db),
342 ModuleDef::TypeAlias(it) => it.name(db),
343 ModuleDef::Static(it) => it.name(db),
344 ModuleDef::BuiltinType(it) => it.name(),
349 pub fn diagnostics(self, db: &dyn HirDatabase) -> Vec<AnyDiagnostic> {
350 let id = match self {
351 ModuleDef::Adt(it) => match it {
352 Adt::Struct(it) => it.id.into(),
353 Adt::Enum(it) => it.id.into(),
354 Adt::Union(it) => it.id.into(),
356 ModuleDef::Trait(it) => it.id.into(),
357 ModuleDef::Function(it) => it.id.into(),
358 ModuleDef::TypeAlias(it) => it.id.into(),
359 ModuleDef::Module(it) => it.id.into(),
360 ModuleDef::Const(it) => it.id.into(),
361 ModuleDef::Static(it) => it.id.into(),
362 _ => return Vec::new(),
365 let module = match self.module(db) {
367 None => return Vec::new(),
370 let mut acc = Vec::new();
372 match self.as_def_with_body() {
374 def.diagnostics(db, &mut acc);
377 for diag in hir_ty::diagnostics::incorrect_case(db, module.id.krate(), id) {
378 acc.push(diag.into())
386 pub fn as_def_with_body(self) -> Option<DefWithBody> {
388 ModuleDef::Function(it) => Some(it.into()),
389 ModuleDef::Const(it) => Some(it.into()),
390 ModuleDef::Static(it) => Some(it.into()),
394 | ModuleDef::Variant(_)
395 | ModuleDef::Trait(_)
396 | ModuleDef::TypeAlias(_)
397 | ModuleDef::BuiltinType(_) => None,
401 pub fn attrs(&self, db: &dyn HirDatabase) -> Option<AttrsWithOwner> {
403 ModuleDef::Module(it) => it.attrs(db),
404 ModuleDef::Function(it) => it.attrs(db),
405 ModuleDef::Adt(it) => it.attrs(db),
406 ModuleDef::Variant(it) => it.attrs(db),
407 ModuleDef::Const(it) => it.attrs(db),
408 ModuleDef::Static(it) => it.attrs(db),
409 ModuleDef::Trait(it) => it.attrs(db),
410 ModuleDef::TypeAlias(it) => it.attrs(db),
411 ModuleDef::BuiltinType(_) => return None,
416 impl HasVisibility for ModuleDef {
417 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
419 ModuleDef::Module(it) => it.visibility(db),
420 ModuleDef::Function(it) => it.visibility(db),
421 ModuleDef::Adt(it) => it.visibility(db),
422 ModuleDef::Const(it) => it.visibility(db),
423 ModuleDef::Static(it) => it.visibility(db),
424 ModuleDef::Trait(it) => it.visibility(db),
425 ModuleDef::TypeAlias(it) => it.visibility(db),
426 ModuleDef::Variant(it) => it.visibility(db),
427 ModuleDef::BuiltinType(_) => Visibility::Public,
433 /// Name of this module.
434 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
435 let def_map = self.id.def_map(db.upcast());
436 let parent = def_map[self.id.local_id].parent?;
437 def_map[parent].children.iter().find_map(|(name, module_id)| {
438 if *module_id == self.id.local_id {
446 /// Returns the crate this module is part of.
447 pub fn krate(self) -> Crate {
448 Crate { id: self.id.krate() }
451 /// Topmost parent of this module. Every module has a `crate_root`, but some
452 /// might be missing `krate`. This can happen if a module's file is not included
453 /// in the module tree of any target in `Cargo.toml`.
454 pub fn crate_root(self, db: &dyn HirDatabase) -> Module {
455 let def_map = db.crate_def_map(self.id.krate());
456 Module { id: def_map.module_id(def_map.root()) }
459 /// Iterates over all child modules.
460 pub fn children(self, db: &dyn HirDatabase) -> impl Iterator<Item = Module> {
461 let def_map = self.id.def_map(db.upcast());
462 let children = def_map[self.id.local_id]
465 .map(|(_, module_id)| Module { id: def_map.module_id(*module_id) })
466 .collect::<Vec<_>>();
470 /// Finds a parent module.
471 pub fn parent(self, db: &dyn HirDatabase) -> Option<Module> {
472 // FIXME: handle block expressions as modules (their parent is in a different DefMap)
473 let def_map = self.id.def_map(db.upcast());
474 let parent_id = def_map[self.id.local_id].parent?;
475 Some(Module { id: def_map.module_id(parent_id) })
478 pub fn path_to_root(self, db: &dyn HirDatabase) -> Vec<Module> {
479 let mut res = vec![self];
481 while let Some(next) = curr.parent(db) {
488 /// Returns a `ModuleScope`: a set of items, visible in this module.
491 db: &dyn HirDatabase,
492 visible_from: Option<Module>,
493 ) -> Vec<(Name, ScopeDef)> {
494 self.id.def_map(db.upcast())[self.id.local_id]
497 .filter_map(|(name, def)| {
498 if let Some(m) = visible_from {
500 def.filter_visibility(|vis| vis.is_visible_from(db.upcast(), m.id));
501 if filtered.is_none() && !def.is_none() {
504 Some((name, filtered))
510 .flat_map(|(name, def)| {
511 ScopeDef::all_items(def).into_iter().map(move |item| (name.clone(), item))
516 pub fn diagnostics(self, db: &dyn HirDatabase, acc: &mut Vec<AnyDiagnostic>) {
517 let _p = profile::span("Module::diagnostics").detail(|| {
518 format!("{:?}", self.name(db).map_or("<unknown>".into(), |name| name.to_string()))
520 let def_map = self.id.def_map(db.upcast());
521 for diag in def_map.diagnostics() {
522 if diag.in_module != self.id.local_id {
523 // FIXME: This is accidentally quadratic.
527 DefDiagnosticKind::UnresolvedModule { ast: declaration, candidate } => {
528 let decl = declaration.to_node(db.upcast());
531 decl: InFile::new(declaration.file_id, AstPtr::new(&decl)),
532 candidate: candidate.clone(),
537 DefDiagnosticKind::UnresolvedExternCrate { ast } => {
538 let item = ast.to_node(db.upcast());
540 UnresolvedExternCrate {
541 decl: InFile::new(ast.file_id, AstPtr::new(&item)),
547 DefDiagnosticKind::UnresolvedImport { id, index } => {
548 let file_id = id.file_id();
549 let item_tree = id.item_tree(db.upcast());
550 let import = &item_tree[id.value];
552 let use_tree = import.use_tree_to_ast(db.upcast(), file_id, *index);
554 UnresolvedImport { decl: InFile::new(file_id, AstPtr::new(&use_tree)) }
559 DefDiagnosticKind::UnconfiguredCode { ast, cfg, opts } => {
560 let item = ast.to_node(db.upcast());
563 node: ast.with_value(AstPtr::new(&item).into()),
571 DefDiagnosticKind::UnresolvedProcMacro { ast } => {
572 let mut precise_location = None;
573 let (node, name) = match ast {
574 MacroCallKind::FnLike { ast_id, .. } => {
575 let node = ast_id.to_node(db.upcast());
576 (ast_id.with_value(SyntaxNodePtr::from(AstPtr::new(&node))), None)
578 MacroCallKind::Derive { ast_id, derive_name, .. } => {
579 let node = ast_id.to_node(db.upcast());
581 // Compute the precise location of the macro name's token in the derive
583 // FIXME: This does not handle paths to the macro, but neither does the
586 node.attrs().filter_map(|attr| match attr.as_simple_call() {
587 Some((name, args)) if name == "derive" => Some(args),
590 'outer: for attr in derive_attrs {
592 attr.syntax().children_with_tokens().filter_map(|elem| {
594 syntax::NodeOrToken::Node(_) => None,
595 syntax::NodeOrToken::Token(tok) => Some(tok),
598 for token in tokens {
599 if token.kind() == SyntaxKind::IDENT
600 && token.text() == &**derive_name
602 precise_location = Some(token.text_range());
609 ast_id.with_value(SyntaxNodePtr::from(AstPtr::new(&node))),
610 Some(derive_name.clone()),
613 MacroCallKind::Attr { ast_id, invoc_attr_index, attr_name, .. } => {
614 let node = ast_id.to_node(db.upcast());
616 .doc_comments_and_attrs()
617 .nth((*invoc_attr_index) as usize)
618 .and_then(Either::right)
620 panic!("cannot find attribute #{}", invoc_attr_index)
623 ast_id.with_value(SyntaxNodePtr::from(AstPtr::new(&attr))),
624 Some(attr_name.clone()),
629 UnresolvedProcMacro {
632 macro_name: name.map(Into::into),
638 DefDiagnosticKind::UnresolvedMacroCall { ast, path } => {
639 let node = ast.to_node(db.upcast());
641 UnresolvedMacroCall {
642 macro_call: InFile::new(ast.file_id, AstPtr::new(&node)),
649 DefDiagnosticKind::MacroError { ast, message } => {
650 let node = match ast {
651 MacroCallKind::FnLike { ast_id, .. } => {
652 let node = ast_id.to_node(db.upcast());
653 ast_id.with_value(SyntaxNodePtr::from(AstPtr::new(&node)))
655 MacroCallKind::Derive { ast_id, .. } => {
656 // FIXME: point to the attribute instead, this creates very large diagnostics
657 let node = ast_id.to_node(db.upcast());
658 ast_id.with_value(SyntaxNodePtr::from(AstPtr::new(&node)))
660 MacroCallKind::Attr { ast_id, .. } => {
661 // FIXME: point to the attribute instead, this creates very large diagnostics
662 let node = ast_id.to_node(db.upcast());
663 ast_id.with_value(SyntaxNodePtr::from(AstPtr::new(&node)))
666 acc.push(MacroError { node, message: message.clone() }.into());
669 DefDiagnosticKind::UnimplementedBuiltinMacro { ast } => {
670 let node = ast.to_node(db.upcast());
671 // Must have a name, otherwise we wouldn't emit it.
672 let name = node.name().expect("unimplemented builtin macro with no name");
674 UnimplementedBuiltinMacro {
675 node: ast.with_value(SyntaxNodePtr::from(AstPtr::new(&name))),
680 DefDiagnosticKind::InvalidDeriveTarget { ast, id } => {
681 let node = ast.to_node(db.upcast());
682 let derive = node.attrs().nth(*id as usize);
686 InvalidDeriveTarget {
687 node: ast.with_value(SyntaxNodePtr::from(AstPtr::new(&derive))),
692 None => stdx::never!("derive diagnostic on item without derive attribute"),
695 DefDiagnosticKind::MalformedDerive { ast, id } => {
696 let node = ast.to_node(db.upcast());
697 let derive = node.attrs().nth(*id as usize);
702 node: ast.with_value(SyntaxNodePtr::from(AstPtr::new(&derive))),
707 None => stdx::never!("derive diagnostic on item without derive attribute"),
712 for decl in self.declarations(db) {
714 ModuleDef::Module(m) => {
715 // Only add diagnostics from inline modules
716 if def_map[m.id.local_id].origin.is_inline() {
717 m.diagnostics(db, acc)
720 _ => acc.extend(decl.diagnostics(db)),
724 for impl_def in self.impl_defs(db) {
725 for item in impl_def.items(db) {
726 let def: DefWithBody = match item {
727 AssocItem::Function(it) => it.into(),
728 AssocItem::Const(it) => it.into(),
729 AssocItem::TypeAlias(_) => continue,
732 def.diagnostics(db, acc);
737 pub fn declarations(self, db: &dyn HirDatabase) -> Vec<ModuleDef> {
738 let def_map = self.id.def_map(db.upcast());
739 let scope = &def_map[self.id.local_id].scope;
742 .map(ModuleDef::from)
743 .chain(scope.unnamed_consts().map(|id| ModuleDef::Const(Const::from(id))))
747 pub fn impl_defs(self, db: &dyn HirDatabase) -> Vec<Impl> {
748 let def_map = self.id.def_map(db.upcast());
749 def_map[self.id.local_id].scope.impls().map(Impl::from).collect()
752 /// Finds a path that can be used to refer to the given item from within
753 /// this module, if possible.
754 pub fn find_use_path(self, db: &dyn DefDatabase, item: impl Into<ItemInNs>) -> Option<ModPath> {
755 hir_def::find_path::find_path(db, item.into().into(), self.into())
758 /// Finds a path that can be used to refer to the given item from within
759 /// this module, if possible. This is used for returning import paths for use-statements.
760 pub fn find_use_path_prefixed(
762 db: &dyn DefDatabase,
763 item: impl Into<ItemInNs>,
764 prefix_kind: PrefixKind,
765 ) -> Option<ModPath> {
766 hir_def::find_path::find_path_prefixed(db, item.into().into(), self.into(), prefix_kind)
770 impl HasVisibility for Module {
771 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
772 let def_map = self.id.def_map(db.upcast());
773 let module_data = &def_map[self.id.local_id];
774 module_data.visibility
778 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
780 pub(crate) parent: VariantDef,
781 pub(crate) id: LocalFieldId,
784 #[derive(Debug, PartialEq, Eq)]
785 pub enum FieldSource {
786 Named(ast::RecordField),
787 Pos(ast::TupleField),
791 pub fn name(&self, db: &dyn HirDatabase) -> Name {
792 self.parent.variant_data(db).fields()[self.id].name.clone()
795 /// Returns the type as in the signature of the struct (i.e., with
796 /// placeholder types for type parameters). Only use this in the context of
797 /// the field definition.
798 pub fn ty(&self, db: &dyn HirDatabase) -> Type {
799 let var_id = self.parent.into();
800 let generic_def_id: GenericDefId = match self.parent {
801 VariantDef::Struct(it) => it.id.into(),
802 VariantDef::Union(it) => it.id.into(),
803 VariantDef::Variant(it) => it.parent.id.into(),
805 let substs = TyBuilder::type_params_subst(db, generic_def_id);
806 let ty = db.field_types(var_id)[self.id].clone().substitute(Interner, &substs);
807 Type::new(db, self.parent.module(db).id.krate(), var_id, ty)
810 pub fn parent_def(&self, _db: &dyn HirDatabase) -> VariantDef {
815 impl HasVisibility for Field {
816 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
817 let variant_data = self.parent.variant_data(db);
818 let visibility = &variant_data.fields()[self.id].visibility;
819 let parent_id: hir_def::VariantId = self.parent.into();
820 visibility.resolve(db.upcast(), &parent_id.resolver(db.upcast()))
824 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
826 pub(crate) id: StructId,
830 pub fn module(self, db: &dyn HirDatabase) -> Module {
831 Module { id: self.id.lookup(db.upcast()).container }
834 pub fn name(self, db: &dyn HirDatabase) -> Name {
835 db.struct_data(self.id).name.clone()
838 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
839 db.struct_data(self.id)
843 .map(|(id, _)| Field { parent: self.into(), id })
847 pub fn ty(self, db: &dyn HirDatabase) -> Type {
848 Type::from_def(db, self.id.lookup(db.upcast()).container.krate(), self.id)
851 pub fn repr(self, db: &dyn HirDatabase) -> Option<ReprKind> {
852 db.struct_data(self.id).repr.clone()
855 pub fn kind(self, db: &dyn HirDatabase) -> StructKind {
856 self.variant_data(db).kind()
859 fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
860 db.struct_data(self.id).variant_data.clone()
864 impl HasVisibility for Struct {
865 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
866 db.struct_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
870 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
872 pub(crate) id: UnionId,
876 pub fn name(self, db: &dyn HirDatabase) -> Name {
877 db.union_data(self.id).name.clone()
880 pub fn module(self, db: &dyn HirDatabase) -> Module {
881 Module { id: self.id.lookup(db.upcast()).container }
884 pub fn ty(self, db: &dyn HirDatabase) -> Type {
885 Type::from_def(db, self.id.lookup(db.upcast()).container.krate(), self.id)
888 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
889 db.union_data(self.id)
893 .map(|(id, _)| Field { parent: self.into(), id })
897 fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
898 db.union_data(self.id).variant_data.clone()
902 impl HasVisibility for Union {
903 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
904 db.union_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
908 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
910 pub(crate) id: EnumId,
914 pub fn module(self, db: &dyn HirDatabase) -> Module {
915 Module { id: self.id.lookup(db.upcast()).container }
918 pub fn name(self, db: &dyn HirDatabase) -> Name {
919 db.enum_data(self.id).name.clone()
922 pub fn variants(self, db: &dyn HirDatabase) -> Vec<Variant> {
923 db.enum_data(self.id).variants.iter().map(|(id, _)| Variant { parent: self, id }).collect()
926 pub fn ty(self, db: &dyn HirDatabase) -> Type {
927 Type::from_def(db, self.id.lookup(db.upcast()).container.krate(), self.id)
931 impl HasVisibility for Enum {
932 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
933 db.enum_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
937 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
939 pub(crate) parent: Enum,
940 pub(crate) id: LocalEnumVariantId,
944 pub fn module(self, db: &dyn HirDatabase) -> Module {
945 self.parent.module(db)
948 pub fn parent_enum(self, _db: &dyn HirDatabase) -> Enum {
952 pub fn name(self, db: &dyn HirDatabase) -> Name {
953 db.enum_data(self.parent.id).variants[self.id].name.clone()
956 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
957 self.variant_data(db)
960 .map(|(id, _)| Field { parent: self.into(), id })
964 pub fn kind(self, db: &dyn HirDatabase) -> StructKind {
965 self.variant_data(db).kind()
968 pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
969 db.enum_data(self.parent.id).variants[self.id].variant_data.clone()
973 /// Variants inherit visibility from the parent enum.
974 impl HasVisibility for Variant {
975 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
976 self.parent_enum(db).visibility(db)
981 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
987 impl_from!(Struct, Union, Enum for Adt);
990 pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
991 let subst = db.generic_defaults(self.into());
992 subst.iter().any(|ty| ty.skip_binders().is_unknown())
995 /// Turns this ADT into a type. Any type parameters of the ADT will be
996 /// turned into unknown types, which is good for e.g. finding the most
997 /// general set of completions, but will not look very nice when printed.
998 pub fn ty(self, db: &dyn HirDatabase) -> Type {
999 let id = AdtId::from(self);
1000 Type::from_def(db, id.module(db.upcast()).krate(), id)
1003 pub fn module(self, db: &dyn HirDatabase) -> Module {
1005 Adt::Struct(s) => s.module(db),
1006 Adt::Union(s) => s.module(db),
1007 Adt::Enum(e) => e.module(db),
1011 pub fn name(self, db: &dyn HirDatabase) -> Name {
1013 Adt::Struct(s) => s.name(db),
1014 Adt::Union(u) => u.name(db),
1015 Adt::Enum(e) => e.name(db),
1020 impl HasVisibility for Adt {
1021 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1023 Adt::Struct(it) => it.visibility(db),
1024 Adt::Union(it) => it.visibility(db),
1025 Adt::Enum(it) => it.visibility(db),
1030 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1031 pub enum VariantDef {
1036 impl_from!(Struct, Union, Variant for VariantDef);
1039 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
1041 VariantDef::Struct(it) => it.fields(db),
1042 VariantDef::Union(it) => it.fields(db),
1043 VariantDef::Variant(it) => it.fields(db),
1047 pub fn module(self, db: &dyn HirDatabase) -> Module {
1049 VariantDef::Struct(it) => it.module(db),
1050 VariantDef::Union(it) => it.module(db),
1051 VariantDef::Variant(it) => it.module(db),
1055 pub fn name(&self, db: &dyn HirDatabase) -> Name {
1057 VariantDef::Struct(s) => s.name(db),
1058 VariantDef::Union(u) => u.name(db),
1059 VariantDef::Variant(e) => e.name(db),
1063 pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
1065 VariantDef::Struct(it) => it.variant_data(db),
1066 VariantDef::Union(it) => it.variant_data(db),
1067 VariantDef::Variant(it) => it.variant_data(db),
1072 /// The defs which have a body.
1073 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1074 pub enum DefWithBody {
1079 impl_from!(Function, Const, Static for DefWithBody);
1082 pub fn module(self, db: &dyn HirDatabase) -> Module {
1084 DefWithBody::Const(c) => c.module(db),
1085 DefWithBody::Function(f) => f.module(db),
1086 DefWithBody::Static(s) => s.module(db),
1090 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1092 DefWithBody::Function(f) => Some(f.name(db)),
1093 DefWithBody::Static(s) => Some(s.name(db)),
1094 DefWithBody::Const(c) => c.name(db),
1098 /// Returns the type this def's body has to evaluate to.
1099 pub fn body_type(self, db: &dyn HirDatabase) -> Type {
1101 DefWithBody::Function(it) => it.ret_type(db),
1102 DefWithBody::Static(it) => it.ty(db),
1103 DefWithBody::Const(it) => it.ty(db),
1107 pub fn diagnostics(self, db: &dyn HirDatabase, acc: &mut Vec<AnyDiagnostic>) {
1108 let krate = self.module(db).id.krate();
1110 let source_map = db.body_with_source_map(self.into()).1;
1111 for diag in source_map.diagnostics() {
1113 BodyDiagnostic::InactiveCode { node, cfg, opts } => acc.push(
1114 InactiveCode { node: node.clone(), cfg: cfg.clone(), opts: opts.clone() }
1117 BodyDiagnostic::MacroError { node, message } => acc.push(
1119 node: node.clone().map(|it| it.into()),
1120 message: message.to_string(),
1124 BodyDiagnostic::UnresolvedProcMacro { node } => acc.push(
1125 UnresolvedProcMacro {
1126 node: node.clone().map(|it| it.into()),
1127 precise_location: None,
1132 BodyDiagnostic::UnresolvedMacroCall { node, path } => acc.push(
1133 UnresolvedMacroCall { macro_call: node.clone(), path: path.clone() }.into(),
1138 let infer = db.infer(self.into());
1139 let source_map = Lazy::new(|| db.body_with_source_map(self.into()).1);
1140 for d in &infer.diagnostics {
1142 hir_ty::InferenceDiagnostic::NoSuchField { expr } => {
1143 let field = source_map.field_syntax(*expr);
1144 acc.push(NoSuchField { field }.into())
1146 hir_ty::InferenceDiagnostic::BreakOutsideOfLoop { expr } => {
1147 let expr = source_map
1149 .expect("break outside of loop in synthetic syntax");
1150 acc.push(BreakOutsideOfLoop { expr }.into())
1155 for expr in hir_ty::diagnostics::missing_unsafe(db, self.into()) {
1156 match source_map.expr_syntax(expr) {
1157 Ok(expr) => acc.push(MissingUnsafe { expr }.into()),
1158 Err(SyntheticSyntax) => {
1159 // FIXME: Here and eslwhere in this file, the `expr` was
1160 // desugared, report or assert that this doesn't happen.
1165 for diagnostic in BodyValidationDiagnostic::collect(db, self.into()) {
1167 BodyValidationDiagnostic::RecordMissingFields {
1172 let variant_data = variant.variant_data(db.upcast());
1173 let missed_fields = missed_fields
1175 .map(|idx| variant_data.fields()[idx].name.clone())
1179 Either::Left(record_expr) => match source_map.expr_syntax(record_expr) {
1181 let root = source_ptr.file_syntax(db.upcast());
1182 if let ast::Expr::RecordExpr(record_expr) =
1183 &source_ptr.value.to_node(&root)
1185 if record_expr.record_expr_field_list().is_some() {
1188 file: source_ptr.file_id,
1189 field_list_parent: Either::Left(AstPtr::new(
1192 field_list_parent_path: record_expr
1194 .map(|path| AstPtr::new(&path)),
1202 Err(SyntheticSyntax) => (),
1204 Either::Right(record_pat) => match source_map.pat_syntax(record_pat) {
1206 if let Some(expr) = source_ptr.value.as_ref().left() {
1207 let root = source_ptr.file_syntax(db.upcast());
1208 if let ast::Pat::RecordPat(record_pat) = expr.to_node(&root) {
1209 if record_pat.record_pat_field_list().is_some() {
1212 file: source_ptr.file_id,
1213 field_list_parent: Either::Right(AstPtr::new(
1216 field_list_parent_path: record_pat
1218 .map(|path| AstPtr::new(&path)),
1227 Err(SyntheticSyntax) => (),
1231 BodyValidationDiagnostic::ReplaceFilterMapNextWithFindMap { method_call_expr } => {
1232 if let Ok(next_source_ptr) = source_map.expr_syntax(method_call_expr) {
1234 ReplaceFilterMapNextWithFindMap {
1235 file: next_source_ptr.file_id,
1236 next_expr: next_source_ptr.value,
1242 BodyValidationDiagnostic::MismatchedArgCount { call_expr, expected, found } => {
1243 match source_map.expr_syntax(call_expr) {
1244 Ok(source_ptr) => acc.push(
1245 MismatchedArgCount { call_expr: source_ptr, expected, found }.into(),
1247 Err(SyntheticSyntax) => (),
1250 BodyValidationDiagnostic::RemoveThisSemicolon { expr } => {
1251 match source_map.expr_syntax(expr) {
1252 Ok(expr) => acc.push(RemoveThisSemicolon { expr }.into()),
1253 Err(SyntheticSyntax) => (),
1256 BodyValidationDiagnostic::MissingOkOrSomeInTailExpr { expr, required } => {
1257 match source_map.expr_syntax(expr) {
1258 Ok(expr) => acc.push(
1259 MissingOkOrSomeInTailExpr {
1262 expected: self.body_type(db),
1266 Err(SyntheticSyntax) => (),
1269 BodyValidationDiagnostic::MissingMatchArms { match_expr } => {
1270 match source_map.expr_syntax(match_expr) {
1272 let root = source_ptr.file_syntax(db.upcast());
1273 if let ast::Expr::MatchExpr(match_expr) =
1274 &source_ptr.value.to_node(&root)
1276 if let (Some(match_expr), Some(arms)) =
1277 (match_expr.expr(), match_expr.match_arm_list())
1281 file: source_ptr.file_id,
1282 match_expr: AstPtr::new(&match_expr),
1283 arms: AstPtr::new(&arms),
1290 Err(SyntheticSyntax) => (),
1293 BodyValidationDiagnostic::AddReferenceHere { arg_expr, mutability } => {
1294 match source_map.expr_syntax(arg_expr) {
1295 Ok(expr) => acc.push(AddReferenceHere { expr, mutability }.into()),
1296 Err(SyntheticSyntax) => (),
1302 let def: ModuleDef = match self {
1303 DefWithBody::Function(it) => it.into(),
1304 DefWithBody::Static(it) => it.into(),
1305 DefWithBody::Const(it) => it.into(),
1307 for diag in hir_ty::diagnostics::incorrect_case(db, krate, def.into()) {
1308 acc.push(diag.into())
1313 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1314 pub struct Function {
1315 pub(crate) id: FunctionId,
1319 pub fn module(self, db: &dyn HirDatabase) -> Module {
1320 self.id.lookup(db.upcast()).module(db.upcast()).into()
1323 pub fn name(self, db: &dyn HirDatabase) -> Name {
1324 db.function_data(self.id).name.clone()
1327 /// Get this function's return type
1328 pub fn ret_type(self, db: &dyn HirDatabase) -> Type {
1329 let resolver = self.id.resolver(db.upcast());
1330 let krate = self.id.lookup(db.upcast()).container.module(db.upcast()).krate();
1331 let ret_type = &db.function_data(self.id).ret_type;
1332 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
1333 let ty = ctx.lower_ty(ret_type);
1334 Type::new_with_resolver_inner(db, krate, &resolver, ty)
1337 pub fn self_param(self, db: &dyn HirDatabase) -> Option<SelfParam> {
1338 if !db.function_data(self.id).has_self_param() {
1341 Some(SelfParam { func: self.id })
1344 pub fn assoc_fn_params(self, db: &dyn HirDatabase) -> Vec<Param> {
1345 let resolver = self.id.resolver(db.upcast());
1346 let krate = self.id.lookup(db.upcast()).container.module(db.upcast()).krate();
1347 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
1348 let environment = db.trait_environment(self.id.into());
1349 db.function_data(self.id)
1353 .map(|(idx, (_, type_ref))| {
1354 let ty = Type { krate, env: environment.clone(), ty: ctx.lower_ty(type_ref) };
1355 Param { func: self, ty, idx }
1360 pub fn method_params(self, db: &dyn HirDatabase) -> Option<Vec<Param>> {
1361 if self.self_param(db).is_none() {
1364 let mut res = self.assoc_fn_params(db);
1369 pub fn is_unsafe(self, db: &dyn HirDatabase) -> bool {
1370 db.function_data(self.id).is_unsafe()
1373 pub fn is_const(self, db: &dyn HirDatabase) -> bool {
1374 db.function_data(self.id).is_const()
1377 pub fn is_async(self, db: &dyn HirDatabase) -> bool {
1378 db.function_data(self.id).is_async()
1381 /// Whether this function declaration has a definition.
1383 /// This is false in the case of required (not provided) trait methods.
1384 pub fn has_body(self, db: &dyn HirDatabase) -> bool {
1385 db.function_data(self.id).has_body()
1388 /// A textual representation of the HIR of this function for debugging purposes.
1389 pub fn debug_hir(self, db: &dyn HirDatabase) -> String {
1390 let body = db.body(self.id.into());
1392 let mut result = String::new();
1393 format_to!(result, "HIR expressions in the body of `{}`:\n", self.name(db));
1394 for (id, expr) in body.exprs.iter() {
1395 format_to!(result, "{:?}: {:?}\n", id, expr);
1402 // Note: logically, this belongs to `hir_ty`, but we are not using it there yet.
1409 impl From<hir_ty::Mutability> for Access {
1410 fn from(mutability: hir_ty::Mutability) -> Access {
1412 hir_ty::Mutability::Not => Access::Shared,
1413 hir_ty::Mutability::Mut => Access::Exclusive,
1418 #[derive(Clone, Debug)]
1421 /// The index in parameter list, including self parameter.
1427 pub fn ty(&self) -> &Type {
1431 pub fn name(&self, db: &dyn HirDatabase) -> Option<Name> {
1432 db.function_data(self.func.id).params[self.idx].0.clone()
1435 pub fn as_local(&self, db: &dyn HirDatabase) -> Local {
1436 let parent = DefWithBodyId::FunctionId(self.func.into());
1437 let body = db.body(parent);
1438 Local { parent, pat_id: body.params[self.idx] }
1441 pub fn pattern_source(&self, db: &dyn HirDatabase) -> Option<ast::Pat> {
1442 self.source(db).and_then(|p| p.value.pat())
1445 pub fn source(&self, db: &dyn HirDatabase) -> Option<InFile<ast::Param>> {
1446 let InFile { file_id, value } = self.func.source(db)?;
1447 let params = value.param_list()?;
1448 if params.self_param().is_some() {
1449 params.params().nth(self.idx.checked_sub(1)?)
1451 params.params().nth(self.idx)
1453 .map(|value| InFile { file_id, value })
1457 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1458 pub struct SelfParam {
1463 pub fn access(self, db: &dyn HirDatabase) -> Access {
1464 let func_data = db.function_data(self.func);
1468 .map(|(_, param)| match &**param {
1469 TypeRef::Reference(.., mutability) => match mutability {
1470 hir_def::type_ref::Mutability::Shared => Access::Shared,
1471 hir_def::type_ref::Mutability::Mut => Access::Exclusive,
1475 .unwrap_or(Access::Owned)
1478 pub fn display(self, db: &dyn HirDatabase) -> &'static str {
1479 match self.access(db) {
1480 Access::Shared => "&self",
1481 Access::Exclusive => "&mut self",
1482 Access::Owned => "self",
1486 pub fn source(&self, db: &dyn HirDatabase) -> Option<InFile<ast::SelfParam>> {
1487 let InFile { file_id, value } = Function::from(self.func).source(db)?;
1490 .and_then(|params| params.self_param())
1491 .map(|value| InFile { file_id, value })
1494 pub fn ty(&self, db: &dyn HirDatabase) -> Type {
1495 let resolver = self.func.resolver(db.upcast());
1496 let krate = self.func.lookup(db.upcast()).container.module(db.upcast()).krate();
1497 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
1498 let environment = db.trait_environment(self.func.into());
1502 env: environment.clone(),
1503 ty: ctx.lower_ty(&db.function_data(self.func).params[0].1),
1508 impl HasVisibility for Function {
1509 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1510 let function_data = db.function_data(self.id);
1511 let visibility = &function_data.visibility;
1512 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1516 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1518 pub(crate) id: ConstId,
1522 pub fn module(self, db: &dyn HirDatabase) -> Module {
1523 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
1526 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1527 db.const_data(self.id).name.clone()
1530 pub fn value(self, db: &dyn HirDatabase) -> Option<ast::Expr> {
1531 self.source(db)?.value.body()
1534 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1535 let data = db.const_data(self.id);
1536 let resolver = self.id.resolver(db.upcast());
1537 let krate = self.id.lookup(db.upcast()).container.krate(db);
1538 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
1539 let ty = ctx.lower_ty(&data.type_ref);
1540 Type::new_with_resolver_inner(db, krate.id, &resolver, ty)
1543 pub fn eval(self, db: &dyn HirDatabase) -> Result<ComputedExpr, ConstEvalError> {
1544 let body = db.body(self.id.into());
1545 let root = &body.exprs[body.body_expr];
1546 let infer = db.infer_query(self.id.into());
1547 let infer = infer.as_ref();
1548 let result = eval_const(
1553 local_data: HashMap::default(),
1554 infer: &mut |x| infer[x].clone(),
1561 impl HasVisibility for Const {
1562 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1563 let function_data = db.const_data(self.id);
1564 let visibility = &function_data.visibility;
1565 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1569 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1571 pub(crate) id: StaticId,
1575 pub fn module(self, db: &dyn HirDatabase) -> Module {
1576 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
1579 pub fn name(self, db: &dyn HirDatabase) -> Name {
1580 db.static_data(self.id).name.clone()
1583 pub fn is_mut(self, db: &dyn HirDatabase) -> bool {
1584 db.static_data(self.id).mutable
1587 pub fn value(self, db: &dyn HirDatabase) -> Option<ast::Expr> {
1588 self.source(db)?.value.body()
1591 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1592 let data = db.static_data(self.id);
1593 let resolver = self.id.resolver(db.upcast());
1594 let krate = self.id.lookup(db.upcast()).container.module(db.upcast()).krate();
1595 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
1596 let ty = ctx.lower_ty(&data.type_ref);
1597 Type::new_with_resolver_inner(db, krate, &resolver, ty)
1601 impl HasVisibility for Static {
1602 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1603 db.static_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1607 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1609 pub(crate) id: TraitId,
1613 pub fn module(self, db: &dyn HirDatabase) -> Module {
1614 Module { id: self.id.lookup(db.upcast()).container }
1617 pub fn name(self, db: &dyn HirDatabase) -> Name {
1618 db.trait_data(self.id).name.clone()
1621 pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
1622 db.trait_data(self.id).items.iter().map(|(_name, it)| (*it).into()).collect()
1625 pub fn is_auto(self, db: &dyn HirDatabase) -> bool {
1626 db.trait_data(self.id).is_auto
1629 pub fn is_unsafe(&self, db: &dyn HirDatabase) -> bool {
1630 db.trait_data(self.id).is_unsafe
1634 impl HasVisibility for Trait {
1635 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1636 db.trait_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1640 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1641 pub struct TypeAlias {
1642 pub(crate) id: TypeAliasId,
1646 pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
1647 let subst = db.generic_defaults(self.id.into());
1648 subst.iter().any(|ty| ty.skip_binders().is_unknown())
1651 pub fn module(self, db: &dyn HirDatabase) -> Module {
1652 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
1655 pub fn type_ref(self, db: &dyn HirDatabase) -> Option<TypeRef> {
1656 db.type_alias_data(self.id).type_ref.as_deref().cloned()
1659 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1660 Type::from_def(db, self.id.lookup(db.upcast()).module(db.upcast()).krate(), self.id)
1663 pub fn name(self, db: &dyn HirDatabase) -> Name {
1664 db.type_alias_data(self.id).name.clone()
1668 impl HasVisibility for TypeAlias {
1669 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1670 let function_data = db.type_alias_data(self.id);
1671 let visibility = &function_data.visibility;
1672 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1676 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1677 pub struct BuiltinType {
1678 pub(crate) inner: hir_def::builtin_type::BuiltinType,
1682 pub fn str() -> BuiltinType {
1683 BuiltinType { inner: hir_def::builtin_type::BuiltinType::Str }
1686 pub fn ty(self, db: &dyn HirDatabase, module: Module) -> Type {
1687 let resolver = module.id.resolver(db.upcast());
1688 Type::new_with_resolver(db, &resolver, TyBuilder::builtin(self.inner))
1689 .expect("crate not present in resolver")
1692 pub fn name(self) -> Name {
1693 self.inner.as_name()
1696 pub fn is_int(&self) -> bool {
1697 matches!(self.inner, hir_def::builtin_type::BuiltinType::Int(_))
1700 pub fn is_uint(&self) -> bool {
1701 matches!(self.inner, hir_def::builtin_type::BuiltinType::Uint(_))
1704 pub fn is_float(&self) -> bool {
1705 matches!(self.inner, hir_def::builtin_type::BuiltinType::Float(_))
1708 pub fn is_char(&self) -> bool {
1709 matches!(self.inner, hir_def::builtin_type::BuiltinType::Char)
1712 pub fn is_str(&self) -> bool {
1713 matches!(self.inner, hir_def::builtin_type::BuiltinType::Str)
1717 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1718 pub enum MacroKind {
1719 /// `macro_rules!` or Macros 2.0 macro.
1721 /// A built-in or custom derive.
1723 /// A built-in function-like macro.
1725 /// A procedural attribute macro.
1727 /// A function-like procedural macro.
1731 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1732 pub struct MacroDef {
1733 pub(crate) id: MacroDefId,
1737 /// FIXME: right now, this just returns the root module of the crate that
1738 /// defines this macro. The reasons for this is that macros are expanded
1739 /// early, in `hir_expand`, where modules simply do not exist yet.
1740 pub fn module(self, db: &dyn HirDatabase) -> Option<Module> {
1741 let krate = self.id.krate;
1742 let def_map = db.crate_def_map(krate);
1743 let module_id = def_map.root();
1744 Some(Module { id: def_map.module_id(module_id) })
1747 /// XXX: this parses the file
1748 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1749 match self.source(db)?.value {
1750 Either::Left(it) => it.name().map(|it| it.as_name()),
1751 Either::Right(_) => {
1752 let krate = self.id.krate;
1753 let def_map = db.crate_def_map(krate);
1754 let (_, name) = def_map.exported_proc_macros().find(|&(id, _)| id == self.id)?;
1760 pub fn kind(&self) -> MacroKind {
1761 match self.id.kind {
1762 MacroDefKind::Declarative(_) => MacroKind::Declarative,
1763 MacroDefKind::BuiltIn(_, _) | MacroDefKind::BuiltInEager(_, _) => MacroKind::BuiltIn,
1764 MacroDefKind::BuiltInDerive(_, _) => MacroKind::Derive,
1765 MacroDefKind::BuiltInAttr(_, _) => MacroKind::Attr,
1766 MacroDefKind::ProcMacro(_, base_db::ProcMacroKind::CustomDerive, _) => {
1769 MacroDefKind::ProcMacro(_, base_db::ProcMacroKind::Attr, _) => MacroKind::Attr,
1770 MacroDefKind::ProcMacro(_, base_db::ProcMacroKind::FuncLike, _) => MacroKind::ProcMacro,
1774 pub fn is_fn_like(&self) -> bool {
1776 MacroKind::Declarative | MacroKind::BuiltIn | MacroKind::ProcMacro => true,
1777 MacroKind::Attr | MacroKind::Derive => false,
1781 pub fn is_attr(&self) -> bool {
1782 matches!(self.kind(), MacroKind::Attr)
1786 #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
1793 impl From<MacroDef> for ItemInNs {
1794 fn from(it: MacroDef) -> Self {
1799 impl From<ModuleDef> for ItemInNs {
1800 fn from(module_def: ModuleDef) -> Self {
1802 ModuleDef::Static(_) | ModuleDef::Const(_) | ModuleDef::Function(_) => {
1803 ItemInNs::Values(module_def)
1805 _ => ItemInNs::Types(module_def),
1811 pub fn as_module_def(self) -> Option<ModuleDef> {
1813 ItemInNs::Types(id) | ItemInNs::Values(id) => Some(id),
1814 ItemInNs::Macros(_) => None,
1818 /// Returns the crate defining this item (or `None` if `self` is built-in).
1819 pub fn krate(&self, db: &dyn HirDatabase) -> Option<Crate> {
1821 ItemInNs::Types(did) | ItemInNs::Values(did) => did.module(db).map(|m| m.krate()),
1822 ItemInNs::Macros(id) => id.module(db).map(|m| m.krate()),
1826 pub fn attrs(&self, db: &dyn HirDatabase) -> Option<AttrsWithOwner> {
1828 ItemInNs::Types(it) | ItemInNs::Values(it) => it.attrs(db),
1829 ItemInNs::Macros(it) => Some(it.attrs(db)),
1834 /// Invariant: `inner.as_assoc_item(db).is_some()`
1835 /// We do not actively enforce this invariant.
1836 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1837 pub enum AssocItem {
1840 TypeAlias(TypeAlias),
1843 pub enum AssocItemContainer {
1847 pub trait AsAssocItem {
1848 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem>;
1851 impl AsAssocItem for Function {
1852 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1853 as_assoc_item(db, AssocItem::Function, self.id)
1856 impl AsAssocItem for Const {
1857 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1858 as_assoc_item(db, AssocItem::Const, self.id)
1861 impl AsAssocItem for TypeAlias {
1862 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1863 as_assoc_item(db, AssocItem::TypeAlias, self.id)
1866 impl AsAssocItem for ModuleDef {
1867 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1869 ModuleDef::Function(it) => it.as_assoc_item(db),
1870 ModuleDef::Const(it) => it.as_assoc_item(db),
1871 ModuleDef::TypeAlias(it) => it.as_assoc_item(db),
1876 fn as_assoc_item<ID, DEF, CTOR, AST>(db: &dyn HirDatabase, ctor: CTOR, id: ID) -> Option<AssocItem>
1878 ID: Lookup<Data = AssocItemLoc<AST>>,
1880 CTOR: FnOnce(DEF) -> AssocItem,
1883 match id.lookup(db.upcast()).container {
1884 ItemContainerId::TraitId(_) | ItemContainerId::ImplId(_) => Some(ctor(DEF::from(id))),
1885 ItemContainerId::ModuleId(_) | ItemContainerId::ExternBlockId(_) => None,
1890 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1892 AssocItem::Function(it) => Some(it.name(db)),
1893 AssocItem::Const(it) => it.name(db),
1894 AssocItem::TypeAlias(it) => Some(it.name(db)),
1897 pub fn module(self, db: &dyn HirDatabase) -> Module {
1899 AssocItem::Function(f) => f.module(db),
1900 AssocItem::Const(c) => c.module(db),
1901 AssocItem::TypeAlias(t) => t.module(db),
1904 pub fn container(self, db: &dyn HirDatabase) -> AssocItemContainer {
1905 let container = match self {
1906 AssocItem::Function(it) => it.id.lookup(db.upcast()).container,
1907 AssocItem::Const(it) => it.id.lookup(db.upcast()).container,
1908 AssocItem::TypeAlias(it) => it.id.lookup(db.upcast()).container,
1911 ItemContainerId::TraitId(id) => AssocItemContainer::Trait(id.into()),
1912 ItemContainerId::ImplId(id) => AssocItemContainer::Impl(id.into()),
1913 ItemContainerId::ModuleId(_) | ItemContainerId::ExternBlockId(_) => {
1914 panic!("invalid AssocItem")
1919 pub fn containing_trait(self, db: &dyn HirDatabase) -> Option<Trait> {
1920 match self.container(db) {
1921 AssocItemContainer::Trait(t) => Some(t),
1926 pub fn containing_trait_impl(self, db: &dyn HirDatabase) -> Option<Trait> {
1927 match self.container(db) {
1928 AssocItemContainer::Impl(i) => i.trait_(db),
1933 pub fn containing_trait_or_trait_impl(self, db: &dyn HirDatabase) -> Option<Trait> {
1934 match self.container(db) {
1935 AssocItemContainer::Trait(t) => Some(t),
1936 AssocItemContainer::Impl(i) => i.trait_(db),
1941 impl HasVisibility for AssocItem {
1942 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1944 AssocItem::Function(f) => f.visibility(db),
1945 AssocItem::Const(c) => c.visibility(db),
1946 AssocItem::TypeAlias(t) => t.visibility(db),
1951 impl From<AssocItem> for ModuleDef {
1952 fn from(assoc: AssocItem) -> Self {
1954 AssocItem::Function(it) => ModuleDef::Function(it),
1955 AssocItem::Const(it) => ModuleDef::Const(it),
1956 AssocItem::TypeAlias(it) => ModuleDef::TypeAlias(it),
1961 #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
1962 pub enum GenericDef {
1966 TypeAlias(TypeAlias),
1968 // enum variants cannot have generics themselves, but their parent enums
1969 // can, and this makes some code easier to write
1971 // consts can have type parameters from their parents (i.e. associated consts of traits)
1976 Adt(Struct, Enum, Union),
1986 pub fn params(self, db: &dyn HirDatabase) -> Vec<GenericParam> {
1987 let generics = db.generic_params(self.into());
1988 let ty_params = generics
1991 .map(|(local_id, _)| TypeParam { id: TypeParamId { parent: self.into(), local_id } })
1992 .map(GenericParam::TypeParam);
1993 let lt_params = generics
1996 .map(|(local_id, _)| LifetimeParam {
1997 id: LifetimeParamId { parent: self.into(), local_id },
1999 .map(GenericParam::LifetimeParam);
2000 let const_params = generics
2003 .map(|(local_id, _)| ConstParam { id: ConstParamId { parent: self.into(), local_id } })
2004 .map(GenericParam::ConstParam);
2005 ty_params.chain(lt_params).chain(const_params).collect()
2008 pub fn type_params(self, db: &dyn HirDatabase) -> Vec<TypeParam> {
2009 let generics = db.generic_params(self.into());
2013 .map(|(local_id, _)| TypeParam { id: TypeParamId { parent: self.into(), local_id } })
2018 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2020 pub(crate) parent: DefWithBodyId,
2021 pub(crate) pat_id: PatId,
2025 pub fn is_param(self, db: &dyn HirDatabase) -> bool {
2026 let src = self.source(db);
2028 Either::Left(bind_pat) => {
2029 bind_pat.syntax().ancestors().any(|it| ast::Param::can_cast(it.kind()))
2031 Either::Right(_self_param) => true,
2035 pub fn as_self_param(self, db: &dyn HirDatabase) -> Option<SelfParam> {
2037 DefWithBodyId::FunctionId(func) if self.is_self(db) => Some(SelfParam { func }),
2042 // FIXME: why is this an option? It shouldn't be?
2043 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
2044 let body = db.body(self.parent);
2045 match &body[self.pat_id] {
2046 Pat::Bind { name, .. } => Some(name.clone()),
2051 pub fn is_self(self, db: &dyn HirDatabase) -> bool {
2052 self.name(db) == Some(name![self])
2055 pub fn is_mut(self, db: &dyn HirDatabase) -> bool {
2056 let body = db.body(self.parent);
2057 matches!(&body[self.pat_id], Pat::Bind { mode: BindingAnnotation::Mutable, .. })
2060 pub fn is_ref(self, db: &dyn HirDatabase) -> bool {
2061 let body = db.body(self.parent);
2064 Pat::Bind { mode: BindingAnnotation::Ref | BindingAnnotation::RefMut, .. }
2068 pub fn parent(self, _db: &dyn HirDatabase) -> DefWithBody {
2072 pub fn module(self, db: &dyn HirDatabase) -> Module {
2073 self.parent(db).module(db)
2076 pub fn ty(self, db: &dyn HirDatabase) -> Type {
2077 let def = self.parent;
2078 let infer = db.infer(def);
2079 let ty = infer[self.pat_id].clone();
2080 let krate = def.module(db.upcast()).krate();
2081 Type::new(db, krate, def, ty)
2084 pub fn source(self, db: &dyn HirDatabase) -> InFile<Either<ast::IdentPat, ast::SelfParam>> {
2085 let (_body, source_map) = db.body_with_source_map(self.parent);
2086 let src = source_map.pat_syntax(self.pat_id).unwrap(); // Hmm...
2087 let root = src.file_syntax(db.upcast());
2089 ast.map_left(|it| it.cast().unwrap().to_node(&root)).map_right(|it| it.to_node(&root))
2094 // FIXME: Wrong name? This is could also be a registered attribute
2095 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2096 pub struct BuiltinAttr {
2097 krate: Option<CrateId>,
2102 // FIXME: consider crates\hir_def\src\nameres\attr_resolution.rs?
2103 pub(crate) fn by_name(db: &dyn HirDatabase, krate: Crate, name: &str) -> Option<Self> {
2104 if let builtin @ Some(_) = Self::builtin(name) {
2107 let idx = db.crate_def_map(krate.id).registered_attrs().iter().position(|it| it == name)?;
2108 Some(BuiltinAttr { krate: Some(krate.id), idx })
2111 pub(crate) fn builtin(name: &str) -> Option<Self> {
2112 hir_def::builtin_attr::INERT_ATTRIBUTES
2114 .position(|tool| tool.name == name)
2115 .map(|idx| BuiltinAttr { krate: None, idx })
2118 pub fn name(&self, db: &dyn HirDatabase) -> SmolStr {
2119 // FIXME: Return a `Name` here
2121 Some(krate) => db.crate_def_map(krate).registered_attrs()[self.idx].clone(),
2122 None => SmolStr::new(hir_def::builtin_attr::INERT_ATTRIBUTES[self.idx].name),
2126 pub fn template(&self, _: &dyn HirDatabase) -> Option<AttributeTemplate> {
2129 None => Some(hir_def::builtin_attr::INERT_ATTRIBUTES[self.idx].template),
2134 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2135 pub struct ToolModule {
2136 krate: Option<CrateId>,
2141 // FIXME: consider crates\hir_def\src\nameres\attr_resolution.rs?
2142 pub(crate) fn by_name(db: &dyn HirDatabase, krate: Crate, name: &str) -> Option<Self> {
2143 if let builtin @ Some(_) = Self::builtin(name) {
2146 let idx = db.crate_def_map(krate.id).registered_tools().iter().position(|it| it == name)?;
2147 Some(ToolModule { krate: Some(krate.id), idx })
2150 pub(crate) fn builtin(name: &str) -> Option<Self> {
2151 hir_def::builtin_attr::TOOL_MODULES
2153 .position(|&tool| tool == name)
2154 .map(|idx| ToolModule { krate: None, idx })
2157 pub fn name(&self, db: &dyn HirDatabase) -> SmolStr {
2158 // FIXME: Return a `Name` here
2160 Some(krate) => db.crate_def_map(krate).registered_tools()[self.idx].clone(),
2161 None => SmolStr::new(hir_def::builtin_attr::TOOL_MODULES[self.idx]),
2166 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2168 pub(crate) parent: DefWithBodyId,
2169 pub(crate) label_id: LabelId,
2173 pub fn module(self, db: &dyn HirDatabase) -> Module {
2174 self.parent(db).module(db)
2177 pub fn parent(self, _db: &dyn HirDatabase) -> DefWithBody {
2181 pub fn name(self, db: &dyn HirDatabase) -> Name {
2182 let body = db.body(self.parent);
2183 body[self.label_id].name.clone()
2186 pub fn source(self, db: &dyn HirDatabase) -> InFile<ast::Label> {
2187 let (_body, source_map) = db.body_with_source_map(self.parent);
2188 let src = source_map.label_syntax(self.label_id);
2189 let root = src.file_syntax(db.upcast());
2190 src.map(|ast| ast.to_node(&root))
2194 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2195 pub enum GenericParam {
2196 TypeParam(TypeParam),
2197 LifetimeParam(LifetimeParam),
2198 ConstParam(ConstParam),
2200 impl_from!(TypeParam, LifetimeParam, ConstParam for GenericParam);
2203 pub fn module(self, db: &dyn HirDatabase) -> Module {
2205 GenericParam::TypeParam(it) => it.module(db),
2206 GenericParam::LifetimeParam(it) => it.module(db),
2207 GenericParam::ConstParam(it) => it.module(db),
2211 pub fn name(self, db: &dyn HirDatabase) -> Name {
2213 GenericParam::TypeParam(it) => it.name(db),
2214 GenericParam::LifetimeParam(it) => it.name(db),
2215 GenericParam::ConstParam(it) => it.name(db),
2220 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2221 pub struct TypeParam {
2222 pub(crate) id: TypeParamId,
2226 pub fn name(self, db: &dyn HirDatabase) -> Name {
2227 let params = db.generic_params(self.id.parent);
2228 params.types[self.id.local_id].name.clone().unwrap_or_else(Name::missing)
2231 pub fn module(self, db: &dyn HirDatabase) -> Module {
2232 self.id.parent.module(db.upcast()).into()
2235 pub fn ty(self, db: &dyn HirDatabase) -> Type {
2236 let resolver = self.id.parent.resolver(db.upcast());
2237 let krate = self.id.parent.module(db.upcast()).krate();
2238 let ty = TyKind::Placeholder(hir_ty::to_placeholder_idx(db, self.id)).intern(Interner);
2239 Type::new_with_resolver_inner(db, krate, &resolver, ty)
2242 pub fn trait_bounds(self, db: &dyn HirDatabase) -> Vec<Trait> {
2243 db.generic_predicates_for_param(self.id, None)
2245 .filter_map(|pred| match &pred.skip_binders().skip_binders() {
2246 hir_ty::WhereClause::Implemented(trait_ref) => {
2247 Some(Trait::from(trait_ref.hir_trait_id()))
2254 pub fn default(self, db: &dyn HirDatabase) -> Option<Type> {
2255 let params = db.generic_defaults(self.id.parent);
2256 let local_idx = hir_ty::param_idx(db, self.id)?;
2257 let resolver = self.id.parent.resolver(db.upcast());
2258 let krate = self.id.parent.module(db.upcast()).krate();
2259 let ty = params.get(local_idx)?.clone();
2260 let subst = TyBuilder::type_params_subst(db, self.id.parent);
2261 let ty = ty.substitute(Interner, &subst_prefix(&subst, local_idx));
2262 Some(Type::new_with_resolver_inner(db, krate, &resolver, ty))
2266 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2267 pub struct LifetimeParam {
2268 pub(crate) id: LifetimeParamId,
2271 impl LifetimeParam {
2272 pub fn name(self, db: &dyn HirDatabase) -> Name {
2273 let params = db.generic_params(self.id.parent);
2274 params.lifetimes[self.id.local_id].name.clone()
2277 pub fn module(self, db: &dyn HirDatabase) -> Module {
2278 self.id.parent.module(db.upcast()).into()
2281 pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef {
2282 self.id.parent.into()
2286 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2287 pub struct ConstParam {
2288 pub(crate) id: ConstParamId,
2292 pub fn name(self, db: &dyn HirDatabase) -> Name {
2293 let params = db.generic_params(self.id.parent);
2294 params.consts[self.id.local_id].name.clone()
2297 pub fn module(self, db: &dyn HirDatabase) -> Module {
2298 self.id.parent.module(db.upcast()).into()
2301 pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef {
2302 self.id.parent.into()
2305 pub fn ty(self, db: &dyn HirDatabase) -> Type {
2306 let def = self.id.parent;
2307 let krate = def.module(db.upcast()).krate();
2308 Type::new(db, krate, def, db.const_param_ty(self.id))
2312 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2314 pub(crate) id: ImplId,
2318 pub fn all_in_crate(db: &dyn HirDatabase, krate: Crate) -> Vec<Impl> {
2319 let inherent = db.inherent_impls_in_crate(krate.id);
2320 let trait_ = db.trait_impls_in_crate(krate.id);
2322 inherent.all_impls().chain(trait_.all_impls()).map(Self::from).collect()
2325 pub fn all_for_type(db: &dyn HirDatabase, Type { krate, ty, .. }: Type) -> Vec<Impl> {
2326 let def_crates = match method_resolution::def_crates(db, &ty, krate) {
2327 Some(def_crates) => def_crates,
2328 None => return Vec::new(),
2331 let filter = |impl_def: &Impl| {
2332 let self_ty = impl_def.self_ty(db);
2333 let rref = self_ty.remove_ref();
2334 ty.equals_ctor(rref.as_ref().map_or(&self_ty.ty, |it| &it.ty))
2337 let fp = TyFingerprint::for_inherent_impl(&ty);
2340 None => return Vec::new(),
2343 let mut all = Vec::new();
2344 def_crates.iter().for_each(|&id| {
2346 db.inherent_impls_in_crate(id)
2354 for id in def_crates
2356 .flat_map(|&id| Crate { id }.transitive_reverse_dependencies(db))
2357 .map(|Crate { id }| id)
2358 .chain(def_crates.iter().copied())
2362 db.trait_impls_in_crate(id)
2363 .for_self_ty_without_blanket_impls(fp)
2371 pub fn all_for_trait(db: &dyn HirDatabase, trait_: Trait) -> Vec<Impl> {
2372 let krate = trait_.module(db).krate();
2373 let mut all = Vec::new();
2374 for Crate { id } in krate.transitive_reverse_dependencies(db).into_iter() {
2375 let impls = db.trait_impls_in_crate(id);
2376 all.extend(impls.for_trait(trait_.id).map(Self::from))
2381 // FIXME: the return type is wrong. This should be a hir version of
2382 // `TraitRef` (to account for parameters and qualifiers)
2383 pub fn trait_(self, db: &dyn HirDatabase) -> Option<Trait> {
2384 let trait_ref = db.impl_trait(self.id)?.skip_binders().clone();
2385 let id = hir_ty::from_chalk_trait_id(trait_ref.trait_id);
2389 pub fn self_ty(self, db: &dyn HirDatabase) -> Type {
2390 let impl_data = db.impl_data(self.id);
2391 let resolver = self.id.resolver(db.upcast());
2392 let krate = self.id.lookup(db.upcast()).container.krate();
2393 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
2394 let ty = ctx.lower_ty(&impl_data.self_ty);
2395 Type::new_with_resolver_inner(db, krate, &resolver, ty)
2398 pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
2399 db.impl_data(self.id).items.iter().map(|it| (*it).into()).collect()
2402 pub fn is_negative(self, db: &dyn HirDatabase) -> bool {
2403 db.impl_data(self.id).is_negative
2406 pub fn module(self, db: &dyn HirDatabase) -> Module {
2407 self.id.lookup(db.upcast()).container.into()
2410 pub fn is_builtin_derive(self, db: &dyn HirDatabase) -> Option<InFile<ast::Attr>> {
2411 let src = self.source(db)?;
2412 let item = src.file_id.is_builtin_derive(db.upcast())?;
2413 let hygenic = hir_expand::hygiene::Hygiene::new(db.upcast(), item.file_id);
2415 // FIXME: handle `cfg_attr`
2420 let path = ModPath::from_src(db.upcast(), it.path()?, &hygenic)?;
2421 if path.as_ident()?.to_smol_str() == "derive" {
2429 Some(item.with_value(attr))
2433 #[derive(Clone, PartialEq, Eq, Debug)]
2436 env: Arc<TraitEnvironment>,
2441 pub(crate) fn new_with_resolver(
2442 db: &dyn HirDatabase,
2443 resolver: &Resolver,
2446 let krate = resolver.krate()?;
2447 Some(Type::new_with_resolver_inner(db, krate, resolver, ty))
2449 pub(crate) fn new_with_resolver_inner(
2450 db: &dyn HirDatabase,
2452 resolver: &Resolver,
2455 let environment = resolver
2457 .map_or_else(|| Arc::new(TraitEnvironment::empty(krate)), |d| db.trait_environment(d));
2458 Type { krate, env: environment, ty }
2461 fn new(db: &dyn HirDatabase, krate: CrateId, lexical_env: impl HasResolver, ty: Ty) -> Type {
2462 let resolver = lexical_env.resolver(db.upcast());
2463 let environment = resolver
2465 .map_or_else(|| Arc::new(TraitEnvironment::empty(krate)), |d| db.trait_environment(d));
2466 Type { krate, env: environment, ty }
2470 db: &dyn HirDatabase,
2472 def: impl HasResolver + Into<TyDefId>,
2474 let ty = TyBuilder::def_ty(db, def.into()).fill_with_unknown().build();
2475 Type::new(db, krate, def, ty)
2478 pub fn new_slice(ty: Type) -> Type {
2479 Type { krate: ty.krate, env: ty.env, ty: TyBuilder::slice(ty.ty) }
2482 pub fn is_unit(&self) -> bool {
2483 matches!(self.ty.kind(Interner), TyKind::Tuple(0, ..))
2486 pub fn is_bool(&self) -> bool {
2487 matches!(self.ty.kind(Interner), TyKind::Scalar(Scalar::Bool))
2490 pub fn is_never(&self) -> bool {
2491 matches!(self.ty.kind(Interner), TyKind::Never)
2494 pub fn is_mutable_reference(&self) -> bool {
2495 matches!(self.ty.kind(Interner), TyKind::Ref(hir_ty::Mutability::Mut, ..))
2498 pub fn is_reference(&self) -> bool {
2499 matches!(self.ty.kind(Interner), TyKind::Ref(..))
2502 pub fn is_usize(&self) -> bool {
2503 matches!(self.ty.kind(Interner), TyKind::Scalar(Scalar::Uint(UintTy::Usize)))
2506 pub fn remove_ref(&self) -> Option<Type> {
2507 match &self.ty.kind(Interner) {
2508 TyKind::Ref(.., ty) => Some(self.derived(ty.clone())),
2513 pub fn strip_references(&self) -> Type {
2514 self.derived(self.ty.strip_references().clone())
2517 pub fn is_unknown(&self) -> bool {
2518 self.ty.is_unknown()
2521 /// Checks that particular type `ty` implements `std::future::Future`.
2522 /// This function is used in `.await` syntax completion.
2523 pub fn impls_future(&self, db: &dyn HirDatabase) -> bool {
2524 // No special case for the type of async block, since Chalk can figure it out.
2526 let krate = self.krate;
2528 let std_future_trait =
2529 db.lang_item(krate, SmolStr::new_inline("future_trait")).and_then(|it| it.as_trait());
2530 let std_future_trait = match std_future_trait {
2532 None => return false,
2536 Canonical { value: self.ty.clone(), binders: CanonicalVarKinds::empty(Interner) };
2537 method_resolution::implements_trait(
2546 /// Checks that particular type `ty` implements `std::ops::FnOnce`.
2548 /// This function can be used to check if a particular type is callable, since FnOnce is a
2549 /// supertrait of Fn and FnMut, so all callable types implements at least FnOnce.
2550 pub fn impls_fnonce(&self, db: &dyn HirDatabase) -> bool {
2551 let krate = self.krate;
2553 let fnonce_trait = match FnTrait::FnOnce.get_id(db, krate) {
2555 None => return false,
2559 Canonical { value: self.ty.clone(), binders: CanonicalVarKinds::empty(Interner) };
2560 method_resolution::implements_trait_unique(
2569 pub fn impls_trait(&self, db: &dyn HirDatabase, trait_: Trait, args: &[Type]) -> bool {
2570 let trait_ref = TyBuilder::trait_ref(db, trait_.id)
2571 .push(self.ty.clone())
2572 .fill(args.iter().map(|t| t.ty.clone()))
2575 let goal = Canonical {
2576 value: hir_ty::InEnvironment::new(&self.env.env, trait_ref.cast(Interner)),
2577 binders: CanonicalVarKinds::empty(Interner),
2580 db.trait_solve(self.krate, goal).is_some()
2583 pub fn normalize_trait_assoc_type(
2585 db: &dyn HirDatabase,
2589 let projection = TyBuilder::assoc_type_projection(db, alias.id)
2590 .push(self.ty.clone())
2591 .fill(args.iter().map(|t| t.ty.clone()))
2593 let goal = hir_ty::make_canonical(
2597 alias: AliasTy::Projection(projection),
2598 ty: TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0))
2603 [TyVariableKind::General].into_iter(),
2606 match db.trait_solve(self.krate, goal)? {
2607 Solution::Unique(s) => s
2612 .map(|ty| self.derived(ty.assert_ty_ref(Interner).clone())),
2613 Solution::Ambig(_) => None,
2617 pub fn is_copy(&self, db: &dyn HirDatabase) -> bool {
2618 let lang_item = db.lang_item(self.krate, SmolStr::new_inline("copy"));
2619 let copy_trait = match lang_item {
2620 Some(LangItemTarget::TraitId(it)) => it,
2623 self.impls_trait(db, copy_trait.into(), &[])
2626 pub fn as_callable(&self, db: &dyn HirDatabase) -> Option<Callable> {
2627 let def = self.ty.callable_def(db);
2629 let sig = self.ty.callable_sig(db)?;
2630 Some(Callable { ty: self.clone(), sig, def, is_bound_method: false })
2633 pub fn is_closure(&self) -> bool {
2634 matches!(&self.ty.kind(Interner), TyKind::Closure { .. })
2637 pub fn is_fn(&self) -> bool {
2638 matches!(&self.ty.kind(Interner), TyKind::FnDef(..) | TyKind::Function { .. })
2641 pub fn is_array(&self) -> bool {
2642 matches!(&self.ty.kind(Interner), TyKind::Array(..))
2645 pub fn is_packed(&self, db: &dyn HirDatabase) -> bool {
2646 let adt_id = match *self.ty.kind(Interner) {
2647 TyKind::Adt(hir_ty::AdtId(adt_id), ..) => adt_id,
2651 let adt = adt_id.into();
2653 Adt::Struct(s) => matches!(s.repr(db), Some(ReprKind::Packed)),
2658 pub fn is_raw_ptr(&self) -> bool {
2659 matches!(&self.ty.kind(Interner), TyKind::Raw(..))
2662 pub fn contains_unknown(&self) -> bool {
2663 return go(&self.ty);
2665 fn go(ty: &Ty) -> bool {
2666 match ty.kind(Interner) {
2667 TyKind::Error => true,
2669 TyKind::Adt(_, substs)
2670 | TyKind::AssociatedType(_, substs)
2671 | TyKind::Tuple(_, substs)
2672 | TyKind::OpaqueType(_, substs)
2673 | TyKind::FnDef(_, substs)
2674 | TyKind::Closure(_, substs) => {
2675 substs.iter(Interner).filter_map(|a| a.ty(Interner)).any(go)
2678 TyKind::Array(_ty, len) if len.is_unknown() => true,
2679 TyKind::Array(ty, _)
2681 | TyKind::Raw(_, ty)
2682 | TyKind::Ref(_, _, ty) => go(ty),
2687 | TyKind::Placeholder(_)
2688 | TyKind::BoundVar(_)
2689 | TyKind::InferenceVar(_, _)
2691 | TyKind::Function(_)
2693 | TyKind::Foreign(_)
2694 | TyKind::Generator(..)
2695 | TyKind::GeneratorWitness(..) => false,
2700 pub fn fields(&self, db: &dyn HirDatabase) -> Vec<(Field, Type)> {
2701 let (variant_id, substs) = match self.ty.kind(Interner) {
2702 TyKind::Adt(hir_ty::AdtId(AdtId::StructId(s)), substs) => ((*s).into(), substs),
2703 TyKind::Adt(hir_ty::AdtId(AdtId::UnionId(u)), substs) => ((*u).into(), substs),
2704 _ => return Vec::new(),
2707 db.field_types(variant_id)
2709 .map(|(local_id, ty)| {
2710 let def = Field { parent: variant_id.into(), id: local_id };
2711 let ty = ty.clone().substitute(Interner, substs);
2712 (def, self.derived(ty))
2717 pub fn tuple_fields(&self, _db: &dyn HirDatabase) -> Vec<Type> {
2718 if let TyKind::Tuple(_, substs) = &self.ty.kind(Interner) {
2721 .map(|ty| self.derived(ty.assert_ty_ref(Interner).clone()))
2728 pub fn autoderef<'a>(&'a self, db: &'a dyn HirDatabase) -> impl Iterator<Item = Type> + 'a {
2729 self.autoderef_(db).map(move |ty| self.derived(ty))
2732 pub fn autoderef_<'a>(&'a self, db: &'a dyn HirDatabase) -> impl Iterator<Item = Ty> + 'a {
2733 // There should be no inference vars in types passed here
2734 let canonical = hir_ty::replace_errors_with_variables(&self.ty);
2735 let environment = self.env.env.clone();
2736 let ty = InEnvironment { goal: canonical, environment };
2737 autoderef(db, Some(self.krate), ty).map(|canonical| canonical.value)
2740 // This would be nicer if it just returned an iterator, but that runs into
2741 // lifetime problems, because we need to borrow temp `CrateImplDefs`.
2742 pub fn iterate_assoc_items<T>(
2744 db: &dyn HirDatabase,
2746 mut callback: impl FnMut(AssocItem) -> Option<T>,
2748 let mut slot = None;
2749 self.iterate_assoc_items_dyn(db, krate, &mut |assoc_item_id| {
2750 slot = callback(assoc_item_id.into());
2756 fn iterate_assoc_items_dyn(
2758 db: &dyn HirDatabase,
2760 callback: &mut dyn FnMut(AssocItemId) -> bool,
2762 let def_crates = match method_resolution::def_crates(db, &self.ty, krate.id) {
2766 for krate in def_crates {
2767 let impls = db.inherent_impls_in_crate(krate);
2769 for impl_def in impls.for_self_ty(&self.ty) {
2770 for &item in db.impl_data(*impl_def).items.iter() {
2779 pub fn type_arguments(&self) -> impl Iterator<Item = Type> + '_ {
2784 .flat_map(|(_, substs)| substs.iter(Interner))
2785 .filter_map(|arg| arg.ty(Interner).cloned())
2786 .map(move |ty| self.derived(ty))
2789 pub fn iterate_method_candidates<T>(
2791 db: &dyn HirDatabase,
2793 traits_in_scope: &FxHashSet<TraitId>,
2794 name: Option<&Name>,
2795 mut callback: impl FnMut(Type, Function) -> Option<T>,
2797 let _p = profile::span("iterate_method_candidates");
2798 let mut slot = None;
2800 self.iterate_method_candidates_dyn(
2805 &mut |ty, assoc_item_id| {
2806 if let AssocItemId::FunctionId(func) = assoc_item_id {
2807 if let Some(res) = callback(self.derived(ty.clone()), func.into()) {
2809 return ControlFlow::Break(());
2812 ControlFlow::Continue(())
2818 fn iterate_method_candidates_dyn(
2820 db: &dyn HirDatabase,
2822 traits_in_scope: &FxHashSet<TraitId>,
2823 name: Option<&Name>,
2824 callback: &mut dyn FnMut(&Ty, AssocItemId) -> ControlFlow<()>,
2826 // There should be no inference vars in types passed here
2827 let canonical = hir_ty::replace_errors_with_variables(&self.ty);
2829 let env = self.env.clone();
2830 let krate = krate.id;
2832 method_resolution::iterate_method_candidates_dyn(
2840 method_resolution::LookupMode::MethodCall,
2841 &mut |ty, id| callback(&ty.value, id),
2845 pub fn iterate_path_candidates<T>(
2847 db: &dyn HirDatabase,
2849 traits_in_scope: &FxHashSet<TraitId>,
2850 name: Option<&Name>,
2851 mut callback: impl FnMut(Type, AssocItem) -> Option<T>,
2853 let _p = profile::span("iterate_path_candidates");
2854 let mut slot = None;
2855 self.iterate_path_candidates_dyn(
2860 &mut |ty, assoc_item_id| {
2861 if let Some(res) = callback(self.derived(ty.clone()), assoc_item_id.into()) {
2863 return ControlFlow::Break(());
2865 ControlFlow::Continue(())
2871 fn iterate_path_candidates_dyn(
2873 db: &dyn HirDatabase,
2875 traits_in_scope: &FxHashSet<TraitId>,
2876 name: Option<&Name>,
2877 callback: &mut dyn FnMut(&Ty, AssocItemId) -> ControlFlow<()>,
2879 let canonical = hir_ty::replace_errors_with_variables(&self.ty);
2881 let env = self.env.clone();
2882 let krate = krate.id;
2884 method_resolution::iterate_method_candidates_dyn(
2892 method_resolution::LookupMode::Path,
2893 &mut |ty, id| callback(&ty.value, id),
2897 pub fn as_adt(&self) -> Option<Adt> {
2898 let (adt, _subst) = self.ty.as_adt()?;
2902 pub fn as_builtin(&self) -> Option<BuiltinType> {
2903 self.ty.as_builtin().map(|inner| BuiltinType { inner })
2906 pub fn as_dyn_trait(&self) -> Option<Trait> {
2907 self.ty.dyn_trait().map(Into::into)
2910 /// If a type can be represented as `dyn Trait`, returns all traits accessible via this type,
2911 /// or an empty iterator otherwise.
2912 pub fn applicable_inherent_traits<'a>(
2914 db: &'a dyn HirDatabase,
2915 ) -> impl Iterator<Item = Trait> + 'a {
2916 let _p = profile::span("applicable_inherent_traits");
2918 .filter_map(|ty| ty.dyn_trait())
2919 .flat_map(move |dyn_trait_id| hir_ty::all_super_traits(db.upcast(), dyn_trait_id))
2923 pub fn env_traits<'a>(&'a self, db: &'a dyn HirDatabase) -> impl Iterator<Item = Trait> + 'a {
2924 let _p = profile::span("env_traits");
2926 .filter(|ty| matches!(ty.kind(Interner), TyKind::Placeholder(_)))
2929 .traits_in_scope_from_clauses(ty)
2930 .flat_map(|t| hir_ty::all_super_traits(db.upcast(), t))
2935 pub fn as_impl_traits(&self, db: &dyn HirDatabase) -> Option<impl Iterator<Item = Trait>> {
2936 self.ty.impl_trait_bounds(db).map(|it| {
2937 it.into_iter().filter_map(|pred| match pred.skip_binders() {
2938 hir_ty::WhereClause::Implemented(trait_ref) => {
2939 Some(Trait::from(trait_ref.hir_trait_id()))
2946 pub fn as_associated_type_parent_trait(&self, db: &dyn HirDatabase) -> Option<Trait> {
2947 self.ty.associated_type_parent_trait(db).map(Into::into)
2950 fn derived(&self, ty: Ty) -> Type {
2951 Type { krate: self.krate, env: self.env.clone(), ty }
2954 pub fn walk(&self, db: &dyn HirDatabase, mut cb: impl FnMut(Type)) {
2955 // TypeWalk::walk for a Ty at first visits parameters and only after that the Ty itself.
2956 // We need a different order here.
2959 db: &dyn HirDatabase,
2961 substs: &Substitution,
2962 cb: &mut impl FnMut(Type),
2964 for ty in substs.iter(Interner).filter_map(|a| a.ty(Interner)) {
2965 walk_type(db, &type_.derived(ty.clone()), cb);
2970 db: &dyn HirDatabase,
2972 bounds: &[QuantifiedWhereClause],
2973 cb: &mut impl FnMut(Type),
2975 for pred in bounds {
2976 if let WhereClause::Implemented(trait_ref) = pred.skip_binders() {
2978 // skip the self type. it's likely the type we just got the bounds from
2980 trait_ref.substitution.iter(Interner).skip(1).filter_map(|a| a.ty(Interner))
2982 walk_type(db, &type_.derived(ty.clone()), cb);
2988 fn walk_type(db: &dyn HirDatabase, type_: &Type, cb: &mut impl FnMut(Type)) {
2989 let ty = type_.ty.strip_references();
2990 match ty.kind(Interner) {
2991 TyKind::Adt(_, substs) => {
2992 cb(type_.derived(ty.clone()));
2993 walk_substs(db, type_, substs, cb);
2995 TyKind::AssociatedType(_, substs) => {
2996 if ty.associated_type_parent_trait(db).is_some() {
2997 cb(type_.derived(ty.clone()));
2999 walk_substs(db, type_, substs, cb);
3001 TyKind::OpaqueType(_, subst) => {
3002 if let Some(bounds) = ty.impl_trait_bounds(db) {
3003 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
3006 walk_substs(db, type_, subst, cb);
3008 TyKind::Alias(AliasTy::Opaque(opaque_ty)) => {
3009 if let Some(bounds) = ty.impl_trait_bounds(db) {
3010 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
3013 walk_substs(db, type_, &opaque_ty.substitution, cb);
3015 TyKind::Placeholder(_) => {
3016 if let Some(bounds) = ty.impl_trait_bounds(db) {
3017 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
3020 TyKind::Dyn(bounds) => {
3023 &type_.derived(ty.clone()),
3024 bounds.bounds.skip_binders().interned(),
3029 TyKind::Ref(_, _, ty)
3030 | TyKind::Raw(_, ty)
3031 | TyKind::Array(ty, _)
3032 | TyKind::Slice(ty) => {
3033 walk_type(db, &type_.derived(ty.clone()), cb);
3036 TyKind::FnDef(_, substs)
3037 | TyKind::Tuple(_, substs)
3038 | TyKind::Closure(.., substs) => {
3039 walk_substs(db, type_, substs, cb);
3041 TyKind::Function(hir_ty::FnPointer { substitution, .. }) => {
3042 walk_substs(db, type_, &substitution.0, cb);
3049 walk_type(db, self, &mut cb);
3052 pub fn could_unify_with(&self, db: &dyn HirDatabase, other: &Type) -> bool {
3053 let tys = hir_ty::replace_errors_with_variables(&(self.ty.clone(), other.ty.clone()));
3054 could_unify(db, self.env.clone(), &tys)
3060 pub struct Callable {
3063 def: Option<CallableDefId>,
3064 pub(crate) is_bound_method: bool,
3067 pub enum CallableKind {
3069 TupleStruct(Struct),
3070 TupleEnumVariant(Variant),
3075 pub fn kind(&self) -> CallableKind {
3077 Some(CallableDefId::FunctionId(it)) => CallableKind::Function(it.into()),
3078 Some(CallableDefId::StructId(it)) => CallableKind::TupleStruct(it.into()),
3079 Some(CallableDefId::EnumVariantId(it)) => CallableKind::TupleEnumVariant(it.into()),
3080 None => CallableKind::Closure,
3083 pub fn receiver_param(&self, db: &dyn HirDatabase) -> Option<ast::SelfParam> {
3084 let func = match self.def {
3085 Some(CallableDefId::FunctionId(it)) if self.is_bound_method => it,
3088 let src = func.lookup(db.upcast()).source(db.upcast());
3089 let param_list = src.value.param_list()?;
3090 param_list.self_param()
3092 pub fn n_params(&self) -> usize {
3093 self.sig.params().len() - if self.is_bound_method { 1 } else { 0 }
3097 db: &dyn HirDatabase,
3098 ) -> Vec<(Option<Either<ast::SelfParam, ast::Pat>>, Type)> {
3103 .skip(if self.is_bound_method { 1 } else { 0 })
3104 .map(|ty| self.ty.derived(ty.clone()));
3105 let patterns = match self.def {
3106 Some(CallableDefId::FunctionId(func)) => {
3107 let src = func.lookup(db.upcast()).source(db.upcast());
3108 src.value.param_list().map(|param_list| {
3111 .map(|it| Some(Either::Left(it)))
3112 .filter(|_| !self.is_bound_method)
3114 .chain(param_list.params().map(|it| it.pat().map(Either::Right)))
3119 patterns.into_iter().flatten().chain(iter::repeat(None)).zip(types).collect()
3121 pub fn return_type(&self) -> Type {
3122 self.ty.derived(self.sig.ret().clone())
3127 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
3129 ModuleDef(ModuleDef),
3131 GenericParam(GenericParam),
3140 pub fn all_items(def: PerNs) -> ArrayVec<Self, 3> {
3141 let mut items = ArrayVec::new();
3143 match (def.take_types(), def.take_values()) {
3144 (Some(m1), None) => items.push(ScopeDef::ModuleDef(m1.into())),
3145 (None, Some(m2)) => items.push(ScopeDef::ModuleDef(m2.into())),
3146 (Some(m1), Some(m2)) => {
3147 // Some items, like unit structs and enum variants, are
3148 // returned as both a type and a value. Here we want
3149 // to de-duplicate them.
3151 items.push(ScopeDef::ModuleDef(m1.into()));
3152 items.push(ScopeDef::ModuleDef(m2.into()));
3154 items.push(ScopeDef::ModuleDef(m1.into()));
3160 if let Some(macro_def_id) = def.take_macros() {
3161 items.push(ScopeDef::MacroDef(macro_def_id.into()));
3164 if items.is_empty() {
3165 items.push(ScopeDef::Unknown);
3171 pub fn attrs(&self, db: &dyn HirDatabase) -> Option<AttrsWithOwner> {
3173 ScopeDef::ModuleDef(it) => it.attrs(db),
3174 ScopeDef::MacroDef(it) => Some(it.attrs(db)),
3175 ScopeDef::GenericParam(it) => Some(it.attrs(db)),
3176 ScopeDef::ImplSelfType(_)
3177 | ScopeDef::AdtSelfType(_)
3178 | ScopeDef::Local(_)
3179 | ScopeDef::Label(_)
3180 | ScopeDef::Unknown => None,
3184 pub fn krate(&self, db: &dyn HirDatabase) -> Option<Crate> {
3186 ScopeDef::ModuleDef(it) => it.module(db).map(|m| m.krate()),
3187 ScopeDef::MacroDef(it) => it.module(db).map(|m| m.krate()),
3188 ScopeDef::GenericParam(it) => Some(it.module(db).krate()),
3189 ScopeDef::ImplSelfType(_) => None,
3190 ScopeDef::AdtSelfType(it) => Some(it.module(db).krate()),
3191 ScopeDef::Local(it) => Some(it.module(db).krate()),
3192 ScopeDef::Label(it) => Some(it.module(db).krate()),
3193 ScopeDef::Unknown => None,
3198 impl From<ItemInNs> for ScopeDef {
3199 fn from(item: ItemInNs) -> Self {
3201 ItemInNs::Types(id) => ScopeDef::ModuleDef(id),
3202 ItemInNs::Values(id) => ScopeDef::ModuleDef(id),
3203 ItemInNs::Macros(id) => ScopeDef::MacroDef(id),
3208 pub trait HasVisibility {
3209 fn visibility(&self, db: &dyn HirDatabase) -> Visibility;
3210 fn is_visible_from(&self, db: &dyn HirDatabase, module: Module) -> bool {
3211 let vis = self.visibility(db);
3212 vis.is_visible_from(db.upcast(), module.id)
3216 /// Trait for obtaining the defining crate of an item.
3217 pub trait HasCrate {
3218 fn krate(&self, db: &dyn HirDatabase) -> Crate;
3221 impl<T: hir_def::HasModule> HasCrate for T {
3222 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3223 self.module(db.upcast()).krate().into()
3227 impl HasCrate for AssocItem {
3228 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3229 self.module(db).krate()
3233 impl HasCrate for Field {
3234 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3235 self.parent_def(db).module(db).krate()
3239 impl HasCrate for Function {
3240 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3241 self.module(db).krate()
3245 impl HasCrate for Const {
3246 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3247 self.module(db).krate()
3251 impl HasCrate for TypeAlias {
3252 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3253 self.module(db).krate()
3257 impl HasCrate for Type {
3258 fn krate(&self, _db: &dyn HirDatabase) -> Crate {