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"]
35 use std::{collections::HashMap, iter, ops::ControlFlow, sync::Arc};
37 use arrayvec::ArrayVec;
38 use base_db::{CrateDisplayName, CrateId, CrateOrigin, Edition, FileId};
41 adt::{ReprKind, VariantData},
42 body::{BodyDiagnostic, SyntheticSyntax},
43 expr::{BindingAnnotation, LabelId, Pat, PatId},
44 item_tree::ItemTreeNode,
45 lang_item::LangItemTarget,
46 nameres::{self, diagnostics::DefDiagnostic},
48 resolver::{HasResolver, Resolver},
50 AdtId, AssocItemId, AssocItemLoc, AttrDefId, ConstId, ConstParamId, DefWithBodyId, EnumId,
51 FunctionId, GenericDefId, HasModule, ImplId, ItemContainerId, LifetimeParamId,
52 LocalEnumVariantId, LocalFieldId, Lookup, ModuleId, StaticId, StructId, TraitId, TypeAliasId,
55 use hir_expand::{name::name, MacroCallKind, MacroDefId, MacroDefKind};
58 consteval::{eval_const, ComputedExpr, ConstEvalCtx, ConstEvalError, ConstExt},
60 diagnostics::BodyValidationDiagnostic,
61 method_resolution::{self, TyFingerprint},
65 AliasEq, AliasTy, BoundVar, CallableDefId, CallableSig, Canonical, CanonicalVarKinds, Cast,
66 DebruijnIndex, InEnvironment, Interner, QuantifiedWhereClause, Scalar, Solution, Substitution,
67 TraitEnvironment, TraitRefExt, Ty, TyBuilder, TyDefId, TyExt, TyKind, TyVariableKind,
70 use itertools::Itertools;
71 use nameres::diagnostics::DefDiagnosticKind;
72 use once_cell::unsync::Lazy;
73 use rustc_hash::FxHashSet;
74 use stdx::{format_to, impl_from};
76 ast::{self, HasAttrs as _, HasDocComments, HasName},
77 AstNode, AstPtr, SmolStr, SyntaxKind, SyntaxNodePtr,
79 use tt::{Ident, Leaf, Literal, TokenTree};
81 use crate::db::{DefDatabase, HirDatabase};
84 attrs::{HasAttrs, Namespace},
86 AddReferenceHere, AnyDiagnostic, BreakOutsideOfLoop, InactiveCode, IncorrectCase,
87 InvalidDeriveTarget, MacroError, MalformedDerive, MismatchedArgCount, MissingFields,
88 MissingMatchArms, MissingOkOrSomeInTailExpr, MissingUnsafe, NoSuchField,
89 RemoveThisSemicolon, ReplaceFilterMapNextWithFindMap, UnimplementedBuiltinMacro,
90 UnresolvedExternCrate, UnresolvedImport, UnresolvedMacroCall, UnresolvedModule,
93 has_source::HasSource,
94 semantics::{PathResolution, Semantics, SemanticsScope, TypeInfo},
97 // Be careful with these re-exports.
99 // `hir` is the boundary between the compiler and the IDE. It should try hard to
100 // isolate the compiler from the ide, to allow the two to be refactored
101 // independently. Re-exporting something from the compiler is the sure way to
102 // breach the boundary.
104 // Generally, a refactoring which *removes* a name from this list is a good
107 cfg::{CfgAtom, CfgExpr, CfgOptions},
110 attr::{Attr, Attrs, AttrsWithOwner, Documentation},
111 builtin_attr::AttributeTemplate,
112 find_path::PrefixKind,
114 nameres::ModuleSource,
115 path::{ModPath, PathKind},
116 type_ref::{Mutability, TypeRef},
117 visibility::Visibility,
121 ExpandResult, HirFileId, InFile, MacroFile, Origin,
123 hir_ty::display::HirDisplay,
126 // These are negative re-exports: pub using these names is forbidden, they
127 // should remain private to hir internals.
131 hir_expand::{hygiene::Hygiene, name::AsName},
134 /// hir::Crate describes a single crate. It's the main interface with which
135 /// a crate's dependencies interact. Mostly, it should be just a proxy for the
137 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
139 pub(crate) id: CrateId,
143 pub struct CrateDependency {
149 pub fn origin(self, db: &dyn HirDatabase) -> CrateOrigin {
150 db.crate_graph()[self.id].origin.clone()
153 pub fn dependencies(self, db: &dyn HirDatabase) -> Vec<CrateDependency> {
154 db.crate_graph()[self.id]
158 let krate = Crate { id: dep.crate_id };
159 let name = dep.as_name();
160 CrateDependency { krate, name }
165 pub fn reverse_dependencies(self, db: &dyn HirDatabase) -> Vec<Crate> {
166 let crate_graph = db.crate_graph();
170 crate_graph[krate].dependencies.iter().any(|it| it.crate_id == self.id)
172 .map(|id| Crate { id })
176 pub fn transitive_reverse_dependencies(self, db: &dyn HirDatabase) -> Vec<Crate> {
177 db.crate_graph().transitive_rev_deps(self.id).into_iter().map(|id| Crate { id }).collect()
180 pub fn root_module(self, db: &dyn HirDatabase) -> Module {
181 let def_map = db.crate_def_map(self.id);
182 Module { id: def_map.module_id(def_map.root()) }
185 pub fn modules(self, db: &dyn HirDatabase) -> Vec<Module> {
186 let def_map = db.crate_def_map(self.id);
187 def_map.modules().map(|(id, _)| def_map.module_id(id).into()).collect()
190 pub fn root_file(self, db: &dyn HirDatabase) -> FileId {
191 db.crate_graph()[self.id].root_file_id
194 pub fn edition(self, db: &dyn HirDatabase) -> Edition {
195 db.crate_graph()[self.id].edition
198 pub fn version(self, db: &dyn HirDatabase) -> Option<String> {
199 db.crate_graph()[self.id].version.clone()
202 pub fn display_name(self, db: &dyn HirDatabase) -> Option<CrateDisplayName> {
203 db.crate_graph()[self.id].display_name.clone()
206 pub fn query_external_importables(
208 db: &dyn DefDatabase,
209 query: import_map::Query,
210 ) -> impl Iterator<Item = Either<ModuleDef, MacroDef>> {
211 let _p = profile::span("query_external_importables");
212 import_map::search_dependencies(db, self.into(), query).into_iter().map(|item| {
213 match ItemInNs::from(item) {
214 ItemInNs::Types(mod_id) | ItemInNs::Values(mod_id) => Either::Left(mod_id),
215 ItemInNs::Macros(mac_id) => Either::Right(mac_id),
220 pub fn all(db: &dyn HirDatabase) -> Vec<Crate> {
221 db.crate_graph().iter().map(|id| Crate { id }).collect()
224 /// Try to get the root URL of the documentation of a crate.
225 pub fn get_html_root_url(self: &Crate, db: &dyn HirDatabase) -> Option<String> {
226 // Look for #![doc(html_root_url = "...")]
227 let attrs = db.attrs(AttrDefId::ModuleId(self.root_module(db).into()));
228 let doc_attr_q = attrs.by_key("doc");
230 if !doc_attr_q.exists() {
234 let doc_url = doc_attr_q.tt_values().map(|tt| {
235 let name = tt.token_trees.iter()
236 .skip_while(|tt| !matches!(tt, TokenTree::Leaf(Leaf::Ident(Ident { text, ..} )) if text == "html_root_url"))
240 Some(TokenTree::Leaf(Leaf::Literal(Literal{ref text, ..}))) => Some(text),
245 doc_url.map(|s| s.trim_matches('"').trim_end_matches('/').to_owned() + "/")
248 pub fn cfg(&self, db: &dyn HirDatabase) -> CfgOptions {
249 db.crate_graph()[self.id].cfg_options.clone()
252 pub fn potential_cfg(&self, db: &dyn HirDatabase) -> CfgOptions {
253 db.crate_graph()[self.id].potential_cfg_options.clone()
257 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
259 pub(crate) id: ModuleId,
262 /// The defs which can be visible in the module.
263 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
268 // Can't be directly declared, but can be imported.
273 TypeAlias(TypeAlias),
274 BuiltinType(BuiltinType),
279 Adt(Struct, Enum, Union),
289 impl From<VariantDef> for ModuleDef {
290 fn from(var: VariantDef) -> Self {
292 VariantDef::Struct(t) => Adt::from(t).into(),
293 VariantDef::Union(t) => Adt::from(t).into(),
294 VariantDef::Variant(t) => t.into(),
300 pub fn module(self, db: &dyn HirDatabase) -> Option<Module> {
302 ModuleDef::Module(it) => it.parent(db),
303 ModuleDef::Function(it) => Some(it.module(db)),
304 ModuleDef::Adt(it) => Some(it.module(db)),
305 ModuleDef::Variant(it) => Some(it.module(db)),
306 ModuleDef::Const(it) => Some(it.module(db)),
307 ModuleDef::Static(it) => Some(it.module(db)),
308 ModuleDef::Trait(it) => Some(it.module(db)),
309 ModuleDef::TypeAlias(it) => Some(it.module(db)),
310 ModuleDef::BuiltinType(_) => None,
314 pub fn canonical_path(&self, db: &dyn HirDatabase) -> Option<String> {
315 let mut segments = vec![self.name(db)?];
316 for m in self.module(db)?.path_to_root(db) {
317 segments.extend(m.name(db))
320 Some(segments.into_iter().join("::"))
323 pub fn canonical_module_path(
325 db: &dyn HirDatabase,
326 ) -> Option<impl Iterator<Item = Module>> {
327 self.module(db).map(|it| it.path_to_root(db).into_iter().rev())
330 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
331 let name = match self {
332 ModuleDef::Module(it) => it.name(db)?,
333 ModuleDef::Const(it) => it.name(db)?,
334 ModuleDef::Adt(it) => it.name(db),
335 ModuleDef::Trait(it) => it.name(db),
336 ModuleDef::Function(it) => it.name(db),
337 ModuleDef::Variant(it) => it.name(db),
338 ModuleDef::TypeAlias(it) => it.name(db),
339 ModuleDef::Static(it) => it.name(db),
340 ModuleDef::BuiltinType(it) => it.name(),
345 pub fn diagnostics(self, db: &dyn HirDatabase) -> Vec<AnyDiagnostic> {
346 let id = match self {
347 ModuleDef::Adt(it) => match it {
348 Adt::Struct(it) => it.id.into(),
349 Adt::Enum(it) => it.id.into(),
350 Adt::Union(it) => it.id.into(),
352 ModuleDef::Trait(it) => it.id.into(),
353 ModuleDef::Function(it) => it.id.into(),
354 ModuleDef::TypeAlias(it) => it.id.into(),
355 ModuleDef::Module(it) => it.id.into(),
356 ModuleDef::Const(it) => it.id.into(),
357 ModuleDef::Static(it) => it.id.into(),
358 _ => return Vec::new(),
361 let module = match self.module(db) {
363 None => return Vec::new(),
366 let mut acc = Vec::new();
368 match self.as_def_with_body() {
370 def.diagnostics(db, &mut acc);
373 for diag in hir_ty::diagnostics::incorrect_case(db, module.id.krate(), id) {
374 acc.push(diag.into())
382 pub fn as_def_with_body(self) -> Option<DefWithBody> {
384 ModuleDef::Function(it) => Some(it.into()),
385 ModuleDef::Const(it) => Some(it.into()),
386 ModuleDef::Static(it) => Some(it.into()),
390 | ModuleDef::Variant(_)
391 | ModuleDef::Trait(_)
392 | ModuleDef::TypeAlias(_)
393 | ModuleDef::BuiltinType(_) => None,
397 pub fn attrs(&self, db: &dyn HirDatabase) -> Option<AttrsWithOwner> {
399 ModuleDef::Module(it) => it.attrs(db),
400 ModuleDef::Function(it) => it.attrs(db),
401 ModuleDef::Adt(it) => it.attrs(db),
402 ModuleDef::Variant(it) => it.attrs(db),
403 ModuleDef::Const(it) => it.attrs(db),
404 ModuleDef::Static(it) => it.attrs(db),
405 ModuleDef::Trait(it) => it.attrs(db),
406 ModuleDef::TypeAlias(it) => it.attrs(db),
407 ModuleDef::BuiltinType(_) => return None,
412 impl HasVisibility for ModuleDef {
413 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
415 ModuleDef::Module(it) => it.visibility(db),
416 ModuleDef::Function(it) => it.visibility(db),
417 ModuleDef::Adt(it) => it.visibility(db),
418 ModuleDef::Const(it) => it.visibility(db),
419 ModuleDef::Static(it) => it.visibility(db),
420 ModuleDef::Trait(it) => it.visibility(db),
421 ModuleDef::TypeAlias(it) => it.visibility(db),
422 ModuleDef::Variant(it) => it.visibility(db),
423 ModuleDef::BuiltinType(_) => Visibility::Public,
429 /// Name of this module.
430 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
431 let def_map = self.id.def_map(db.upcast());
432 let parent = def_map[self.id.local_id].parent?;
433 def_map[parent].children.iter().find_map(|(name, module_id)| {
434 if *module_id == self.id.local_id {
442 /// Returns the crate this module is part of.
443 pub fn krate(self) -> Crate {
444 Crate { id: self.id.krate() }
447 /// Topmost parent of this module. Every module has a `crate_root`, but some
448 /// might be missing `krate`. This can happen if a module's file is not included
449 /// in the module tree of any target in `Cargo.toml`.
450 pub fn crate_root(self, db: &dyn HirDatabase) -> Module {
451 let def_map = db.crate_def_map(self.id.krate());
452 Module { id: def_map.module_id(def_map.root()) }
455 /// Iterates over all child modules.
456 pub fn children(self, db: &dyn HirDatabase) -> impl Iterator<Item = Module> {
457 let def_map = self.id.def_map(db.upcast());
458 let children = def_map[self.id.local_id]
461 .map(|(_, module_id)| Module { id: def_map.module_id(*module_id) })
462 .collect::<Vec<_>>();
466 /// Finds a parent module.
467 pub fn parent(self, db: &dyn HirDatabase) -> Option<Module> {
468 // FIXME: handle block expressions as modules (their parent is in a different DefMap)
469 let def_map = self.id.def_map(db.upcast());
470 let parent_id = def_map[self.id.local_id].parent?;
471 Some(Module { id: def_map.module_id(parent_id) })
474 pub fn path_to_root(self, db: &dyn HirDatabase) -> Vec<Module> {
475 let mut res = vec![self];
477 while let Some(next) = curr.parent(db) {
484 /// Returns a `ModuleScope`: a set of items, visible in this module.
487 db: &dyn HirDatabase,
488 visible_from: Option<Module>,
489 ) -> Vec<(Name, ScopeDef)> {
490 self.id.def_map(db.upcast())[self.id.local_id]
493 .filter_map(|(name, def)| {
494 if let Some(m) = visible_from {
496 def.filter_visibility(|vis| vis.is_visible_from(db.upcast(), m.id));
497 if filtered.is_none() && !def.is_none() {
500 Some((name, filtered))
506 .flat_map(|(name, def)| {
507 ScopeDef::all_items(def).into_iter().map(move |item| (name.clone(), item))
512 pub fn diagnostics(self, db: &dyn HirDatabase, acc: &mut Vec<AnyDiagnostic>) {
513 let _p = profile::span("Module::diagnostics").detail(|| {
514 format!("{:?}", self.name(db).map_or("<unknown>".into(), |name| name.to_string()))
516 let def_map = self.id.def_map(db.upcast());
517 for diag in def_map.diagnostics() {
518 if diag.in_module != self.id.local_id {
519 // FIXME: This is accidentally quadratic.
522 emit_def_diagnostic(db, acc, diag);
524 for decl in self.declarations(db) {
526 ModuleDef::Module(m) => {
527 // Only add diagnostics from inline modules
528 if def_map[m.id.local_id].origin.is_inline() {
529 m.diagnostics(db, acc)
532 _ => acc.extend(decl.diagnostics(db)),
536 for impl_def in self.impl_defs(db) {
537 for item in impl_def.items(db) {
538 let def: DefWithBody = match item {
539 AssocItem::Function(it) => it.into(),
540 AssocItem::Const(it) => it.into(),
541 AssocItem::TypeAlias(_) => continue,
544 def.diagnostics(db, acc);
549 pub fn declarations(self, db: &dyn HirDatabase) -> Vec<ModuleDef> {
550 let def_map = self.id.def_map(db.upcast());
551 let scope = &def_map[self.id.local_id].scope;
554 .map(ModuleDef::from)
555 .chain(scope.unnamed_consts().map(|id| ModuleDef::Const(Const::from(id))))
559 pub fn impl_defs(self, db: &dyn HirDatabase) -> Vec<Impl> {
560 let def_map = self.id.def_map(db.upcast());
561 def_map[self.id.local_id].scope.impls().map(Impl::from).collect()
564 /// Finds a path that can be used to refer to the given item from within
565 /// this module, if possible.
566 pub fn find_use_path(self, db: &dyn DefDatabase, item: impl Into<ItemInNs>) -> Option<ModPath> {
567 hir_def::find_path::find_path(db, item.into().into(), self.into())
570 /// Finds a path that can be used to refer to the given item from within
571 /// this module, if possible. This is used for returning import paths for use-statements.
572 pub fn find_use_path_prefixed(
574 db: &dyn DefDatabase,
575 item: impl Into<ItemInNs>,
576 prefix_kind: PrefixKind,
577 ) -> Option<ModPath> {
578 hir_def::find_path::find_path_prefixed(db, item.into().into(), self.into(), prefix_kind)
582 fn emit_def_diagnostic(db: &dyn HirDatabase, acc: &mut Vec<AnyDiagnostic>, diag: &DefDiagnostic) {
584 DefDiagnosticKind::UnresolvedModule { ast: declaration, candidate } => {
585 let decl = declaration.to_node(db.upcast());
588 decl: InFile::new(declaration.file_id, AstPtr::new(&decl)),
589 candidate: candidate.clone(),
594 DefDiagnosticKind::UnresolvedExternCrate { ast } => {
595 let item = ast.to_node(db.upcast());
597 UnresolvedExternCrate { decl: InFile::new(ast.file_id, AstPtr::new(&item)) }.into(),
601 DefDiagnosticKind::UnresolvedImport { id, index } => {
602 let file_id = id.file_id();
603 let item_tree = id.item_tree(db.upcast());
604 let import = &item_tree[id.value];
606 let use_tree = import.use_tree_to_ast(db.upcast(), file_id, *index);
608 UnresolvedImport { decl: InFile::new(file_id, AstPtr::new(&use_tree)) }.into(),
612 DefDiagnosticKind::UnconfiguredCode { ast, cfg, opts } => {
613 let item = ast.to_node(db.upcast());
616 node: ast.with_value(AstPtr::new(&item).into()),
624 DefDiagnosticKind::UnresolvedProcMacro { ast } => {
625 let mut precise_location = None;
626 let (node, name) = match ast {
627 MacroCallKind::FnLike { ast_id, .. } => {
628 let node = ast_id.to_node(db.upcast());
629 (ast_id.with_value(SyntaxNodePtr::from(AstPtr::new(&node))), None)
631 MacroCallKind::Derive { ast_id, derive_name, .. } => {
632 let node = ast_id.to_node(db.upcast());
634 // Compute the precise location of the macro name's token in the derive
636 // FIXME: This does not handle paths to the macro, but neither does the
639 node.attrs().filter_map(|attr| match attr.as_simple_call() {
640 Some((name, args)) if name == "derive" => Some(args),
643 'outer: for attr in derive_attrs {
645 attr.syntax().children_with_tokens().filter_map(|elem| match elem {
646 syntax::NodeOrToken::Node(_) => None,
647 syntax::NodeOrToken::Token(tok) => Some(tok),
649 for token in tokens {
650 if token.kind() == SyntaxKind::IDENT && token.text() == &**derive_name {
651 precise_location = Some(token.text_range());
658 ast_id.with_value(SyntaxNodePtr::from(AstPtr::new(&node))),
659 Some(derive_name.clone()),
662 MacroCallKind::Attr { ast_id, invoc_attr_index, attr_name, .. } => {
663 let node = ast_id.to_node(db.upcast());
665 .doc_comments_and_attrs()
666 .nth((*invoc_attr_index) as usize)
667 .and_then(Either::right)
668 .unwrap_or_else(|| panic!("cannot find attribute #{}", invoc_attr_index));
670 ast_id.with_value(SyntaxNodePtr::from(AstPtr::new(&attr))),
671 Some(attr_name.clone()),
676 UnresolvedProcMacro { node, precise_location, macro_name: name.map(Into::into) }
681 DefDiagnosticKind::UnresolvedMacroCall { ast, path } => {
682 let node = ast.to_node(db.upcast());
684 UnresolvedMacroCall {
685 macro_call: InFile::new(ast.file_id, AstPtr::new(&node)),
692 DefDiagnosticKind::MacroError { ast, message } => {
693 let node = match ast {
694 MacroCallKind::FnLike { ast_id, .. } => {
695 let node = ast_id.to_node(db.upcast());
696 ast_id.with_value(SyntaxNodePtr::from(AstPtr::new(&node)))
698 MacroCallKind::Derive { ast_id, .. } => {
699 // FIXME: point to the attribute instead, this creates very large diagnostics
700 let node = ast_id.to_node(db.upcast());
701 ast_id.with_value(SyntaxNodePtr::from(AstPtr::new(&node)))
703 MacroCallKind::Attr { ast_id, .. } => {
704 // FIXME: point to the attribute instead, this creates very large diagnostics
705 let node = ast_id.to_node(db.upcast());
706 ast_id.with_value(SyntaxNodePtr::from(AstPtr::new(&node)))
709 acc.push(MacroError { node, message: message.clone() }.into());
712 DefDiagnosticKind::UnimplementedBuiltinMacro { ast } => {
713 let node = ast.to_node(db.upcast());
714 // Must have a name, otherwise we wouldn't emit it.
715 let name = node.name().expect("unimplemented builtin macro with no name");
717 UnimplementedBuiltinMacro {
718 node: ast.with_value(SyntaxNodePtr::from(AstPtr::new(&name))),
723 DefDiagnosticKind::InvalidDeriveTarget { ast, id } => {
724 let node = ast.to_node(db.upcast());
725 let derive = node.attrs().nth(*id as usize);
729 InvalidDeriveTarget {
730 node: ast.with_value(SyntaxNodePtr::from(AstPtr::new(&derive))),
735 None => stdx::never!("derive diagnostic on item without derive attribute"),
738 DefDiagnosticKind::MalformedDerive { ast, id } => {
739 let node = ast.to_node(db.upcast());
740 let derive = node.attrs().nth(*id as usize);
745 node: ast.with_value(SyntaxNodePtr::from(AstPtr::new(&derive))),
750 None => stdx::never!("derive diagnostic on item without derive attribute"),
756 impl HasVisibility for Module {
757 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
758 let def_map = self.id.def_map(db.upcast());
759 let module_data = &def_map[self.id.local_id];
760 module_data.visibility
764 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
766 pub(crate) parent: VariantDef,
767 pub(crate) id: LocalFieldId,
770 #[derive(Debug, PartialEq, Eq)]
771 pub enum FieldSource {
772 Named(ast::RecordField),
773 Pos(ast::TupleField),
777 pub fn name(&self, db: &dyn HirDatabase) -> Name {
778 self.parent.variant_data(db).fields()[self.id].name.clone()
781 /// Returns the type as in the signature of the struct (i.e., with
782 /// placeholder types for type parameters). Only use this in the context of
783 /// the field definition.
784 pub fn ty(&self, db: &dyn HirDatabase) -> Type {
785 let var_id = self.parent.into();
786 let generic_def_id: GenericDefId = match self.parent {
787 VariantDef::Struct(it) => it.id.into(),
788 VariantDef::Union(it) => it.id.into(),
789 VariantDef::Variant(it) => it.parent.id.into(),
791 let substs = TyBuilder::type_params_subst(db, generic_def_id);
792 let ty = db.field_types(var_id)[self.id].clone().substitute(Interner, &substs);
793 Type::new(db, self.parent.module(db).id.krate(), var_id, ty)
796 pub fn parent_def(&self, _db: &dyn HirDatabase) -> VariantDef {
801 impl HasVisibility for Field {
802 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
803 let variant_data = self.parent.variant_data(db);
804 let visibility = &variant_data.fields()[self.id].visibility;
805 let parent_id: hir_def::VariantId = self.parent.into();
806 visibility.resolve(db.upcast(), &parent_id.resolver(db.upcast()))
810 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
812 pub(crate) id: StructId,
816 pub fn module(self, db: &dyn HirDatabase) -> Module {
817 Module { id: self.id.lookup(db.upcast()).container }
820 pub fn name(self, db: &dyn HirDatabase) -> Name {
821 db.struct_data(self.id).name.clone()
824 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
825 db.struct_data(self.id)
829 .map(|(id, _)| Field { parent: self.into(), id })
833 pub fn ty(self, db: &dyn HirDatabase) -> Type {
834 Type::from_def(db, self.id.lookup(db.upcast()).container.krate(), self.id)
837 pub fn repr(self, db: &dyn HirDatabase) -> Option<ReprKind> {
838 db.struct_data(self.id).repr.clone()
841 pub fn kind(self, db: &dyn HirDatabase) -> StructKind {
842 self.variant_data(db).kind()
845 fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
846 db.struct_data(self.id).variant_data.clone()
850 impl HasVisibility for Struct {
851 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
852 db.struct_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
856 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
858 pub(crate) id: UnionId,
862 pub fn name(self, db: &dyn HirDatabase) -> Name {
863 db.union_data(self.id).name.clone()
866 pub fn module(self, db: &dyn HirDatabase) -> Module {
867 Module { id: self.id.lookup(db.upcast()).container }
870 pub fn ty(self, db: &dyn HirDatabase) -> Type {
871 Type::from_def(db, self.id.lookup(db.upcast()).container.krate(), self.id)
874 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
875 db.union_data(self.id)
879 .map(|(id, _)| Field { parent: self.into(), id })
883 fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
884 db.union_data(self.id).variant_data.clone()
888 impl HasVisibility for Union {
889 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
890 db.union_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
894 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
896 pub(crate) id: EnumId,
900 pub fn module(self, db: &dyn HirDatabase) -> Module {
901 Module { id: self.id.lookup(db.upcast()).container }
904 pub fn name(self, db: &dyn HirDatabase) -> Name {
905 db.enum_data(self.id).name.clone()
908 pub fn variants(self, db: &dyn HirDatabase) -> Vec<Variant> {
909 db.enum_data(self.id).variants.iter().map(|(id, _)| Variant { parent: self, id }).collect()
912 pub fn ty(self, db: &dyn HirDatabase) -> Type {
913 Type::from_def(db, self.id.lookup(db.upcast()).container.krate(), self.id)
917 impl HasVisibility for Enum {
918 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
919 db.enum_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
923 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
925 pub(crate) parent: Enum,
926 pub(crate) id: LocalEnumVariantId,
930 pub fn module(self, db: &dyn HirDatabase) -> Module {
931 self.parent.module(db)
934 pub fn parent_enum(self, _db: &dyn HirDatabase) -> Enum {
938 pub fn name(self, db: &dyn HirDatabase) -> Name {
939 db.enum_data(self.parent.id).variants[self.id].name.clone()
942 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
943 self.variant_data(db)
946 .map(|(id, _)| Field { parent: self.into(), id })
950 pub fn kind(self, db: &dyn HirDatabase) -> StructKind {
951 self.variant_data(db).kind()
954 pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
955 db.enum_data(self.parent.id).variants[self.id].variant_data.clone()
959 /// Variants inherit visibility from the parent enum.
960 impl HasVisibility for Variant {
961 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
962 self.parent_enum(db).visibility(db)
967 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
973 impl_from!(Struct, Union, Enum for Adt);
976 pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
977 let subst = db.generic_defaults(self.into());
978 subst.iter().any(|ty| ty.skip_binders().is_unknown())
981 /// Turns this ADT into a type. Any type parameters of the ADT will be
982 /// turned into unknown types, which is good for e.g. finding the most
983 /// general set of completions, but will not look very nice when printed.
984 pub fn ty(self, db: &dyn HirDatabase) -> Type {
985 let id = AdtId::from(self);
986 Type::from_def(db, id.module(db.upcast()).krate(), id)
989 pub fn module(self, db: &dyn HirDatabase) -> Module {
991 Adt::Struct(s) => s.module(db),
992 Adt::Union(s) => s.module(db),
993 Adt::Enum(e) => e.module(db),
997 pub fn name(self, db: &dyn HirDatabase) -> Name {
999 Adt::Struct(s) => s.name(db),
1000 Adt::Union(u) => u.name(db),
1001 Adt::Enum(e) => e.name(db),
1006 impl HasVisibility for Adt {
1007 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1009 Adt::Struct(it) => it.visibility(db),
1010 Adt::Union(it) => it.visibility(db),
1011 Adt::Enum(it) => it.visibility(db),
1016 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1017 pub enum VariantDef {
1022 impl_from!(Struct, Union, Variant for VariantDef);
1025 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
1027 VariantDef::Struct(it) => it.fields(db),
1028 VariantDef::Union(it) => it.fields(db),
1029 VariantDef::Variant(it) => it.fields(db),
1033 pub fn module(self, db: &dyn HirDatabase) -> Module {
1035 VariantDef::Struct(it) => it.module(db),
1036 VariantDef::Union(it) => it.module(db),
1037 VariantDef::Variant(it) => it.module(db),
1041 pub fn name(&self, db: &dyn HirDatabase) -> Name {
1043 VariantDef::Struct(s) => s.name(db),
1044 VariantDef::Union(u) => u.name(db),
1045 VariantDef::Variant(e) => e.name(db),
1049 pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
1051 VariantDef::Struct(it) => it.variant_data(db),
1052 VariantDef::Union(it) => it.variant_data(db),
1053 VariantDef::Variant(it) => it.variant_data(db),
1058 /// The defs which have a body.
1059 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1060 pub enum DefWithBody {
1065 impl_from!(Function, Const, Static for DefWithBody);
1068 pub fn module(self, db: &dyn HirDatabase) -> Module {
1070 DefWithBody::Const(c) => c.module(db),
1071 DefWithBody::Function(f) => f.module(db),
1072 DefWithBody::Static(s) => s.module(db),
1076 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1078 DefWithBody::Function(f) => Some(f.name(db)),
1079 DefWithBody::Static(s) => Some(s.name(db)),
1080 DefWithBody::Const(c) => c.name(db),
1084 /// Returns the type this def's body has to evaluate to.
1085 pub fn body_type(self, db: &dyn HirDatabase) -> Type {
1087 DefWithBody::Function(it) => it.ret_type(db),
1088 DefWithBody::Static(it) => it.ty(db),
1089 DefWithBody::Const(it) => it.ty(db),
1093 pub fn diagnostics(self, db: &dyn HirDatabase, acc: &mut Vec<AnyDiagnostic>) {
1094 let krate = self.module(db).id.krate();
1096 let (body, source_map) = db.body_with_source_map(self.into());
1098 for (_, def_map) in body.blocks(db.upcast()) {
1099 for diag in def_map.diagnostics() {
1100 emit_def_diagnostic(db, acc, diag);
1104 for diag in source_map.diagnostics() {
1106 BodyDiagnostic::InactiveCode { node, cfg, opts } => acc.push(
1107 InactiveCode { node: node.clone(), cfg: cfg.clone(), opts: opts.clone() }
1110 BodyDiagnostic::MacroError { node, message } => acc.push(
1112 node: node.clone().map(|it| it.into()),
1113 message: message.to_string(),
1117 BodyDiagnostic::UnresolvedProcMacro { node } => acc.push(
1118 UnresolvedProcMacro {
1119 node: node.clone().map(|it| it.into()),
1120 precise_location: None,
1125 BodyDiagnostic::UnresolvedMacroCall { node, path } => acc.push(
1126 UnresolvedMacroCall { macro_call: node.clone(), path: path.clone() }.into(),
1131 let infer = db.infer(self.into());
1132 let source_map = Lazy::new(|| db.body_with_source_map(self.into()).1);
1133 for d in &infer.diagnostics {
1135 hir_ty::InferenceDiagnostic::NoSuchField { expr } => {
1136 let field = source_map.field_syntax(*expr);
1137 acc.push(NoSuchField { field }.into())
1139 hir_ty::InferenceDiagnostic::BreakOutsideOfLoop { expr } => {
1140 let expr = source_map
1142 .expect("break outside of loop in synthetic syntax");
1143 acc.push(BreakOutsideOfLoop { expr }.into())
1148 for expr in hir_ty::diagnostics::missing_unsafe(db, self.into()) {
1149 match source_map.expr_syntax(expr) {
1150 Ok(expr) => acc.push(MissingUnsafe { expr }.into()),
1151 Err(SyntheticSyntax) => {
1152 // FIXME: Here and eslwhere in this file, the `expr` was
1153 // desugared, report or assert that this doesn't happen.
1158 for diagnostic in BodyValidationDiagnostic::collect(db, self.into()) {
1160 BodyValidationDiagnostic::RecordMissingFields {
1165 let variant_data = variant.variant_data(db.upcast());
1166 let missed_fields = missed_fields
1168 .map(|idx| variant_data.fields()[idx].name.clone())
1172 Either::Left(record_expr) => match source_map.expr_syntax(record_expr) {
1174 let root = source_ptr.file_syntax(db.upcast());
1175 if let ast::Expr::RecordExpr(record_expr) =
1176 &source_ptr.value.to_node(&root)
1178 if record_expr.record_expr_field_list().is_some() {
1181 file: source_ptr.file_id,
1182 field_list_parent: Either::Left(AstPtr::new(
1185 field_list_parent_path: record_expr
1187 .map(|path| AstPtr::new(&path)),
1195 Err(SyntheticSyntax) => (),
1197 Either::Right(record_pat) => match source_map.pat_syntax(record_pat) {
1199 if let Some(expr) = source_ptr.value.as_ref().left() {
1200 let root = source_ptr.file_syntax(db.upcast());
1201 if let ast::Pat::RecordPat(record_pat) = expr.to_node(&root) {
1202 if record_pat.record_pat_field_list().is_some() {
1205 file: source_ptr.file_id,
1206 field_list_parent: Either::Right(AstPtr::new(
1209 field_list_parent_path: record_pat
1211 .map(|path| AstPtr::new(&path)),
1220 Err(SyntheticSyntax) => (),
1224 BodyValidationDiagnostic::ReplaceFilterMapNextWithFindMap { method_call_expr } => {
1225 if let Ok(next_source_ptr) = source_map.expr_syntax(method_call_expr) {
1227 ReplaceFilterMapNextWithFindMap {
1228 file: next_source_ptr.file_id,
1229 next_expr: next_source_ptr.value,
1235 BodyValidationDiagnostic::MismatchedArgCount { call_expr, expected, found } => {
1236 match source_map.expr_syntax(call_expr) {
1237 Ok(source_ptr) => acc.push(
1238 MismatchedArgCount { call_expr: source_ptr, expected, found }.into(),
1240 Err(SyntheticSyntax) => (),
1243 BodyValidationDiagnostic::RemoveThisSemicolon { expr } => {
1244 match source_map.expr_syntax(expr) {
1245 Ok(expr) => acc.push(RemoveThisSemicolon { expr }.into()),
1246 Err(SyntheticSyntax) => (),
1249 BodyValidationDiagnostic::MissingOkOrSomeInTailExpr { expr, required } => {
1250 match source_map.expr_syntax(expr) {
1251 Ok(expr) => acc.push(
1252 MissingOkOrSomeInTailExpr {
1255 expected: self.body_type(db),
1259 Err(SyntheticSyntax) => (),
1262 BodyValidationDiagnostic::MissingMatchArms { match_expr } => {
1263 match source_map.expr_syntax(match_expr) {
1265 let root = source_ptr.file_syntax(db.upcast());
1266 if let ast::Expr::MatchExpr(match_expr) =
1267 &source_ptr.value.to_node(&root)
1269 if let Some(match_expr) = match_expr.expr() {
1272 file: source_ptr.file_id,
1273 match_expr: AstPtr::new(&match_expr),
1280 Err(SyntheticSyntax) => (),
1283 BodyValidationDiagnostic::AddReferenceHere { arg_expr, mutability } => {
1284 match source_map.expr_syntax(arg_expr) {
1285 Ok(expr) => acc.push(AddReferenceHere { expr, mutability }.into()),
1286 Err(SyntheticSyntax) => (),
1292 let def: ModuleDef = match self {
1293 DefWithBody::Function(it) => it.into(),
1294 DefWithBody::Static(it) => it.into(),
1295 DefWithBody::Const(it) => it.into(),
1297 for diag in hir_ty::diagnostics::incorrect_case(db, krate, def.into()) {
1298 acc.push(diag.into())
1303 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1304 pub struct Function {
1305 pub(crate) id: FunctionId,
1309 pub fn module(self, db: &dyn HirDatabase) -> Module {
1310 self.id.lookup(db.upcast()).module(db.upcast()).into()
1313 pub fn name(self, db: &dyn HirDatabase) -> Name {
1314 db.function_data(self.id).name.clone()
1317 /// Get this function's return type
1318 pub fn ret_type(self, db: &dyn HirDatabase) -> Type {
1319 let resolver = self.id.resolver(db.upcast());
1320 let krate = self.id.lookup(db.upcast()).container.module(db.upcast()).krate();
1321 let ret_type = &db.function_data(self.id).ret_type;
1322 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
1323 let ty = ctx.lower_ty(ret_type);
1324 Type::new_with_resolver_inner(db, krate, &resolver, ty)
1327 pub fn self_param(self, db: &dyn HirDatabase) -> Option<SelfParam> {
1328 if !db.function_data(self.id).has_self_param() {
1331 Some(SelfParam { func: self.id })
1334 pub fn assoc_fn_params(self, db: &dyn HirDatabase) -> Vec<Param> {
1335 let resolver = self.id.resolver(db.upcast());
1336 let krate = self.id.lookup(db.upcast()).container.module(db.upcast()).krate();
1337 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
1338 let environment = db.trait_environment(self.id.into());
1339 db.function_data(self.id)
1343 .map(|(idx, (_, type_ref))| {
1344 let ty = Type { krate, env: environment.clone(), ty: ctx.lower_ty(type_ref) };
1345 Param { func: self, ty, idx }
1350 pub fn method_params(self, db: &dyn HirDatabase) -> Option<Vec<Param>> {
1351 if self.self_param(db).is_none() {
1354 let mut res = self.assoc_fn_params(db);
1359 pub fn is_unsafe(self, db: &dyn HirDatabase) -> bool {
1360 db.function_data(self.id).is_unsafe()
1363 pub fn is_const(self, db: &dyn HirDatabase) -> bool {
1364 db.function_data(self.id).is_const()
1367 pub fn is_async(self, db: &dyn HirDatabase) -> bool {
1368 db.function_data(self.id).is_async()
1371 /// Whether this function declaration has a definition.
1373 /// This is false in the case of required (not provided) trait methods.
1374 pub fn has_body(self, db: &dyn HirDatabase) -> bool {
1375 db.function_data(self.id).has_body()
1378 /// A textual representation of the HIR of this function for debugging purposes.
1379 pub fn debug_hir(self, db: &dyn HirDatabase) -> String {
1380 let body = db.body(self.id.into());
1382 let mut result = String::new();
1383 format_to!(result, "HIR expressions in the body of `{}`:\n", self.name(db));
1384 for (id, expr) in body.exprs.iter() {
1385 format_to!(result, "{:?}: {:?}\n", id, expr);
1392 // Note: logically, this belongs to `hir_ty`, but we are not using it there yet.
1399 impl From<hir_ty::Mutability> for Access {
1400 fn from(mutability: hir_ty::Mutability) -> Access {
1402 hir_ty::Mutability::Not => Access::Shared,
1403 hir_ty::Mutability::Mut => Access::Exclusive,
1408 #[derive(Clone, Debug)]
1411 /// The index in parameter list, including self parameter.
1417 pub fn ty(&self) -> &Type {
1421 pub fn name(&self, db: &dyn HirDatabase) -> Option<Name> {
1422 db.function_data(self.func.id).params[self.idx].0.clone()
1425 pub fn as_local(&self, db: &dyn HirDatabase) -> Local {
1426 let parent = DefWithBodyId::FunctionId(self.func.into());
1427 let body = db.body(parent);
1428 Local { parent, pat_id: body.params[self.idx] }
1431 pub fn pattern_source(&self, db: &dyn HirDatabase) -> Option<ast::Pat> {
1432 self.source(db).and_then(|p| p.value.pat())
1435 pub fn source(&self, db: &dyn HirDatabase) -> Option<InFile<ast::Param>> {
1436 let InFile { file_id, value } = self.func.source(db)?;
1437 let params = value.param_list()?;
1438 if params.self_param().is_some() {
1439 params.params().nth(self.idx.checked_sub(1)?)
1441 params.params().nth(self.idx)
1443 .map(|value| InFile { file_id, value })
1447 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1448 pub struct SelfParam {
1453 pub fn access(self, db: &dyn HirDatabase) -> Access {
1454 let func_data = db.function_data(self.func);
1458 .map(|(_, param)| match &**param {
1459 TypeRef::Reference(.., mutability) => match mutability {
1460 hir_def::type_ref::Mutability::Shared => Access::Shared,
1461 hir_def::type_ref::Mutability::Mut => Access::Exclusive,
1465 .unwrap_or(Access::Owned)
1468 pub fn display(self, db: &dyn HirDatabase) -> &'static str {
1469 match self.access(db) {
1470 Access::Shared => "&self",
1471 Access::Exclusive => "&mut self",
1472 Access::Owned => "self",
1476 pub fn source(&self, db: &dyn HirDatabase) -> Option<InFile<ast::SelfParam>> {
1477 let InFile { file_id, value } = Function::from(self.func).source(db)?;
1480 .and_then(|params| params.self_param())
1481 .map(|value| InFile { file_id, value })
1484 pub fn ty(&self, db: &dyn HirDatabase) -> Type {
1485 let resolver = self.func.resolver(db.upcast());
1486 let krate = self.func.lookup(db.upcast()).container.module(db.upcast()).krate();
1487 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
1488 let environment = db.trait_environment(self.func.into());
1492 env: environment.clone(),
1493 ty: ctx.lower_ty(&db.function_data(self.func).params[0].1),
1498 impl HasVisibility for Function {
1499 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1500 let function_data = db.function_data(self.id);
1501 let visibility = &function_data.visibility;
1502 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1506 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1508 pub(crate) id: ConstId,
1512 pub fn module(self, db: &dyn HirDatabase) -> Module {
1513 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
1516 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1517 db.const_data(self.id).name.clone()
1520 pub fn value(self, db: &dyn HirDatabase) -> Option<ast::Expr> {
1521 self.source(db)?.value.body()
1524 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1525 let data = db.const_data(self.id);
1526 let resolver = self.id.resolver(db.upcast());
1527 let krate = self.id.lookup(db.upcast()).container.krate(db);
1528 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
1529 let ty = ctx.lower_ty(&data.type_ref);
1530 Type::new_with_resolver_inner(db, krate.id, &resolver, ty)
1533 pub fn eval(self, db: &dyn HirDatabase) -> Result<ComputedExpr, ConstEvalError> {
1534 let body = db.body(self.id.into());
1535 let root = &body.exprs[body.body_expr];
1536 let infer = db.infer_query(self.id.into());
1537 let infer = infer.as_ref();
1538 let result = eval_const(
1543 local_data: HashMap::default(),
1544 infer: &mut |x| infer[x].clone(),
1551 impl HasVisibility for Const {
1552 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1553 let function_data = db.const_data(self.id);
1554 let visibility = &function_data.visibility;
1555 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1559 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1561 pub(crate) id: StaticId,
1565 pub fn module(self, db: &dyn HirDatabase) -> Module {
1566 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
1569 pub fn name(self, db: &dyn HirDatabase) -> Name {
1570 db.static_data(self.id).name.clone()
1573 pub fn is_mut(self, db: &dyn HirDatabase) -> bool {
1574 db.static_data(self.id).mutable
1577 pub fn value(self, db: &dyn HirDatabase) -> Option<ast::Expr> {
1578 self.source(db)?.value.body()
1581 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1582 let data = db.static_data(self.id);
1583 let resolver = self.id.resolver(db.upcast());
1584 let krate = self.id.lookup(db.upcast()).container.module(db.upcast()).krate();
1585 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
1586 let ty = ctx.lower_ty(&data.type_ref);
1587 Type::new_with_resolver_inner(db, krate, &resolver, ty)
1591 impl HasVisibility for Static {
1592 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1593 db.static_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1597 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1599 pub(crate) id: TraitId,
1603 pub fn lang(db: &dyn HirDatabase, krate: Crate, name: &Name) -> Option<Trait> {
1604 db.lang_item(krate.into(), name.to_smol_str())
1605 .and_then(LangItemTarget::as_trait)
1609 pub fn module(self, db: &dyn HirDatabase) -> Module {
1610 Module { id: self.id.lookup(db.upcast()).container }
1613 pub fn name(self, db: &dyn HirDatabase) -> Name {
1614 db.trait_data(self.id).name.clone()
1617 pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
1618 db.trait_data(self.id).items.iter().map(|(_name, it)| (*it).into()).collect()
1621 pub fn is_auto(self, db: &dyn HirDatabase) -> bool {
1622 db.trait_data(self.id).is_auto
1625 pub fn is_unsafe(&self, db: &dyn HirDatabase) -> bool {
1626 db.trait_data(self.id).is_unsafe
1630 impl HasVisibility for Trait {
1631 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1632 db.trait_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1636 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1637 pub struct TypeAlias {
1638 pub(crate) id: TypeAliasId,
1642 pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
1643 let subst = db.generic_defaults(self.id.into());
1644 subst.iter().any(|ty| ty.skip_binders().is_unknown())
1647 pub fn module(self, db: &dyn HirDatabase) -> Module {
1648 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
1651 pub fn type_ref(self, db: &dyn HirDatabase) -> Option<TypeRef> {
1652 db.type_alias_data(self.id).type_ref.as_deref().cloned()
1655 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1656 Type::from_def(db, self.id.lookup(db.upcast()).module(db.upcast()).krate(), self.id)
1659 pub fn name(self, db: &dyn HirDatabase) -> Name {
1660 db.type_alias_data(self.id).name.clone()
1664 impl HasVisibility for TypeAlias {
1665 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1666 let function_data = db.type_alias_data(self.id);
1667 let visibility = &function_data.visibility;
1668 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1672 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1673 pub struct BuiltinType {
1674 pub(crate) inner: hir_def::builtin_type::BuiltinType,
1678 pub fn str() -> BuiltinType {
1679 BuiltinType { inner: hir_def::builtin_type::BuiltinType::Str }
1682 pub fn ty(self, db: &dyn HirDatabase, module: Module) -> Type {
1683 let resolver = module.id.resolver(db.upcast());
1684 Type::new_with_resolver(db, &resolver, TyBuilder::builtin(self.inner))
1685 .expect("crate not present in resolver")
1688 pub fn name(self) -> Name {
1689 self.inner.as_name()
1692 pub fn is_int(&self) -> bool {
1693 matches!(self.inner, hir_def::builtin_type::BuiltinType::Int(_))
1696 pub fn is_uint(&self) -> bool {
1697 matches!(self.inner, hir_def::builtin_type::BuiltinType::Uint(_))
1700 pub fn is_float(&self) -> bool {
1701 matches!(self.inner, hir_def::builtin_type::BuiltinType::Float(_))
1704 pub fn is_char(&self) -> bool {
1705 matches!(self.inner, hir_def::builtin_type::BuiltinType::Char)
1708 pub fn is_str(&self) -> bool {
1709 matches!(self.inner, hir_def::builtin_type::BuiltinType::Str)
1713 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1714 pub enum MacroKind {
1715 /// `macro_rules!` or Macros 2.0 macro.
1717 /// A built-in or custom derive.
1719 /// A built-in function-like macro.
1721 /// A procedural attribute macro.
1723 /// A function-like procedural macro.
1727 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1728 pub struct MacroDef {
1729 pub(crate) id: MacroDefId,
1733 /// FIXME: right now, this just returns the root module of the crate that
1734 /// defines this macro. The reasons for this is that macros are expanded
1735 /// early, in `hir_expand`, where modules simply do not exist yet.
1736 pub fn module(self, db: &dyn HirDatabase) -> Option<Module> {
1737 let krate = self.id.krate;
1738 let def_map = db.crate_def_map(krate);
1739 let module_id = def_map.root();
1740 Some(Module { id: def_map.module_id(module_id) })
1743 /// XXX: this parses the file
1744 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1745 match self.source(db)?.value {
1746 Either::Left(it) => it.name().map(|it| it.as_name()),
1747 Either::Right(_) => {
1748 let krate = self.id.krate;
1749 let def_map = db.crate_def_map(krate);
1750 let (_, name) = def_map.exported_proc_macros().find(|&(id, _)| id == self.id)?;
1756 pub fn kind(&self) -> MacroKind {
1757 match self.id.kind {
1758 MacroDefKind::Declarative(_) => MacroKind::Declarative,
1759 MacroDefKind::BuiltIn(_, _) | MacroDefKind::BuiltInEager(_, _) => MacroKind::BuiltIn,
1760 MacroDefKind::BuiltInDerive(_, _) => MacroKind::Derive,
1761 MacroDefKind::BuiltInAttr(_, _) => MacroKind::Attr,
1762 MacroDefKind::ProcMacro(_, base_db::ProcMacroKind::CustomDerive, _) => {
1765 MacroDefKind::ProcMacro(_, base_db::ProcMacroKind::Attr, _) => MacroKind::Attr,
1766 MacroDefKind::ProcMacro(_, base_db::ProcMacroKind::FuncLike, _) => MacroKind::ProcMacro,
1770 pub fn is_fn_like(&self) -> bool {
1772 MacroKind::Declarative | MacroKind::BuiltIn | MacroKind::ProcMacro => true,
1773 MacroKind::Attr | MacroKind::Derive => false,
1777 pub fn is_attr(&self) -> bool {
1778 matches!(self.kind(), MacroKind::Attr)
1782 #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
1789 impl From<MacroDef> for ItemInNs {
1790 fn from(it: MacroDef) -> Self {
1795 impl From<ModuleDef> for ItemInNs {
1796 fn from(module_def: ModuleDef) -> Self {
1798 ModuleDef::Static(_) | ModuleDef::Const(_) | ModuleDef::Function(_) => {
1799 ItemInNs::Values(module_def)
1801 _ => ItemInNs::Types(module_def),
1807 pub fn as_module_def(self) -> Option<ModuleDef> {
1809 ItemInNs::Types(id) | ItemInNs::Values(id) => Some(id),
1810 ItemInNs::Macros(_) => None,
1814 /// Returns the crate defining this item (or `None` if `self` is built-in).
1815 pub fn krate(&self, db: &dyn HirDatabase) -> Option<Crate> {
1817 ItemInNs::Types(did) | ItemInNs::Values(did) => did.module(db).map(|m| m.krate()),
1818 ItemInNs::Macros(id) => id.module(db).map(|m| m.krate()),
1822 pub fn attrs(&self, db: &dyn HirDatabase) -> Option<AttrsWithOwner> {
1824 ItemInNs::Types(it) | ItemInNs::Values(it) => it.attrs(db),
1825 ItemInNs::Macros(it) => Some(it.attrs(db)),
1830 /// Invariant: `inner.as_assoc_item(db).is_some()`
1831 /// We do not actively enforce this invariant.
1832 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1833 pub enum AssocItem {
1836 TypeAlias(TypeAlias),
1839 pub enum AssocItemContainer {
1843 pub trait AsAssocItem {
1844 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem>;
1847 impl AsAssocItem for Function {
1848 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1849 as_assoc_item(db, AssocItem::Function, self.id)
1852 impl AsAssocItem for Const {
1853 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1854 as_assoc_item(db, AssocItem::Const, self.id)
1857 impl AsAssocItem for TypeAlias {
1858 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1859 as_assoc_item(db, AssocItem::TypeAlias, self.id)
1862 impl AsAssocItem for ModuleDef {
1863 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1865 ModuleDef::Function(it) => it.as_assoc_item(db),
1866 ModuleDef::Const(it) => it.as_assoc_item(db),
1867 ModuleDef::TypeAlias(it) => it.as_assoc_item(db),
1872 fn as_assoc_item<ID, DEF, CTOR, AST>(db: &dyn HirDatabase, ctor: CTOR, id: ID) -> Option<AssocItem>
1874 ID: Lookup<Data = AssocItemLoc<AST>>,
1876 CTOR: FnOnce(DEF) -> AssocItem,
1879 match id.lookup(db.upcast()).container {
1880 ItemContainerId::TraitId(_) | ItemContainerId::ImplId(_) => Some(ctor(DEF::from(id))),
1881 ItemContainerId::ModuleId(_) | ItemContainerId::ExternBlockId(_) => None,
1886 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1888 AssocItem::Function(it) => Some(it.name(db)),
1889 AssocItem::Const(it) => it.name(db),
1890 AssocItem::TypeAlias(it) => Some(it.name(db)),
1893 pub fn module(self, db: &dyn HirDatabase) -> Module {
1895 AssocItem::Function(f) => f.module(db),
1896 AssocItem::Const(c) => c.module(db),
1897 AssocItem::TypeAlias(t) => t.module(db),
1900 pub fn container(self, db: &dyn HirDatabase) -> AssocItemContainer {
1901 let container = match self {
1902 AssocItem::Function(it) => it.id.lookup(db.upcast()).container,
1903 AssocItem::Const(it) => it.id.lookup(db.upcast()).container,
1904 AssocItem::TypeAlias(it) => it.id.lookup(db.upcast()).container,
1907 ItemContainerId::TraitId(id) => AssocItemContainer::Trait(id.into()),
1908 ItemContainerId::ImplId(id) => AssocItemContainer::Impl(id.into()),
1909 ItemContainerId::ModuleId(_) | ItemContainerId::ExternBlockId(_) => {
1910 panic!("invalid AssocItem")
1915 pub fn containing_trait(self, db: &dyn HirDatabase) -> Option<Trait> {
1916 match self.container(db) {
1917 AssocItemContainer::Trait(t) => Some(t),
1922 pub fn containing_trait_impl(self, db: &dyn HirDatabase) -> Option<Trait> {
1923 match self.container(db) {
1924 AssocItemContainer::Impl(i) => i.trait_(db),
1929 pub fn containing_trait_or_trait_impl(self, db: &dyn HirDatabase) -> Option<Trait> {
1930 match self.container(db) {
1931 AssocItemContainer::Trait(t) => Some(t),
1932 AssocItemContainer::Impl(i) => i.trait_(db),
1937 impl HasVisibility for AssocItem {
1938 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1940 AssocItem::Function(f) => f.visibility(db),
1941 AssocItem::Const(c) => c.visibility(db),
1942 AssocItem::TypeAlias(t) => t.visibility(db),
1947 impl From<AssocItem> for ModuleDef {
1948 fn from(assoc: AssocItem) -> Self {
1950 AssocItem::Function(it) => ModuleDef::Function(it),
1951 AssocItem::Const(it) => ModuleDef::Const(it),
1952 AssocItem::TypeAlias(it) => ModuleDef::TypeAlias(it),
1957 #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
1958 pub enum GenericDef {
1962 TypeAlias(TypeAlias),
1964 // enum variants cannot have generics themselves, but their parent enums
1965 // can, and this makes some code easier to write
1967 // consts can have type parameters from their parents (i.e. associated consts of traits)
1972 Adt(Struct, Enum, Union),
1982 pub fn params(self, db: &dyn HirDatabase) -> Vec<GenericParam> {
1983 let generics = db.generic_params(self.into());
1984 let ty_params = generics
1987 .map(|(local_id, _)| TypeParam { id: TypeParamId { parent: self.into(), local_id } })
1988 .map(GenericParam::TypeParam);
1989 let lt_params = generics
1992 .map(|(local_id, _)| LifetimeParam {
1993 id: LifetimeParamId { parent: self.into(), local_id },
1995 .map(GenericParam::LifetimeParam);
1996 let const_params = generics
1999 .map(|(local_id, _)| ConstParam { id: ConstParamId { parent: self.into(), local_id } })
2000 .map(GenericParam::ConstParam);
2001 ty_params.chain(lt_params).chain(const_params).collect()
2004 pub fn type_params(self, db: &dyn HirDatabase) -> Vec<TypeParam> {
2005 let generics = db.generic_params(self.into());
2009 .map(|(local_id, _)| TypeParam { id: TypeParamId { parent: self.into(), local_id } })
2014 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2016 pub(crate) parent: DefWithBodyId,
2017 pub(crate) pat_id: PatId,
2021 pub fn is_param(self, db: &dyn HirDatabase) -> bool {
2022 let src = self.source(db);
2024 Either::Left(bind_pat) => {
2025 bind_pat.syntax().ancestors().any(|it| ast::Param::can_cast(it.kind()))
2027 Either::Right(_self_param) => true,
2031 pub fn as_self_param(self, db: &dyn HirDatabase) -> Option<SelfParam> {
2033 DefWithBodyId::FunctionId(func) if self.is_self(db) => Some(SelfParam { func }),
2038 // FIXME: why is this an option? It shouldn't be?
2039 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
2040 let body = db.body(self.parent);
2041 match &body[self.pat_id] {
2042 Pat::Bind { name, .. } => Some(name.clone()),
2047 pub fn is_self(self, db: &dyn HirDatabase) -> bool {
2048 self.name(db) == Some(name![self])
2051 pub fn is_mut(self, db: &dyn HirDatabase) -> bool {
2052 let body = db.body(self.parent);
2053 matches!(&body[self.pat_id], Pat::Bind { mode: BindingAnnotation::Mutable, .. })
2056 pub fn is_ref(self, db: &dyn HirDatabase) -> bool {
2057 let body = db.body(self.parent);
2060 Pat::Bind { mode: BindingAnnotation::Ref | BindingAnnotation::RefMut, .. }
2064 pub fn parent(self, _db: &dyn HirDatabase) -> DefWithBody {
2068 pub fn module(self, db: &dyn HirDatabase) -> Module {
2069 self.parent(db).module(db)
2072 pub fn ty(self, db: &dyn HirDatabase) -> Type {
2073 let def = self.parent;
2074 let infer = db.infer(def);
2075 let ty = infer[self.pat_id].clone();
2076 let krate = def.module(db.upcast()).krate();
2077 Type::new(db, krate, def, ty)
2080 pub fn source(self, db: &dyn HirDatabase) -> InFile<Either<ast::IdentPat, ast::SelfParam>> {
2081 let (_body, source_map) = db.body_with_source_map(self.parent);
2082 let src = source_map.pat_syntax(self.pat_id).unwrap(); // Hmm...
2083 let root = src.file_syntax(db.upcast());
2085 ast.map_left(|it| it.cast().unwrap().to_node(&root)).map_right(|it| it.to_node(&root))
2090 // FIXME: Wrong name? This is could also be a registered attribute
2091 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2092 pub struct BuiltinAttr {
2093 krate: Option<CrateId>,
2098 // FIXME: consider crates\hir_def\src\nameres\attr_resolution.rs?
2099 pub(crate) fn by_name(db: &dyn HirDatabase, krate: Crate, name: &str) -> Option<Self> {
2100 if let builtin @ Some(_) = Self::builtin(name) {
2103 let idx = db.crate_def_map(krate.id).registered_attrs().iter().position(|it| it == name)?;
2104 Some(BuiltinAttr { krate: Some(krate.id), idx })
2107 pub(crate) fn builtin(name: &str) -> Option<Self> {
2108 hir_def::builtin_attr::INERT_ATTRIBUTES
2110 .position(|tool| tool.name == name)
2111 .map(|idx| BuiltinAttr { krate: None, idx })
2114 pub fn name(&self, db: &dyn HirDatabase) -> SmolStr {
2115 // FIXME: Return a `Name` here
2117 Some(krate) => db.crate_def_map(krate).registered_attrs()[self.idx].clone(),
2118 None => SmolStr::new(hir_def::builtin_attr::INERT_ATTRIBUTES[self.idx].name),
2122 pub fn template(&self, _: &dyn HirDatabase) -> Option<AttributeTemplate> {
2125 None => Some(hir_def::builtin_attr::INERT_ATTRIBUTES[self.idx].template),
2130 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2131 pub struct ToolModule {
2132 krate: Option<CrateId>,
2137 // FIXME: consider crates\hir_def\src\nameres\attr_resolution.rs?
2138 pub(crate) fn by_name(db: &dyn HirDatabase, krate: Crate, name: &str) -> Option<Self> {
2139 if let builtin @ Some(_) = Self::builtin(name) {
2142 let idx = db.crate_def_map(krate.id).registered_tools().iter().position(|it| it == name)?;
2143 Some(ToolModule { krate: Some(krate.id), idx })
2146 pub(crate) fn builtin(name: &str) -> Option<Self> {
2147 hir_def::builtin_attr::TOOL_MODULES
2149 .position(|&tool| tool == name)
2150 .map(|idx| ToolModule { krate: None, idx })
2153 pub fn name(&self, db: &dyn HirDatabase) -> SmolStr {
2154 // FIXME: Return a `Name` here
2156 Some(krate) => db.crate_def_map(krate).registered_tools()[self.idx].clone(),
2157 None => SmolStr::new(hir_def::builtin_attr::TOOL_MODULES[self.idx]),
2162 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2164 pub(crate) parent: DefWithBodyId,
2165 pub(crate) label_id: LabelId,
2169 pub fn module(self, db: &dyn HirDatabase) -> Module {
2170 self.parent(db).module(db)
2173 pub fn parent(self, _db: &dyn HirDatabase) -> DefWithBody {
2177 pub fn name(self, db: &dyn HirDatabase) -> Name {
2178 let body = db.body(self.parent);
2179 body[self.label_id].name.clone()
2182 pub fn source(self, db: &dyn HirDatabase) -> InFile<ast::Label> {
2183 let (_body, source_map) = db.body_with_source_map(self.parent);
2184 let src = source_map.label_syntax(self.label_id);
2185 let root = src.file_syntax(db.upcast());
2186 src.map(|ast| ast.to_node(&root))
2190 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2191 pub enum GenericParam {
2192 TypeParam(TypeParam),
2193 LifetimeParam(LifetimeParam),
2194 ConstParam(ConstParam),
2196 impl_from!(TypeParam, LifetimeParam, ConstParam for GenericParam);
2199 pub fn module(self, db: &dyn HirDatabase) -> Module {
2201 GenericParam::TypeParam(it) => it.module(db),
2202 GenericParam::LifetimeParam(it) => it.module(db),
2203 GenericParam::ConstParam(it) => it.module(db),
2207 pub fn name(self, db: &dyn HirDatabase) -> Name {
2209 GenericParam::TypeParam(it) => it.name(db),
2210 GenericParam::LifetimeParam(it) => it.name(db),
2211 GenericParam::ConstParam(it) => it.name(db),
2216 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2217 pub struct TypeParam {
2218 pub(crate) id: TypeParamId,
2222 pub fn name(self, db: &dyn HirDatabase) -> Name {
2223 let params = db.generic_params(self.id.parent);
2224 params.types[self.id.local_id].name.clone().unwrap_or_else(Name::missing)
2227 pub fn module(self, db: &dyn HirDatabase) -> Module {
2228 self.id.parent.module(db.upcast()).into()
2231 pub fn ty(self, db: &dyn HirDatabase) -> Type {
2232 let resolver = self.id.parent.resolver(db.upcast());
2233 let krate = self.id.parent.module(db.upcast()).krate();
2234 let ty = TyKind::Placeholder(hir_ty::to_placeholder_idx(db, self.id)).intern(Interner);
2235 Type::new_with_resolver_inner(db, krate, &resolver, ty)
2238 pub fn trait_bounds(self, db: &dyn HirDatabase) -> Vec<Trait> {
2239 db.generic_predicates_for_param(self.id, None)
2241 .filter_map(|pred| match &pred.skip_binders().skip_binders() {
2242 hir_ty::WhereClause::Implemented(trait_ref) => {
2243 Some(Trait::from(trait_ref.hir_trait_id()))
2250 pub fn default(self, db: &dyn HirDatabase) -> Option<Type> {
2251 let params = db.generic_defaults(self.id.parent);
2252 let local_idx = hir_ty::param_idx(db, self.id)?;
2253 let resolver = self.id.parent.resolver(db.upcast());
2254 let krate = self.id.parent.module(db.upcast()).krate();
2255 let ty = params.get(local_idx)?.clone();
2256 let subst = TyBuilder::type_params_subst(db, self.id.parent);
2257 let ty = ty.substitute(Interner, &subst_prefix(&subst, local_idx));
2258 Some(Type::new_with_resolver_inner(db, krate, &resolver, ty))
2262 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2263 pub struct LifetimeParam {
2264 pub(crate) id: LifetimeParamId,
2267 impl LifetimeParam {
2268 pub fn name(self, db: &dyn HirDatabase) -> Name {
2269 let params = db.generic_params(self.id.parent);
2270 params.lifetimes[self.id.local_id].name.clone()
2273 pub fn module(self, db: &dyn HirDatabase) -> Module {
2274 self.id.parent.module(db.upcast()).into()
2277 pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef {
2278 self.id.parent.into()
2282 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2283 pub struct ConstParam {
2284 pub(crate) id: ConstParamId,
2288 pub fn name(self, db: &dyn HirDatabase) -> Name {
2289 let params = db.generic_params(self.id.parent);
2290 params.consts[self.id.local_id].name.clone()
2293 pub fn module(self, db: &dyn HirDatabase) -> Module {
2294 self.id.parent.module(db.upcast()).into()
2297 pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef {
2298 self.id.parent.into()
2301 pub fn ty(self, db: &dyn HirDatabase) -> Type {
2302 let def = self.id.parent;
2303 let krate = def.module(db.upcast()).krate();
2304 Type::new(db, krate, def, db.const_param_ty(self.id))
2308 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2310 pub(crate) id: ImplId,
2314 pub fn all_in_crate(db: &dyn HirDatabase, krate: Crate) -> Vec<Impl> {
2315 let inherent = db.inherent_impls_in_crate(krate.id);
2316 let trait_ = db.trait_impls_in_crate(krate.id);
2318 inherent.all_impls().chain(trait_.all_impls()).map(Self::from).collect()
2321 pub fn all_for_type(db: &dyn HirDatabase, Type { krate, ty, .. }: Type) -> Vec<Impl> {
2322 let def_crates = match method_resolution::def_crates(db, &ty, krate) {
2323 Some(def_crates) => def_crates,
2324 None => return Vec::new(),
2327 let filter = |impl_def: &Impl| {
2328 let self_ty = impl_def.self_ty(db);
2329 let rref = self_ty.remove_ref();
2330 ty.equals_ctor(rref.as_ref().map_or(&self_ty.ty, |it| &it.ty))
2333 let fp = TyFingerprint::for_inherent_impl(&ty);
2336 None => return Vec::new(),
2339 let mut all = Vec::new();
2340 def_crates.iter().for_each(|&id| {
2342 db.inherent_impls_in_crate(id)
2350 for id in def_crates
2352 .flat_map(|&id| Crate { id }.transitive_reverse_dependencies(db))
2353 .map(|Crate { id }| id)
2354 .chain(def_crates.iter().copied())
2358 db.trait_impls_in_crate(id)
2359 .for_self_ty_without_blanket_impls(fp)
2367 pub fn all_for_trait(db: &dyn HirDatabase, trait_: Trait) -> Vec<Impl> {
2368 let krate = trait_.module(db).krate();
2369 let mut all = Vec::new();
2370 for Crate { id } in krate.transitive_reverse_dependencies(db).into_iter() {
2371 let impls = db.trait_impls_in_crate(id);
2372 all.extend(impls.for_trait(trait_.id).map(Self::from))
2377 // FIXME: the return type is wrong. This should be a hir version of
2378 // `TraitRef` (to account for parameters and qualifiers)
2379 pub fn trait_(self, db: &dyn HirDatabase) -> Option<Trait> {
2380 let trait_ref = db.impl_trait(self.id)?.skip_binders().clone();
2381 let id = hir_ty::from_chalk_trait_id(trait_ref.trait_id);
2385 pub fn self_ty(self, db: &dyn HirDatabase) -> Type {
2386 let impl_data = db.impl_data(self.id);
2387 let resolver = self.id.resolver(db.upcast());
2388 let krate = self.id.lookup(db.upcast()).container.krate();
2389 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
2390 let ty = ctx.lower_ty(&impl_data.self_ty);
2391 Type::new_with_resolver_inner(db, krate, &resolver, ty)
2394 pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
2395 db.impl_data(self.id).items.iter().map(|it| (*it).into()).collect()
2398 pub fn is_negative(self, db: &dyn HirDatabase) -> bool {
2399 db.impl_data(self.id).is_negative
2402 pub fn module(self, db: &dyn HirDatabase) -> Module {
2403 self.id.lookup(db.upcast()).container.into()
2406 pub fn is_builtin_derive(self, db: &dyn HirDatabase) -> Option<InFile<ast::Attr>> {
2407 let src = self.source(db)?;
2408 let item = src.file_id.is_builtin_derive(db.upcast())?;
2409 let hygenic = hir_expand::hygiene::Hygiene::new(db.upcast(), item.file_id);
2411 // FIXME: handle `cfg_attr`
2416 let path = ModPath::from_src(db.upcast(), it.path()?, &hygenic)?;
2417 if path.as_ident()?.to_smol_str() == "derive" {
2425 Some(item.with_value(attr))
2429 #[derive(Clone, PartialEq, Eq, Debug)]
2432 env: Arc<TraitEnvironment>,
2437 pub(crate) fn new_with_resolver(
2438 db: &dyn HirDatabase,
2439 resolver: &Resolver,
2442 let krate = resolver.krate()?;
2443 Some(Type::new_with_resolver_inner(db, krate, resolver, ty))
2445 pub(crate) fn new_with_resolver_inner(
2446 db: &dyn HirDatabase,
2448 resolver: &Resolver,
2451 let environment = resolver
2453 .map_or_else(|| Arc::new(TraitEnvironment::empty(krate)), |d| db.trait_environment(d));
2454 Type { krate, env: environment, ty }
2457 fn new(db: &dyn HirDatabase, krate: CrateId, lexical_env: impl HasResolver, ty: Ty) -> Type {
2458 let resolver = lexical_env.resolver(db.upcast());
2459 let environment = resolver
2461 .map_or_else(|| Arc::new(TraitEnvironment::empty(krate)), |d| db.trait_environment(d));
2462 Type { krate, env: environment, ty }
2466 db: &dyn HirDatabase,
2468 def: impl HasResolver + Into<TyDefId>,
2470 let ty = TyBuilder::def_ty(db, def.into()).fill_with_unknown().build();
2471 Type::new(db, krate, def, ty)
2474 pub fn new_slice(ty: Type) -> Type {
2475 Type { krate: ty.krate, env: ty.env, ty: TyBuilder::slice(ty.ty) }
2478 pub fn is_unit(&self) -> bool {
2479 matches!(self.ty.kind(Interner), TyKind::Tuple(0, ..))
2482 pub fn is_bool(&self) -> bool {
2483 matches!(self.ty.kind(Interner), TyKind::Scalar(Scalar::Bool))
2486 pub fn is_never(&self) -> bool {
2487 matches!(self.ty.kind(Interner), TyKind::Never)
2490 pub fn is_mutable_reference(&self) -> bool {
2491 matches!(self.ty.kind(Interner), TyKind::Ref(hir_ty::Mutability::Mut, ..))
2494 pub fn is_reference(&self) -> bool {
2495 matches!(self.ty.kind(Interner), TyKind::Ref(..))
2498 pub fn is_usize(&self) -> bool {
2499 matches!(self.ty.kind(Interner), TyKind::Scalar(Scalar::Uint(UintTy::Usize)))
2502 pub fn remove_ref(&self) -> Option<Type> {
2503 match &self.ty.kind(Interner) {
2504 TyKind::Ref(.., ty) => Some(self.derived(ty.clone())),
2509 pub fn strip_references(&self) -> Type {
2510 self.derived(self.ty.strip_references().clone())
2513 pub fn is_unknown(&self) -> bool {
2514 self.ty.is_unknown()
2517 /// Checks that particular type `ty` implements `std::future::Future`.
2518 /// This function is used in `.await` syntax completion.
2519 pub fn impls_future(&self, db: &dyn HirDatabase) -> bool {
2520 // No special case for the type of async block, since Chalk can figure it out.
2522 let krate = self.krate;
2524 let std_future_trait =
2525 db.lang_item(krate, SmolStr::new_inline("future_trait")).and_then(|it| it.as_trait());
2526 let std_future_trait = match std_future_trait {
2528 None => return false,
2532 Canonical { value: self.ty.clone(), binders: CanonicalVarKinds::empty(Interner) };
2533 method_resolution::implements_trait(
2542 /// Checks that particular type `ty` implements `std::ops::FnOnce`.
2544 /// This function can be used to check if a particular type is callable, since FnOnce is a
2545 /// supertrait of Fn and FnMut, so all callable types implements at least FnOnce.
2546 pub fn impls_fnonce(&self, db: &dyn HirDatabase) -> bool {
2547 let krate = self.krate;
2549 let fnonce_trait = match FnTrait::FnOnce.get_id(db, krate) {
2551 None => return false,
2555 Canonical { value: self.ty.clone(), binders: CanonicalVarKinds::empty(Interner) };
2556 method_resolution::implements_trait_unique(
2565 pub fn impls_trait(&self, db: &dyn HirDatabase, trait_: Trait, args: &[Type]) -> bool {
2566 let trait_ref = TyBuilder::trait_ref(db, trait_.id)
2567 .push(self.ty.clone())
2568 .fill(args.iter().map(|t| t.ty.clone()))
2571 let goal = Canonical {
2572 value: hir_ty::InEnvironment::new(&self.env.env, trait_ref.cast(Interner)),
2573 binders: CanonicalVarKinds::empty(Interner),
2576 db.trait_solve(self.krate, goal).is_some()
2579 pub fn normalize_trait_assoc_type(
2581 db: &dyn HirDatabase,
2585 let projection = TyBuilder::assoc_type_projection(db, alias.id)
2586 .push(self.ty.clone())
2587 .fill(args.iter().map(|t| t.ty.clone()))
2589 let goal = hir_ty::make_canonical(
2593 alias: AliasTy::Projection(projection),
2594 ty: TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0))
2599 [TyVariableKind::General].into_iter(),
2602 match db.trait_solve(self.krate, goal)? {
2603 Solution::Unique(s) => s
2608 .map(|ty| self.derived(ty.assert_ty_ref(Interner).clone())),
2609 Solution::Ambig(_) => None,
2613 pub fn is_copy(&self, db: &dyn HirDatabase) -> bool {
2614 let lang_item = db.lang_item(self.krate, SmolStr::new_inline("copy"));
2615 let copy_trait = match lang_item {
2616 Some(LangItemTarget::TraitId(it)) => it,
2619 self.impls_trait(db, copy_trait.into(), &[])
2622 pub fn as_callable(&self, db: &dyn HirDatabase) -> Option<Callable> {
2623 let def = self.ty.callable_def(db);
2625 let sig = self.ty.callable_sig(db)?;
2626 Some(Callable { ty: self.clone(), sig, def, is_bound_method: false })
2629 pub fn is_closure(&self) -> bool {
2630 matches!(&self.ty.kind(Interner), TyKind::Closure { .. })
2633 pub fn is_fn(&self) -> bool {
2634 matches!(&self.ty.kind(Interner), TyKind::FnDef(..) | TyKind::Function { .. })
2637 pub fn is_array(&self) -> bool {
2638 matches!(&self.ty.kind(Interner), TyKind::Array(..))
2641 pub fn is_packed(&self, db: &dyn HirDatabase) -> bool {
2642 let adt_id = match *self.ty.kind(Interner) {
2643 TyKind::Adt(hir_ty::AdtId(adt_id), ..) => adt_id,
2647 let adt = adt_id.into();
2649 Adt::Struct(s) => matches!(s.repr(db), Some(ReprKind::Packed)),
2654 pub fn is_raw_ptr(&self) -> bool {
2655 matches!(&self.ty.kind(Interner), TyKind::Raw(..))
2658 pub fn contains_unknown(&self) -> bool {
2659 return go(&self.ty);
2661 fn go(ty: &Ty) -> bool {
2662 match ty.kind(Interner) {
2663 TyKind::Error => true,
2665 TyKind::Adt(_, substs)
2666 | TyKind::AssociatedType(_, substs)
2667 | TyKind::Tuple(_, substs)
2668 | TyKind::OpaqueType(_, substs)
2669 | TyKind::FnDef(_, substs)
2670 | TyKind::Closure(_, substs) => {
2671 substs.iter(Interner).filter_map(|a| a.ty(Interner)).any(go)
2674 TyKind::Array(_ty, len) if len.is_unknown() => true,
2675 TyKind::Array(ty, _)
2677 | TyKind::Raw(_, ty)
2678 | TyKind::Ref(_, _, ty) => go(ty),
2683 | TyKind::Placeholder(_)
2684 | TyKind::BoundVar(_)
2685 | TyKind::InferenceVar(_, _)
2687 | TyKind::Function(_)
2689 | TyKind::Foreign(_)
2690 | TyKind::Generator(..)
2691 | TyKind::GeneratorWitness(..) => false,
2696 pub fn fields(&self, db: &dyn HirDatabase) -> Vec<(Field, Type)> {
2697 let (variant_id, substs) = match self.ty.kind(Interner) {
2698 TyKind::Adt(hir_ty::AdtId(AdtId::StructId(s)), substs) => ((*s).into(), substs),
2699 TyKind::Adt(hir_ty::AdtId(AdtId::UnionId(u)), substs) => ((*u).into(), substs),
2700 _ => return Vec::new(),
2703 db.field_types(variant_id)
2705 .map(|(local_id, ty)| {
2706 let def = Field { parent: variant_id.into(), id: local_id };
2707 let ty = ty.clone().substitute(Interner, substs);
2708 (def, self.derived(ty))
2713 pub fn tuple_fields(&self, _db: &dyn HirDatabase) -> Vec<Type> {
2714 if let TyKind::Tuple(_, substs) = &self.ty.kind(Interner) {
2717 .map(|ty| self.derived(ty.assert_ty_ref(Interner).clone()))
2724 pub fn autoderef<'a>(&'a self, db: &'a dyn HirDatabase) -> impl Iterator<Item = Type> + 'a {
2725 self.autoderef_(db).map(move |ty| self.derived(ty))
2728 pub fn autoderef_<'a>(&'a self, db: &'a dyn HirDatabase) -> impl Iterator<Item = Ty> + 'a {
2729 // There should be no inference vars in types passed here
2730 let canonical = hir_ty::replace_errors_with_variables(&self.ty);
2731 let environment = self.env.env.clone();
2732 let ty = InEnvironment { goal: canonical, environment };
2733 autoderef(db, Some(self.krate), ty).map(|canonical| canonical.value)
2736 // This would be nicer if it just returned an iterator, but that runs into
2737 // lifetime problems, because we need to borrow temp `CrateImplDefs`.
2738 pub fn iterate_assoc_items<T>(
2740 db: &dyn HirDatabase,
2742 mut callback: impl FnMut(AssocItem) -> Option<T>,
2744 let mut slot = None;
2745 self.iterate_assoc_items_dyn(db, krate, &mut |assoc_item_id| {
2746 slot = callback(assoc_item_id.into());
2752 fn iterate_assoc_items_dyn(
2754 db: &dyn HirDatabase,
2756 callback: &mut dyn FnMut(AssocItemId) -> bool,
2758 let def_crates = match method_resolution::def_crates(db, &self.ty, krate.id) {
2762 for krate in def_crates {
2763 let impls = db.inherent_impls_in_crate(krate);
2765 for impl_def in impls.for_self_ty(&self.ty) {
2766 for &item in db.impl_data(*impl_def).items.iter() {
2775 pub fn type_arguments(&self) -> impl Iterator<Item = Type> + '_ {
2780 .flat_map(|(_, substs)| substs.iter(Interner))
2781 .filter_map(|arg| arg.ty(Interner).cloned())
2782 .map(move |ty| self.derived(ty))
2785 pub fn iterate_method_candidates<T>(
2787 db: &dyn HirDatabase,
2789 traits_in_scope: &FxHashSet<TraitId>,
2790 name: Option<&Name>,
2791 mut callback: impl FnMut(Type, Function) -> Option<T>,
2793 let _p = profile::span("iterate_method_candidates");
2794 let mut slot = None;
2796 self.iterate_method_candidates_dyn(
2801 &mut |ty, assoc_item_id| {
2802 if let AssocItemId::FunctionId(func) = assoc_item_id {
2803 if let Some(res) = callback(self.derived(ty.clone()), func.into()) {
2805 return ControlFlow::Break(());
2808 ControlFlow::Continue(())
2814 fn iterate_method_candidates_dyn(
2816 db: &dyn HirDatabase,
2818 traits_in_scope: &FxHashSet<TraitId>,
2819 name: Option<&Name>,
2820 callback: &mut dyn FnMut(&Ty, AssocItemId) -> ControlFlow<()>,
2822 // There should be no inference vars in types passed here
2823 let canonical = hir_ty::replace_errors_with_variables(&self.ty);
2825 let env = self.env.clone();
2826 let krate = krate.id;
2828 method_resolution::iterate_method_candidates_dyn(
2836 method_resolution::LookupMode::MethodCall,
2837 &mut |ty, id| callback(&ty.value, id),
2841 pub fn iterate_path_candidates<T>(
2843 db: &dyn HirDatabase,
2845 traits_in_scope: &FxHashSet<TraitId>,
2846 name: Option<&Name>,
2847 mut callback: impl FnMut(Type, AssocItem) -> Option<T>,
2849 let _p = profile::span("iterate_path_candidates");
2850 let mut slot = None;
2851 self.iterate_path_candidates_dyn(
2856 &mut |ty, assoc_item_id| {
2857 if let Some(res) = callback(self.derived(ty.clone()), assoc_item_id.into()) {
2859 return ControlFlow::Break(());
2861 ControlFlow::Continue(())
2867 fn iterate_path_candidates_dyn(
2869 db: &dyn HirDatabase,
2871 traits_in_scope: &FxHashSet<TraitId>,
2872 name: Option<&Name>,
2873 callback: &mut dyn FnMut(&Ty, AssocItemId) -> ControlFlow<()>,
2875 let canonical = hir_ty::replace_errors_with_variables(&self.ty);
2877 let env = self.env.clone();
2878 let krate = krate.id;
2880 method_resolution::iterate_method_candidates_dyn(
2888 method_resolution::LookupMode::Path,
2889 &mut |ty, id| callback(&ty.value, id),
2893 pub fn as_adt(&self) -> Option<Adt> {
2894 let (adt, _subst) = self.ty.as_adt()?;
2898 pub fn as_builtin(&self) -> Option<BuiltinType> {
2899 self.ty.as_builtin().map(|inner| BuiltinType { inner })
2902 pub fn as_dyn_trait(&self) -> Option<Trait> {
2903 self.ty.dyn_trait().map(Into::into)
2906 /// If a type can be represented as `dyn Trait`, returns all traits accessible via this type,
2907 /// or an empty iterator otherwise.
2908 pub fn applicable_inherent_traits<'a>(
2910 db: &'a dyn HirDatabase,
2911 ) -> impl Iterator<Item = Trait> + 'a {
2912 let _p = profile::span("applicable_inherent_traits");
2914 .filter_map(|ty| ty.dyn_trait())
2915 .flat_map(move |dyn_trait_id| hir_ty::all_super_traits(db.upcast(), dyn_trait_id))
2919 pub fn env_traits<'a>(&'a self, db: &'a dyn HirDatabase) -> impl Iterator<Item = Trait> + 'a {
2920 let _p = profile::span("env_traits");
2922 .filter(|ty| matches!(ty.kind(Interner), TyKind::Placeholder(_)))
2925 .traits_in_scope_from_clauses(ty)
2926 .flat_map(|t| hir_ty::all_super_traits(db.upcast(), t))
2931 pub fn as_impl_traits(&self, db: &dyn HirDatabase) -> Option<impl Iterator<Item = Trait>> {
2932 self.ty.impl_trait_bounds(db).map(|it| {
2933 it.into_iter().filter_map(|pred| match pred.skip_binders() {
2934 hir_ty::WhereClause::Implemented(trait_ref) => {
2935 Some(Trait::from(trait_ref.hir_trait_id()))
2942 pub fn as_associated_type_parent_trait(&self, db: &dyn HirDatabase) -> Option<Trait> {
2943 self.ty.associated_type_parent_trait(db).map(Into::into)
2946 fn derived(&self, ty: Ty) -> Type {
2947 Type { krate: self.krate, env: self.env.clone(), ty }
2950 pub fn walk(&self, db: &dyn HirDatabase, mut cb: impl FnMut(Type)) {
2951 // TypeWalk::walk for a Ty at first visits parameters and only after that the Ty itself.
2952 // We need a different order here.
2955 db: &dyn HirDatabase,
2957 substs: &Substitution,
2958 cb: &mut impl FnMut(Type),
2960 for ty in substs.iter(Interner).filter_map(|a| a.ty(Interner)) {
2961 walk_type(db, &type_.derived(ty.clone()), cb);
2966 db: &dyn HirDatabase,
2968 bounds: &[QuantifiedWhereClause],
2969 cb: &mut impl FnMut(Type),
2971 for pred in bounds {
2972 if let WhereClause::Implemented(trait_ref) = pred.skip_binders() {
2974 // skip the self type. it's likely the type we just got the bounds from
2976 trait_ref.substitution.iter(Interner).skip(1).filter_map(|a| a.ty(Interner))
2978 walk_type(db, &type_.derived(ty.clone()), cb);
2984 fn walk_type(db: &dyn HirDatabase, type_: &Type, cb: &mut impl FnMut(Type)) {
2985 let ty = type_.ty.strip_references();
2986 match ty.kind(Interner) {
2987 TyKind::Adt(_, substs) => {
2988 cb(type_.derived(ty.clone()));
2989 walk_substs(db, type_, substs, cb);
2991 TyKind::AssociatedType(_, substs) => {
2992 if ty.associated_type_parent_trait(db).is_some() {
2993 cb(type_.derived(ty.clone()));
2995 walk_substs(db, type_, substs, cb);
2997 TyKind::OpaqueType(_, subst) => {
2998 if let Some(bounds) = ty.impl_trait_bounds(db) {
2999 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
3002 walk_substs(db, type_, subst, cb);
3004 TyKind::Alias(AliasTy::Opaque(opaque_ty)) => {
3005 if let Some(bounds) = ty.impl_trait_bounds(db) {
3006 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
3009 walk_substs(db, type_, &opaque_ty.substitution, cb);
3011 TyKind::Placeholder(_) => {
3012 if let Some(bounds) = ty.impl_trait_bounds(db) {
3013 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
3016 TyKind::Dyn(bounds) => {
3019 &type_.derived(ty.clone()),
3020 bounds.bounds.skip_binders().interned(),
3025 TyKind::Ref(_, _, ty)
3026 | TyKind::Raw(_, ty)
3027 | TyKind::Array(ty, _)
3028 | TyKind::Slice(ty) => {
3029 walk_type(db, &type_.derived(ty.clone()), cb);
3032 TyKind::FnDef(_, substs)
3033 | TyKind::Tuple(_, substs)
3034 | TyKind::Closure(.., substs) => {
3035 walk_substs(db, type_, substs, cb);
3037 TyKind::Function(hir_ty::FnPointer { substitution, .. }) => {
3038 walk_substs(db, type_, &substitution.0, cb);
3045 walk_type(db, self, &mut cb);
3048 pub fn could_unify_with(&self, db: &dyn HirDatabase, other: &Type) -> bool {
3049 let tys = hir_ty::replace_errors_with_variables(&(self.ty.clone(), other.ty.clone()));
3050 could_unify(db, self.env.clone(), &tys)
3056 pub struct Callable {
3059 def: Option<CallableDefId>,
3060 pub(crate) is_bound_method: bool,
3063 pub enum CallableKind {
3065 TupleStruct(Struct),
3066 TupleEnumVariant(Variant),
3071 pub fn kind(&self) -> CallableKind {
3073 Some(CallableDefId::FunctionId(it)) => CallableKind::Function(it.into()),
3074 Some(CallableDefId::StructId(it)) => CallableKind::TupleStruct(it.into()),
3075 Some(CallableDefId::EnumVariantId(it)) => CallableKind::TupleEnumVariant(it.into()),
3076 None => CallableKind::Closure,
3079 pub fn receiver_param(&self, db: &dyn HirDatabase) -> Option<ast::SelfParam> {
3080 let func = match self.def {
3081 Some(CallableDefId::FunctionId(it)) if self.is_bound_method => it,
3084 let src = func.lookup(db.upcast()).source(db.upcast());
3085 let param_list = src.value.param_list()?;
3086 param_list.self_param()
3088 pub fn n_params(&self) -> usize {
3089 self.sig.params().len() - if self.is_bound_method { 1 } else { 0 }
3093 db: &dyn HirDatabase,
3094 ) -> Vec<(Option<Either<ast::SelfParam, ast::Pat>>, Type)> {
3099 .skip(if self.is_bound_method { 1 } else { 0 })
3100 .map(|ty| self.ty.derived(ty.clone()));
3101 let patterns = match self.def {
3102 Some(CallableDefId::FunctionId(func)) => {
3103 let src = func.lookup(db.upcast()).source(db.upcast());
3104 src.value.param_list().map(|param_list| {
3107 .map(|it| Some(Either::Left(it)))
3108 .filter(|_| !self.is_bound_method)
3110 .chain(param_list.params().map(|it| it.pat().map(Either::Right)))
3115 patterns.into_iter().flatten().chain(iter::repeat(None)).zip(types).collect()
3117 pub fn return_type(&self) -> Type {
3118 self.ty.derived(self.sig.ret().clone())
3123 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
3125 ModuleDef(ModuleDef),
3127 GenericParam(GenericParam),
3136 pub fn all_items(def: PerNs) -> ArrayVec<Self, 3> {
3137 let mut items = ArrayVec::new();
3139 match (def.take_types(), def.take_values()) {
3140 (Some(m1), None) => items.push(ScopeDef::ModuleDef(m1.into())),
3141 (None, Some(m2)) => items.push(ScopeDef::ModuleDef(m2.into())),
3142 (Some(m1), Some(m2)) => {
3143 // Some items, like unit structs and enum variants, are
3144 // returned as both a type and a value. Here we want
3145 // to de-duplicate them.
3147 items.push(ScopeDef::ModuleDef(m1.into()));
3148 items.push(ScopeDef::ModuleDef(m2.into()));
3150 items.push(ScopeDef::ModuleDef(m1.into()));
3156 if let Some(macro_def_id) = def.take_macros() {
3157 items.push(ScopeDef::MacroDef(macro_def_id.into()));
3160 if items.is_empty() {
3161 items.push(ScopeDef::Unknown);
3167 pub fn attrs(&self, db: &dyn HirDatabase) -> Option<AttrsWithOwner> {
3169 ScopeDef::ModuleDef(it) => it.attrs(db),
3170 ScopeDef::MacroDef(it) => Some(it.attrs(db)),
3171 ScopeDef::GenericParam(it) => Some(it.attrs(db)),
3172 ScopeDef::ImplSelfType(_)
3173 | ScopeDef::AdtSelfType(_)
3174 | ScopeDef::Local(_)
3175 | ScopeDef::Label(_)
3176 | ScopeDef::Unknown => None,
3180 pub fn krate(&self, db: &dyn HirDatabase) -> Option<Crate> {
3182 ScopeDef::ModuleDef(it) => it.module(db).map(|m| m.krate()),
3183 ScopeDef::MacroDef(it) => it.module(db).map(|m| m.krate()),
3184 ScopeDef::GenericParam(it) => Some(it.module(db).krate()),
3185 ScopeDef::ImplSelfType(_) => None,
3186 ScopeDef::AdtSelfType(it) => Some(it.module(db).krate()),
3187 ScopeDef::Local(it) => Some(it.module(db).krate()),
3188 ScopeDef::Label(it) => Some(it.module(db).krate()),
3189 ScopeDef::Unknown => None,
3194 impl From<ItemInNs> for ScopeDef {
3195 fn from(item: ItemInNs) -> Self {
3197 ItemInNs::Types(id) => ScopeDef::ModuleDef(id),
3198 ItemInNs::Values(id) => ScopeDef::ModuleDef(id),
3199 ItemInNs::Macros(id) => ScopeDef::MacroDef(id),
3204 pub trait HasVisibility {
3205 fn visibility(&self, db: &dyn HirDatabase) -> Visibility;
3206 fn is_visible_from(&self, db: &dyn HirDatabase, module: Module) -> bool {
3207 let vis = self.visibility(db);
3208 vis.is_visible_from(db.upcast(), module.id)
3212 /// Trait for obtaining the defining crate of an item.
3213 pub trait HasCrate {
3214 fn krate(&self, db: &dyn HirDatabase) -> Crate;
3217 impl<T: hir_def::HasModule> HasCrate for T {
3218 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3219 self.module(db.upcast()).krate().into()
3223 impl HasCrate for AssocItem {
3224 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3225 self.module(db).krate()
3229 impl HasCrate for Field {
3230 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3231 self.parent_def(db).module(db).krate()
3235 impl HasCrate for Function {
3236 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3237 self.module(db).krate()
3241 impl HasCrate for Const {
3242 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3243 self.module(db).krate()
3247 impl HasCrate for TypeAlias {
3248 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3249 self.module(db).krate()
3253 impl HasCrate for Type {
3254 fn krate(&self, _db: &dyn HirDatabase) -> Crate {