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 #![warn(rust_2018_idioms, unused_lifetimes, semicolon_in_expressions_from_macros)]
21 #![recursion_limit = "512"]
36 use std
::{iter, ops::ControlFlow, sync::Arc}
;
38 use arrayvec
::ArrayVec
;
39 use base_db
::{CrateDisplayName, CrateId, CrateOrigin, Edition, FileId, ProcMacroKind}
;
43 body
::{BodyDiagnostic, SyntheticSyntax}
,
44 expr
::{BindingAnnotation, ExprOrPatId, LabelId, Pat, PatId}
,
45 generics
::{TypeOrConstParamData, TypeParamProvenance}
,
46 item_tree
::ItemTreeNode
,
47 lang_item
::{LangItem, LangItemTarget}
,
48 layout
::{Layout, LayoutError, ReprOptions}
,
49 nameres
::{self, diagnostics::DefDiagnostic}
,
51 resolver
::{HasResolver, Resolver}
,
53 type_ref
::ConstScalar
,
54 AdtId
, AssocItemId
, AssocItemLoc
, AttrDefId
, ConstId
, ConstParamId
, DefWithBodyId
, EnumId
,
55 EnumVariantId
, FunctionId
, GenericDefId
, HasModule
, ImplId
, ItemContainerId
, LifetimeParamId
,
56 LocalEnumVariantId
, LocalFieldId
, Lookup
, MacroExpander
, MacroId
, ModuleId
, StaticId
, StructId
,
57 TraitId
, TypeAliasId
, TypeOrConstParamId
, TypeParamId
, UnionId
,
59 use hir_expand
::{name::name, MacroCallKind}
;
61 all_super_traits
, autoderef
,
62 consteval
::{unknown_const_as_generic, ComputedExpr, ConstEvalError, ConstExt}
,
63 diagnostics
::BodyValidationDiagnostic
,
65 method_resolution
::{self, TyFingerprint}
,
68 AliasTy
, CallableDefId
, CallableSig
, Canonical
, CanonicalVarKinds
, Cast
, ClosureId
,
69 ConcreteConst
, ConstValue
, GenericArgData
, Interner
, ParamKind
, QuantifiedWhereClause
, Scalar
,
70 Substitution
, TraitEnvironment
, TraitRefExt
, Ty
, TyBuilder
, TyDefId
, TyExt
, TyKind
,
73 use itertools
::Itertools
;
74 use nameres
::diagnostics
::DefDiagnosticKind
;
75 use once_cell
::unsync
::Lazy
;
76 use rustc_hash
::FxHashSet
;
77 use stdx
::{impl_from, never}
;
79 ast
::{self, HasAttrs as _, HasDocComments, HasName}
,
80 AstNode
, AstPtr
, SmolStr
, SyntaxNodePtr
, TextRange
, T
,
83 use crate::db
::{DefDatabase, HirDatabase}
;
86 attrs
::{HasAttrs, Namespace}
,
88 AnyDiagnostic
, BreakOutsideOfLoop
, InactiveCode
, IncorrectCase
, InvalidDeriveTarget
,
89 MacroError
, MalformedDerive
, MismatchedArgCount
, MissingFields
, MissingMatchArms
,
90 MissingUnsafe
, NoSuchField
, PrivateAssocItem
, PrivateField
,
91 ReplaceFilterMapNextWithFindMap
, TypeMismatch
, UnimplementedBuiltinMacro
,
92 UnresolvedExternCrate
, UnresolvedImport
, UnresolvedMacroCall
, UnresolvedModule
,
95 has_source
::HasSource
,
96 semantics
::{PathResolution, Semantics, SemanticsScope, TypeInfo, VisibleTraits}
,
99 // Be careful with these re-exports.
101 // `hir` is the boundary between the compiler and the IDE. It should try hard to
102 // isolate the compiler from the ide, to allow the two to be refactored
103 // independently. Re-exporting something from the compiler is the sure way to
104 // breach the boundary.
106 // Generally, a refactoring which *removes* a name from this list is a good
109 cfg
::{CfgAtom, CfgExpr, CfgOptions}
,
112 attr
::{Attrs, AttrsWithOwner, Documentation}
,
113 builtin_attr
::AttributeTemplate
,
114 find_path
::PrefixKind
,
116 nameres
::ModuleSource
,
117 path
::{ModPath, PathKind}
,
118 type_ref
::{Mutability, TypeRef}
,
119 visibility
::Visibility
,
120 // FIXME: This is here since it is input of a method in `HirWrite`
121 // and things outside of hir need to implement that trait. We probably
122 // should move whole `hir_ty::display` to this crate so we will become
123 // able to use `ModuleDef` or `Definition` instead of `ModuleDefId`.
129 ExpandResult
, HirFileId
, InFile
, MacroFile
, Origin
,
132 display
::{HirDisplay, HirDisplayError, HirWrite}
,
137 // These are negative re-exports: pub using these names is forbidden, they
138 // should remain private to hir internals.
142 hir_expand
::{hygiene::Hygiene, name::AsName}
,
145 /// hir::Crate describes a single crate. It's the main interface with which
146 /// a crate's dependencies interact. Mostly, it should be just a proxy for the
148 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
150 pub(crate) id
: CrateId
,
154 pub struct CrateDependency
{
160 pub fn origin(self, db
: &dyn HirDatabase
) -> CrateOrigin
{
161 db
.crate_graph()[self.id
].origin
.clone()
164 pub fn is_builtin(self, db
: &dyn HirDatabase
) -> bool
{
165 matches
!(self.origin(db
), CrateOrigin
::Lang(_
))
168 pub fn dependencies(self, db
: &dyn HirDatabase
) -> Vec
<CrateDependency
> {
169 db
.crate_graph()[self.id
]
173 let krate
= Crate { id: dep.crate_id }
;
174 let name
= dep
.as_name();
175 CrateDependency { krate, name }
180 pub fn reverse_dependencies(self, db
: &dyn HirDatabase
) -> Vec
<Crate
> {
181 let crate_graph
= db
.crate_graph();
185 crate_graph
[krate
].dependencies
.iter().any(|it
| it
.crate_id
== self.id
)
187 .map(|id
| Crate { id }
)
191 pub fn transitive_reverse_dependencies(
193 db
: &dyn HirDatabase
,
194 ) -> impl Iterator
<Item
= Crate
> {
195 db
.crate_graph().transitive_rev_deps(self.id
).map(|id
| Crate { id }
)
198 pub fn root_module(self, db
: &dyn HirDatabase
) -> Module
{
199 let def_map
= db
.crate_def_map(self.id
);
200 Module { id: def_map.module_id(def_map.root()) }
203 pub fn modules(self, db
: &dyn HirDatabase
) -> Vec
<Module
> {
204 let def_map
= db
.crate_def_map(self.id
);
205 def_map
.modules().map(|(id
, _
)| def_map
.module_id(id
).into()).collect()
208 pub fn root_file(self, db
: &dyn HirDatabase
) -> FileId
{
209 db
.crate_graph()[self.id
].root_file_id
212 pub fn edition(self, db
: &dyn HirDatabase
) -> Edition
{
213 db
.crate_graph()[self.id
].edition
216 pub fn version(self, db
: &dyn HirDatabase
) -> Option
<String
> {
217 db
.crate_graph()[self.id
].version
.clone()
220 pub fn display_name(self, db
: &dyn HirDatabase
) -> Option
<CrateDisplayName
> {
221 db
.crate_graph()[self.id
].display_name
.clone()
224 pub fn query_external_importables(
226 db
: &dyn DefDatabase
,
227 query
: import_map
::Query
,
228 ) -> impl Iterator
<Item
= Either
<ModuleDef
, Macro
>> {
229 let _p
= profile
::span("query_external_importables");
230 import_map
::search_dependencies(db
, self.into(), query
).into_iter().map(|item
| {
231 match ItemInNs
::from(item
) {
232 ItemInNs
::Types(mod_id
) | ItemInNs
::Values(mod_id
) => Either
::Left(mod_id
),
233 ItemInNs
::Macros(mac_id
) => Either
::Right(mac_id
),
238 pub fn all(db
: &dyn HirDatabase
) -> Vec
<Crate
> {
239 db
.crate_graph().iter().map(|id
| Crate { id }
).collect()
242 /// Try to get the root URL of the documentation of a crate.
243 pub fn get_html_root_url(self: &Crate
, db
: &dyn HirDatabase
) -> Option
<String
> {
244 // Look for #![doc(html_root_url = "...")]
245 let attrs
= db
.attrs(AttrDefId
::ModuleId(self.root_module(db
).into()));
246 let doc_url
= attrs
.by_key("doc").find_string_value_in_tt("html_root_url");
247 doc_url
.map(|s
| s
.trim_matches('
"').trim_end_matches('/').to_owned() + "/")
250 pub fn cfg(&self, db: &dyn HirDatabase) -> CfgOptions {
251 db.crate_graph()[self.id].cfg_options.clone()
254 pub fn potential_cfg(&self, db: &dyn HirDatabase) -> CfgOptions {
255 db.crate_graph()[self.id].potential_cfg_options.clone()
259 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
261 pub(crate) id: ModuleId,
264 /// The defs which can be visible in the module.
265 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
270 // Can't be directly declared, but can be imported.
275 TypeAlias(TypeAlias),
276 BuiltinType(BuiltinType),
282 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::Macro(it) => Some(it.module(db)),
315 ModuleDef::BuiltinType(_) => None,
319 pub fn canonical_path(&self, db: &dyn HirDatabase) -> Option<String> {
320 let mut segments = vec![self.name(db)?];
321 for m in self.module(db)?.path_to_root(db) {
322 segments.extend(m.name(db))
325 Some(segments.into_iter().join("::"))
328 pub fn canonical_module_path(
330 db: &dyn HirDatabase,
331 ) -> Option<impl Iterator<Item = Module>> {
332 self.module(db).map(|it| it.path_to_root(db).into_iter().rev())
335 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
336 let name = match self {
337 ModuleDef::Module(it) => it.name(db)?,
338 ModuleDef::Const(it) => it.name(db)?,
339 ModuleDef::Adt(it) => it.name(db),
340 ModuleDef::Trait(it) => it.name(db),
341 ModuleDef::Function(it) => it.name(db),
342 ModuleDef::Variant(it) => it.name(db),
343 ModuleDef::TypeAlias(it) => it.name(db),
344 ModuleDef::Static(it) => it.name(db),
345 ModuleDef::Macro(it) => it.name(db),
346 ModuleDef::BuiltinType(it) => it.name(),
351 pub fn diagnostics(self, db: &dyn HirDatabase) -> Vec<AnyDiagnostic> {
352 let id = match self {
353 ModuleDef::Adt(it) => match it {
354 Adt::Struct(it) => it.id.into(),
355 Adt::Enum(it) => it.id.into(),
356 Adt::Union(it) => it.id.into(),
358 ModuleDef::Trait(it) => it.id.into(),
359 ModuleDef::Function(it) => it.id.into(),
360 ModuleDef::TypeAlias(it) => it.id.into(),
361 ModuleDef::Module(it) => it.id.into(),
362 ModuleDef::Const(it) => it.id.into(),
363 ModuleDef::Static(it) => it.id.into(),
364 ModuleDef::Variant(it) => {
365 EnumVariantId { parent: it.parent.into(), local_id: it.id }.into()
367 ModuleDef::BuiltinType(_) | ModuleDef::Macro(_) => return Vec::new(),
370 let module = match self.module(db) {
372 None => return Vec::new(),
375 let mut acc = Vec::new();
377 match self.as_def_with_body() {
379 def.diagnostics(db, &mut acc);
382 for diag in hir_ty::diagnostics::incorrect_case(db, module.id.krate(), id) {
383 acc.push(diag.into())
391 pub fn as_def_with_body(self) -> Option<DefWithBody> {
393 ModuleDef::Function(it) => Some(it.into()),
394 ModuleDef::Const(it) => Some(it.into()),
395 ModuleDef::Static(it) => Some(it.into()),
396 ModuleDef::Variant(it) => Some(it.into()),
400 | ModuleDef::Trait(_)
401 | ModuleDef::TypeAlias(_)
402 | ModuleDef::Macro(_)
403 | ModuleDef::BuiltinType(_) => None,
407 pub fn attrs(&self, db: &dyn HirDatabase) -> Option<AttrsWithOwner> {
409 ModuleDef::Module(it) => it.attrs(db),
410 ModuleDef::Function(it) => it.attrs(db),
411 ModuleDef::Adt(it) => it.attrs(db),
412 ModuleDef::Variant(it) => it.attrs(db),
413 ModuleDef::Const(it) => it.attrs(db),
414 ModuleDef::Static(it) => it.attrs(db),
415 ModuleDef::Trait(it) => it.attrs(db),
416 ModuleDef::TypeAlias(it) => it.attrs(db),
417 ModuleDef::Macro(it) => it.attrs(db),
418 ModuleDef::BuiltinType(_) => return None,
423 impl HasVisibility for ModuleDef {
424 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
426 ModuleDef::Module(it) => it.visibility(db),
427 ModuleDef::Function(it) => it.visibility(db),
428 ModuleDef::Adt(it) => it.visibility(db),
429 ModuleDef::Const(it) => it.visibility(db),
430 ModuleDef::Static(it) => it.visibility(db),
431 ModuleDef::Trait(it) => it.visibility(db),
432 ModuleDef::TypeAlias(it) => it.visibility(db),
433 ModuleDef::Variant(it) => it.visibility(db),
434 ModuleDef::Macro(it) => it.visibility(db),
435 ModuleDef::BuiltinType(_) => Visibility::Public,
441 /// Name of this module.
442 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
443 let def_map = self.id.def_map(db.upcast());
444 let parent = def_map[self.id.local_id].parent?;
445 def_map[parent].children.iter().find_map(|(name, module_id)| {
446 if *module_id == self.id.local_id {
454 /// Returns the crate this module is part of.
455 pub fn krate(self) -> Crate {
456 Crate { id: self.id.krate() }
459 /// Topmost parent of this module. Every module has a `crate_root`, but some
460 /// might be missing `krate`. This can happen if a module's file is not included
461 /// in the module tree of any target in `Cargo.toml`.
462 pub fn crate_root(self, db: &dyn HirDatabase) -> Module {
463 let def_map = db.crate_def_map(self.id.krate());
464 Module { id: def_map.module_id(def_map.root()) }
467 pub fn is_crate_root(self, db: &dyn HirDatabase) -> bool {
468 let def_map = db.crate_def_map(self.id.krate());
469 def_map.root() == self.id.local_id
472 /// Iterates over all child modules.
473 pub fn children(self, db: &dyn HirDatabase) -> impl Iterator<Item = Module> {
474 let def_map = self.id.def_map(db.upcast());
475 let children = def_map[self.id.local_id]
478 .map(|module_id| Module { id: def_map.module_id(*module_id) })
479 .collect::<Vec<_>>();
483 /// Finds a parent module.
484 pub fn parent(self, db: &dyn HirDatabase) -> Option<Module> {
485 // FIXME: handle block expressions as modules (their parent is in a different DefMap)
486 let def_map = self.id.def_map(db.upcast());
487 let parent_id = def_map[self.id.local_id].parent?;
488 Some(Module { id: def_map.module_id(parent_id) })
491 pub fn path_to_root(self, db: &dyn HirDatabase) -> Vec<Module> {
492 let mut res = vec![self];
494 while let Some(next) = curr.parent(db) {
501 /// Returns a `ModuleScope`: a set of items, visible in this module.
504 db: &dyn HirDatabase,
505 visible_from: Option<Module>,
506 ) -> Vec<(Name, ScopeDef)> {
507 self.id.def_map(db.upcast())[self.id.local_id]
510 .filter_map(|(name, def)| {
511 if let Some(m) = visible_from {
513 def.filter_visibility(|vis| vis.is_visible_from(db.upcast(), m.id));
514 if filtered.is_none() && !def.is_none() {
517 Some((name, filtered))
523 .flat_map(|(name, def)| {
524 ScopeDef::all_items(def).into_iter().map(move |item| (name.clone(), item))
529 /// Fills `acc` with the module's diagnostics.
530 pub fn diagnostics(self, db: &dyn HirDatabase, acc: &mut Vec<AnyDiagnostic>) {
531 let _p = profile::span("Module
::diagnostics
").detail(|| {
532 format!("{:?}
", self.name(db).map_or("<unknown
>".into(), |name| name.to_string()))
534 let def_map = self.id.def_map(db.upcast());
535 for diag in def_map.diagnostics() {
536 if diag.in_module != self.id.local_id {
537 // FIXME: This is accidentally quadratic.
540 emit_def_diagnostic(db, acc, diag);
542 for decl in self.declarations(db) {
544 ModuleDef::Module(m) => {
545 // Only add diagnostics from inline modules
546 if def_map[m.id.local_id].origin.is_inline() {
547 m.diagnostics(db, acc)
550 ModuleDef::Trait(t) => {
551 for diag in db.trait_data_with_diagnostics(t.id).1.iter() {
552 emit_def_diagnostic(db, acc, diag);
554 acc.extend(decl.diagnostics(db))
556 ModuleDef::Adt(adt) => {
559 for diag in db.struct_data_with_diagnostics(s.id).1.iter() {
560 emit_def_diagnostic(db, acc, diag);
564 for diag in db.union_data_with_diagnostics(u.id).1.iter() {
565 emit_def_diagnostic(db, acc, diag);
569 for v in e.variants(db) {
570 acc.extend(ModuleDef::Variant(v).diagnostics(db));
573 for diag in db.enum_data_with_diagnostics(e.id).1.iter() {
574 emit_def_diagnostic(db, acc, diag);
578 acc.extend(decl.diagnostics(db))
580 _ => acc.extend(decl.diagnostics(db)),
584 for impl_def in self.impl_defs(db) {
585 for diag in db.impl_data_with_diagnostics(impl_def.id).1.iter() {
586 emit_def_diagnostic(db, acc, diag);
589 for item in impl_def.items(db) {
590 let def: DefWithBody = match item {
591 AssocItem::Function(it) => it.into(),
592 AssocItem::Const(it) => it.into(),
593 AssocItem::TypeAlias(_) => continue,
596 def.diagnostics(db, acc);
601 pub fn declarations(self, db: &dyn HirDatabase) -> Vec<ModuleDef> {
602 let def_map = self.id.def_map(db.upcast());
603 let scope = &def_map[self.id.local_id].scope;
606 .map(ModuleDef::from)
607 .chain(scope.unnamed_consts().map(|id| ModuleDef::Const(Const::from(id))))
611 pub fn legacy_macros(self, db: &dyn HirDatabase) -> Vec<Macro> {
612 let def_map = self.id.def_map(db.upcast());
613 let scope = &def_map[self.id.local_id].scope;
614 scope.legacy_macros().flat_map(|(_, it)| it).map(|&it| it.into()).collect()
617 pub fn impl_defs(self, db: &dyn HirDatabase) -> Vec<Impl> {
618 let def_map = self.id.def_map(db.upcast());
619 def_map[self.id.local_id].scope.impls().map(Impl::from).collect()
622 /// Finds a path that can be used to refer to the given item from within
623 /// this module, if possible.
624 pub fn find_use_path(
626 db: &dyn DefDatabase,
627 item: impl Into<ItemInNs>,
629 ) -> Option<ModPath> {
630 hir_def::find_path::find_path(db, item.into().into(), self.into(), prefer_no_std)
633 /// Finds a path that can be used to refer to the given item from within
634 /// this module, if possible. This is used for returning import paths for use-statements.
635 pub fn find_use_path_prefixed(
637 db: &dyn DefDatabase,
638 item: impl Into<ItemInNs>,
639 prefix_kind: PrefixKind,
641 ) -> Option<ModPath> {
642 hir_def::find_path::find_path_prefixed(
652 fn emit_def_diagnostic(db: &dyn HirDatabase, acc: &mut Vec<AnyDiagnostic>, diag: &DefDiagnostic) {
654 DefDiagnosticKind::UnresolvedModule { ast: declaration, candidates } => {
655 let decl = declaration.to_node(db.upcast());
658 decl: InFile::new(declaration.file_id, AstPtr::new(&decl)),
659 candidates: candidates.clone(),
664 DefDiagnosticKind::UnresolvedExternCrate { ast } => {
665 let item = ast.to_node(db.upcast());
667 UnresolvedExternCrate { decl: InFile::new(ast.file_id, AstPtr::new(&item)) }.into(),
671 DefDiagnosticKind::UnresolvedImport { id, index } => {
672 let file_id = id.file_id();
673 let item_tree = id.item_tree(db.upcast());
674 let import = &item_tree[id.value];
676 let use_tree = import.use_tree_to_ast(db.upcast(), file_id, *index);
678 UnresolvedImport { decl: InFile::new(file_id, AstPtr::new(&use_tree)) }.into(),
682 DefDiagnosticKind::UnconfiguredCode { ast, cfg, opts } => {
683 let item = ast.to_node(db.upcast());
686 node: ast.with_value(AstPtr::new(&item).into()),
694 DefDiagnosticKind::UnresolvedProcMacro { ast, krate } => {
695 let (node, precise_location, macro_name, kind) = precise_macro_call_location(ast, db);
697 UnresolvedProcMacro { node, precise_location, macro_name, kind, krate: *krate }
702 DefDiagnosticKind::UnresolvedMacroCall { ast, path } => {
703 let (node, precise_location, _, _) = precise_macro_call_location(ast, db);
705 UnresolvedMacroCall {
709 is_bang: matches!(ast, MacroCallKind::FnLike { .. }),
715 DefDiagnosticKind::MacroError { ast, message } => {
716 let (node, precise_location, _, _) = precise_macro_call_location(ast, db);
717 acc.push(MacroError { node, precise_location, message: message.clone() }.into());
720 DefDiagnosticKind::UnimplementedBuiltinMacro { ast } => {
721 let node = ast.to_node(db.upcast());
722 // Must have a name, otherwise we wouldn't emit it.
723 let name = node.name().expect("unimplemented builtin
macro with no name
");
725 UnimplementedBuiltinMacro {
726 node: ast.with_value(SyntaxNodePtr::from(AstPtr::new(&name))),
731 DefDiagnosticKind::InvalidDeriveTarget { ast, id } => {
732 let node = ast.to_node(db.upcast());
733 let derive = node.attrs().nth(*id as usize);
737 InvalidDeriveTarget {
738 node: ast.with_value(SyntaxNodePtr::from(AstPtr::new(&derive))),
743 None => stdx::never!("derive diagnostic on item without derive attribute
"),
746 DefDiagnosticKind::MalformedDerive { ast, id } => {
747 let node = ast.to_node(db.upcast());
748 let derive = node.attrs().nth(*id as usize);
753 node: ast.with_value(SyntaxNodePtr::from(AstPtr::new(&derive))),
758 None => stdx::never!("derive diagnostic on item without derive attribute
"),
764 fn precise_macro_call_location(
766 db: &dyn HirDatabase,
767 ) -> (InFile<SyntaxNodePtr>, Option<TextRange>, Option<String>, MacroKind) {
768 // FIXME: maaybe we actually want slightly different ranges for the different macro diagnostics
769 // - e.g. the full attribute for macro errors, but only the name for name resolution
771 MacroCallKind::FnLike { ast_id, .. } => {
772 let node = ast_id.to_node(db.upcast());
774 ast_id.with_value(SyntaxNodePtr::from(AstPtr::new(&node))),
776 .and_then(|it| it.segment())
777 .and_then(|it| it.name_ref())
778 .map(|it| it.syntax().text_range()),
779 node.path().and_then(|it| it.segment()).map(|it| it.to_string()),
780 MacroKind::ProcMacro,
783 MacroCallKind::Derive { ast_id, derive_attr_index, derive_index } => {
784 let node = ast_id.to_node(db.upcast());
785 // Compute the precise location of the macro name's token in the derive
788 let derive_attr = node
789 .doc_comments_and_attrs()
790 .nth(derive_attr_index.ast_index())
791 .and_then(Either::left)?;
792 let token_tree = derive_attr.meta()?.token_tree()?;
793 let group_by = token_tree
795 .children_with_tokens()
796 .filter_map(|elem| match elem {
797 syntax::NodeOrToken::Token(tok) => Some(tok),
800 .group_by(|t| t.kind() == T![,]);
801 let (_, mut group) = group_by
803 .filter(|&(comma, _)| !comma)
804 .nth(*derive_index as usize)?;
805 group.find(|t| t.kind() == T![ident])
808 ast_id.with_value(SyntaxNodePtr::from(AstPtr::new(&node))),
809 token.as_ref().map(|tok| tok.text_range()),
810 token.as_ref().map(ToString::to_string),
814 MacroCallKind::Attr { ast_id, invoc_attr_index, .. } => {
815 let node = ast_id.to_node(db.upcast());
817 .doc_comments_and_attrs()
818 .nth(invoc_attr_index.ast_index())
819 .and_then(Either::left)
821 panic!("cannot find attribute
#{}", invoc_attr_index.ast_index())
825 ast_id.with_value(SyntaxNodePtr::from(AstPtr::new(&attr))),
826 Some(attr.syntax().text_range()),
828 .and_then(|path| path.segment())
829 .and_then(|seg| seg.name_ref())
831 .map(ToString::to_string),
838 impl HasVisibility for Module {
839 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
840 let def_map = self.id.def_map(db.upcast());
841 let module_data = &def_map[self.id.local_id];
842 module_data.visibility
846 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
848 pub(crate) parent: VariantDef,
849 pub(crate) id: LocalFieldId,
852 #[derive(Debug, PartialEq, Eq)]
853 pub enum FieldSource {
854 Named(ast::RecordField),
855 Pos(ast::TupleField),
859 pub fn name(&self, db: &dyn HirDatabase) -> Name {
860 self.parent.variant_data(db).fields()[self.id].name.clone()
863 pub fn index(&self) -> usize {
864 u32::from(self.id.into_raw()) as usize
867 /// Returns the type as in the signature of the struct (i.e., with
868 /// placeholder types for type parameters). Only use this in the context of
869 /// the field definition.
870 pub fn ty(&self, db: &dyn HirDatabase) -> Type {
871 let var_id = self.parent.into();
872 let generic_def_id: GenericDefId = match self.parent {
873 VariantDef::Struct(it) => it.id.into(),
874 VariantDef::Union(it) => it.id.into(),
875 VariantDef::Variant(it) => it.parent.id.into(),
877 let substs = TyBuilder::placeholder_subst(db, generic_def_id);
878 let ty = db.field_types(var_id)[self.id].clone().substitute(Interner, &substs);
879 Type::new(db, var_id, ty)
882 pub fn layout(&self, db: &dyn HirDatabase) -> Result<Layout, LayoutError> {
883 layout_of_ty(db, &self.ty(db).ty, self.parent.module(db).krate().into())
886 pub fn parent_def(&self, _db: &dyn HirDatabase) -> VariantDef {
891 impl HasVisibility for Field {
892 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
893 let variant_data = self.parent.variant_data(db);
894 let visibility = &variant_data.fields()[self.id].visibility;
895 let parent_id: hir_def::VariantId = self.parent.into();
896 visibility.resolve(db.upcast(), &parent_id.resolver(db.upcast()))
900 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
902 pub(crate) id: StructId,
906 pub fn module(self, db: &dyn HirDatabase) -> Module {
907 Module { id: self.id.lookup(db.upcast()).container }
910 pub fn name(self, db: &dyn HirDatabase) -> Name {
911 db.struct_data(self.id).name.clone()
914 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
915 db.struct_data(self.id)
919 .map(|(id, _)| Field { parent: self.into(), id })
923 pub fn ty(self, db: &dyn HirDatabase) -> Type {
924 Type::from_def(db, self.id)
927 pub fn repr(self, db: &dyn HirDatabase) -> Option<ReprOptions> {
928 db.struct_data(self.id).repr
931 pub fn kind(self, db: &dyn HirDatabase) -> StructKind {
932 self.variant_data(db).kind()
935 fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
936 db.struct_data(self.id).variant_data.clone()
940 impl HasVisibility for Struct {
941 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
942 db.struct_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
946 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
948 pub(crate) id: UnionId,
952 pub fn name(self, db: &dyn HirDatabase) -> Name {
953 db.union_data(self.id).name.clone()
956 pub fn module(self, db: &dyn HirDatabase) -> Module {
957 Module { id: self.id.lookup(db.upcast()).container }
960 pub fn ty(self, db: &dyn HirDatabase) -> Type {
961 Type::from_def(db, self.id)
964 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
965 db.union_data(self.id)
969 .map(|(id, _)| Field { parent: self.into(), id })
973 fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
974 db.union_data(self.id).variant_data.clone()
978 impl HasVisibility for Union {
979 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
980 db.union_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
984 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
986 pub(crate) id: EnumId,
990 pub fn module(self, db: &dyn HirDatabase) -> Module {
991 Module { id: self.id.lookup(db.upcast()).container }
994 pub fn name(self, db: &dyn HirDatabase) -> Name {
995 db.enum_data(self.id).name.clone()
998 pub fn variants(self, db: &dyn HirDatabase) -> Vec<Variant> {
999 db.enum_data(self.id).variants.iter().map(|(id, _)| Variant { parent: self, id }).collect()
1002 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1003 Type::from_def(db, self.id)
1006 /// The type of the enum variant bodies.
1007 pub fn variant_body_ty(self, db: &dyn HirDatabase) -> Type {
1008 Type::new_for_crate(
1009 self.id.lookup(db.upcast()).container.krate(),
1010 TyBuilder::builtin(match db.enum_data(self.id).variant_body_type() {
1011 hir_def::layout::IntegerType::Pointer(sign) => match sign {
1012 true => hir_def::builtin_type::BuiltinType::Int(
1013 hir_def::builtin_type::BuiltinInt::Isize,
1015 false => hir_def::builtin_type::BuiltinType::Uint(
1016 hir_def::builtin_type::BuiltinUint::Usize,
1019 hir_def::layout::IntegerType::Fixed(i, sign) => match sign {
1020 true => hir_def::builtin_type::BuiltinType::Int(match i {
1021 hir_def::layout::Integer::I8 => hir_def::builtin_type::BuiltinInt::I8,
1022 hir_def::layout::Integer::I16 => hir_def::builtin_type::BuiltinInt::I16,
1023 hir_def::layout::Integer::I32 => hir_def::builtin_type::BuiltinInt::I32,
1024 hir_def::layout::Integer::I64 => hir_def::builtin_type::BuiltinInt::I64,
1025 hir_def::layout::Integer::I128 => hir_def::builtin_type::BuiltinInt::I128,
1027 false => hir_def::builtin_type::BuiltinType::Uint(match i {
1028 hir_def::layout::Integer::I8 => hir_def::builtin_type::BuiltinUint::U8,
1029 hir_def::layout::Integer::I16 => hir_def::builtin_type::BuiltinUint::U16,
1030 hir_def::layout::Integer::I32 => hir_def::builtin_type::BuiltinUint::U32,
1031 hir_def::layout::Integer::I64 => hir_def::builtin_type::BuiltinUint::U64,
1032 hir_def::layout::Integer::I128 => hir_def::builtin_type::BuiltinUint::U128,
1039 pub fn is_data_carrying(self, db: &dyn HirDatabase) -> bool {
1040 self.variants(db).iter().any(|v| !matches!(v.kind(db), StructKind::Unit))
1044 impl HasVisibility for Enum {
1045 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1046 db.enum_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1050 impl From<&Variant> for DefWithBodyId {
1051 fn from(&v: &Variant) -> Self {
1052 DefWithBodyId::VariantId(v.into())
1056 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1057 pub struct Variant {
1058 pub(crate) parent: Enum,
1059 pub(crate) id: LocalEnumVariantId,
1063 pub fn module(self, db: &dyn HirDatabase) -> Module {
1064 self.parent.module(db)
1067 pub fn parent_enum(self, _db: &dyn HirDatabase) -> Enum {
1071 pub fn name(self, db: &dyn HirDatabase) -> Name {
1072 db.enum_data(self.parent.id).variants[self.id].name.clone()
1075 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
1076 self.variant_data(db)
1079 .map(|(id, _)| Field { parent: self.into(), id })
1083 pub fn kind(self, db: &dyn HirDatabase) -> StructKind {
1084 self.variant_data(db).kind()
1087 pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
1088 db.enum_data(self.parent.id).variants[self.id].variant_data.clone()
1091 pub fn value(self, db: &dyn HirDatabase) -> Option<ast::Expr> {
1092 self.source(db)?.value.expr()
1095 pub fn eval(self, db: &dyn HirDatabase) -> Result<ComputedExpr, ConstEvalError> {
1096 db.const_eval_variant(self.into())
1100 /// Variants inherit visibility from the parent enum.
1101 impl HasVisibility for Variant {
1102 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1103 self.parent_enum(db).visibility(db)
1108 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1114 impl_from!(Struct, Union, Enum for Adt);
1117 pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
1118 let subst = db.generic_defaults(self.into());
1119 subst.iter().any(|ty| match ty.skip_binders().data(Interner) {
1120 GenericArgData::Ty(x) => x.is_unknown(),
1125 pub fn layout(self, db: &dyn HirDatabase) -> Result<Layout, LayoutError> {
1126 if db.generic_params(self.into()).iter().count() != 0 {
1127 return Err(LayoutError::HasPlaceholder);
1129 db.layout_of_adt(self.into(), Substitution::empty(Interner))
1132 /// Turns this ADT into a type. Any type parameters of the ADT will be
1133 /// turned into unknown types, which is good for e.g. finding the most
1134 /// general set of completions, but will not look very nice when printed.
1135 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1136 let id = AdtId::from(self);
1137 Type::from_def(db, id)
1140 /// Turns this ADT into a type with the given type parameters. This isn't
1141 /// the greatest API, FIXME find a better one.
1142 pub fn ty_with_args(self, db: &dyn HirDatabase, args: &[Type]) -> Type {
1143 let id = AdtId::from(self);
1144 let mut it = args.iter().map(|t| t.ty.clone());
1145 let ty = TyBuilder::def_ty(db, id.into(), None)
1147 let r = it.next().unwrap_or_else(|| TyKind::Error.intern(Interner));
1149 ParamKind::Type => GenericArgData::Ty(r).intern(Interner),
1150 ParamKind::Const(ty) => unknown_const_as_generic(ty.clone()),
1154 Type::new(db, id, ty)
1157 pub fn module(self, db: &dyn HirDatabase) -> Module {
1159 Adt::Struct(s) => s.module(db),
1160 Adt::Union(s) => s.module(db),
1161 Adt::Enum(e) => e.module(db),
1165 pub fn name(self, db: &dyn HirDatabase) -> Name {
1167 Adt::Struct(s) => s.name(db),
1168 Adt::Union(u) => u.name(db),
1169 Adt::Enum(e) => e.name(db),
1173 pub fn as_enum(&self) -> Option<Enum> {
1174 if let Self::Enum(v) = self {
1182 impl HasVisibility for Adt {
1183 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1185 Adt::Struct(it) => it.visibility(db),
1186 Adt::Union(it) => it.visibility(db),
1187 Adt::Enum(it) => it.visibility(db),
1192 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1193 pub enum VariantDef {
1198 impl_from!(Struct, Union, Variant for VariantDef);
1201 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
1203 VariantDef::Struct(it) => it.fields(db),
1204 VariantDef::Union(it) => it.fields(db),
1205 VariantDef::Variant(it) => it.fields(db),
1209 pub fn module(self, db: &dyn HirDatabase) -> Module {
1211 VariantDef::Struct(it) => it.module(db),
1212 VariantDef::Union(it) => it.module(db),
1213 VariantDef::Variant(it) => it.module(db),
1217 pub fn name(&self, db: &dyn HirDatabase) -> Name {
1219 VariantDef::Struct(s) => s.name(db),
1220 VariantDef::Union(u) => u.name(db),
1221 VariantDef::Variant(e) => e.name(db),
1225 pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
1227 VariantDef::Struct(it) => it.variant_data(db),
1228 VariantDef::Union(it) => it.variant_data(db),
1229 VariantDef::Variant(it) => it.variant_data(db),
1234 /// The defs which have a body.
1235 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1236 pub enum DefWithBody {
1242 impl_from!(Function, Const, Static, Variant for DefWithBody);
1245 pub fn module(self, db: &dyn HirDatabase) -> Module {
1247 DefWithBody::Const(c) => c.module(db),
1248 DefWithBody::Function(f) => f.module(db),
1249 DefWithBody::Static(s) => s.module(db),
1250 DefWithBody::Variant(v) => v.module(db),
1254 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1256 DefWithBody::Function(f) => Some(f.name(db)),
1257 DefWithBody::Static(s) => Some(s.name(db)),
1258 DefWithBody::Const(c) => c.name(db),
1259 DefWithBody::Variant(v) => Some(v.name(db)),
1263 /// Returns the type this def's body has to evaluate to.
1264 pub fn body_type(self, db: &dyn HirDatabase) -> Type {
1266 DefWithBody::Function(it) => it.ret_type(db),
1267 DefWithBody::Static(it) => it.ty(db),
1268 DefWithBody::Const(it) => it.ty(db),
1269 DefWithBody::Variant(it) => it.parent.variant_body_ty(db),
1273 fn id(&self) -> DefWithBodyId {
1275 DefWithBody::Function(it) => it.id.into(),
1276 DefWithBody::Static(it) => it.id.into(),
1277 DefWithBody::Const(it) => it.id.into(),
1278 DefWithBody::Variant(it) => it.into(),
1282 /// A textual representation of the HIR of this def's body for debugging purposes.
1283 pub fn debug_hir(self, db: &dyn HirDatabase) -> String {
1284 let body = db.body(self.id());
1285 body.pretty_print(db.upcast(), self.id())
1288 pub fn diagnostics(self, db: &dyn HirDatabase, acc: &mut Vec<AnyDiagnostic>) {
1289 let krate = self.module(db).id.krate();
1291 let (body, source_map) = db.body_with_source_map(self.into());
1293 for (_, def_map) in body.blocks(db.upcast()) {
1294 for diag in def_map.diagnostics() {
1295 emit_def_diagnostic(db, acc, diag);
1299 for diag in source_map.diagnostics() {
1301 BodyDiagnostic::InactiveCode { node, cfg, opts } => acc.push(
1302 InactiveCode { node: node.clone(), cfg: cfg.clone(), opts: opts.clone() }
1305 BodyDiagnostic::MacroError { node, message } => acc.push(
1307 node: node.clone().map(|it| it.into()),
1308 precise_location: None,
1309 message: message.to_string(),
1313 BodyDiagnostic::UnresolvedProcMacro { node, krate } => acc.push(
1314 UnresolvedProcMacro {
1315 node: node.clone().map(|it| it.into()),
1316 precise_location: None,
1318 kind: MacroKind::ProcMacro,
1323 BodyDiagnostic::UnresolvedMacroCall { node, path } => acc.push(
1324 UnresolvedMacroCall {
1325 macro_call: node.clone().map(|ast_ptr| ast_ptr.into()),
1326 precise_location: None,
1335 let infer = db.infer(self.into());
1336 let source_map = Lazy::new(|| db.body_with_source_map(self.into()).1);
1337 for d in &infer.diagnostics {
1339 hir_ty::InferenceDiagnostic::NoSuchField { expr } => {
1340 let field = source_map.field_syntax(*expr);
1341 acc.push(NoSuchField { field }.into())
1343 &hir_ty::InferenceDiagnostic::BreakOutsideOfLoop { expr, is_break } => {
1344 let expr = source_map
1346 .expect("break outside of loop in synthetic syntax");
1347 acc.push(BreakOutsideOfLoop { expr, is_break }.into())
1349 hir_ty::InferenceDiagnostic::MismatchedArgCount { call_expr, expected, found } => {
1350 match source_map.expr_syntax(*call_expr) {
1351 Ok(source_ptr) => acc.push(
1352 MismatchedArgCount {
1353 call_expr: source_ptr,
1354 expected: *expected,
1359 Err(SyntheticSyntax) => (),
1362 &hir_ty::InferenceDiagnostic::PrivateField { expr, field } => {
1363 let expr = source_map.expr_syntax(expr).expect("unexpected synthetic");
1364 let field = field.into();
1365 acc.push(PrivateField { expr, field }.into())
1367 &hir_ty::InferenceDiagnostic::PrivateAssocItem { id, item } => {
1368 let expr_or_pat = match id {
1369 ExprOrPatId::ExprId(expr) => source_map
1371 .expect("unexpected synthetic")
1373 ExprOrPatId::PatId(pat) => source_map
1375 .expect("unexpected synthetic")
1376 .map(Either::Right),
1378 let item = item.into();
1379 acc.push(PrivateAssocItem { expr_or_pat, item }.into())
1383 for (expr, mismatch) in infer.expr_type_mismatches() {
1384 let expr = match source_map.expr_syntax(expr) {
1386 Err(SyntheticSyntax) => continue,
1391 expected: Type::new(db, DefWithBodyId::from(self), mismatch.expected.clone()),
1392 actual: Type::new(db, DefWithBodyId::from(self), mismatch.actual.clone()),
1398 for expr in hir_ty::diagnostics::missing_unsafe(db, self.into()) {
1399 match source_map.expr_syntax(expr) {
1400 Ok(expr) => acc.push(MissingUnsafe { expr }.into()),
1401 Err(SyntheticSyntax) => {
1402 // FIXME: Here and eslwhere in this file, the `expr` was
1403 // desugared, report or assert that this doesn't happen.
1408 for diagnostic in BodyValidationDiagnostic::collect(db, self.into()) {
1410 BodyValidationDiagnostic::RecordMissingFields {
1415 let variant_data = variant.variant_data(db.upcast());
1416 let missed_fields = missed_fields
1418 .map(|idx| variant_data.fields()[idx].name.clone())
1422 Either::Left(record_expr) => match source_map.expr_syntax(record_expr) {
1424 let root = source_ptr.file_syntax(db.upcast());
1425 if let ast::Expr::RecordExpr(record_expr) =
1426 &source_ptr.value.to_node(&root)
1428 if record_expr.record_expr_field_list().is_some() {
1431 file: source_ptr.file_id,
1432 field_list_parent: Either::Left(AstPtr::new(
1435 field_list_parent_path: record_expr
1437 .map(|path| AstPtr::new(&path)),
1445 Err(SyntheticSyntax) => (),
1447 Either::Right(record_pat) => match source_map.pat_syntax(record_pat) {
1449 if let Some(expr) = source_ptr.value.as_ref().left() {
1450 let root = source_ptr.file_syntax(db.upcast());
1451 if let ast::Pat::RecordPat(record_pat) = expr.to_node(&root) {
1452 if record_pat.record_pat_field_list().is_some() {
1455 file: source_ptr.file_id,
1456 field_list_parent: Either::Right(AstPtr::new(
1459 field_list_parent_path: record_pat
1461 .map(|path| AstPtr::new(&path)),
1470 Err(SyntheticSyntax) => (),
1474 BodyValidationDiagnostic::ReplaceFilterMapNextWithFindMap { method_call_expr } => {
1475 if let Ok(next_source_ptr) = source_map.expr_syntax(method_call_expr) {
1477 ReplaceFilterMapNextWithFindMap {
1478 file: next_source_ptr.file_id,
1479 next_expr: next_source_ptr.value,
1485 BodyValidationDiagnostic::MissingMatchArms { match_expr, uncovered_patterns } => {
1486 match source_map.expr_syntax(match_expr) {
1488 let root = source_ptr.file_syntax(db.upcast());
1489 if let ast::Expr::MatchExpr(match_expr) =
1490 &source_ptr.value.to_node(&root)
1492 if let Some(match_expr) = match_expr.expr() {
1495 file: source_ptr.file_id,
1496 match_expr: AstPtr::new(&match_expr),
1504 Err(SyntheticSyntax) => (),
1510 let def: ModuleDef = match self {
1511 DefWithBody::Function(it) => it.into(),
1512 DefWithBody::Static(it) => it.into(),
1513 DefWithBody::Const(it) => it.into(),
1514 DefWithBody::Variant(it) => it.into(),
1516 for diag in hir_ty::diagnostics::incorrect_case(db, krate, def.into()) {
1517 acc.push(diag.into())
1522 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1523 pub struct Function {
1524 pub(crate) id: FunctionId,
1528 pub fn module(self, db: &dyn HirDatabase) -> Module {
1529 self.id.lookup(db.upcast()).module(db.upcast()).into()
1532 pub fn name(self, db: &dyn HirDatabase) -> Name {
1533 db.function_data(self.id).name.clone()
1536 /// Get this function's return type
1537 pub fn ret_type(self, db: &dyn HirDatabase) -> Type {
1538 let resolver = self.id.resolver(db.upcast());
1539 let substs = TyBuilder::placeholder_subst(db, self.id);
1540 let callable_sig = db.callable_item_signature(self.id.into()).substitute(Interner, &substs);
1541 let ty = callable_sig.ret().clone();
1542 Type::new_with_resolver_inner(db, &resolver, ty)
1545 pub fn async_ret_type(self, db: &dyn HirDatabase) -> Option<Type> {
1546 if !self.is_async(db) {
1549 let resolver = self.id.resolver(db.upcast());
1550 let substs = TyBuilder::placeholder_subst(db, self.id);
1551 let callable_sig = db.callable_item_signature(self.id.into()).substitute(Interner, &substs);
1552 let ret_ty = callable_sig.ret().clone();
1553 for pred in ret_ty.impl_trait_bounds(db).into_iter().flatten() {
1554 if let WhereClause::AliasEq(output_eq) = pred.into_value_and_skipped_binders().0 {
1555 return Type::new_with_resolver_inner(db, &resolver, output_eq.ty).into();
1558 never!("Async fn ret_type should be impl Future");
1562 pub fn has_self_param(self, db: &dyn HirDatabase) -> bool {
1563 db.function_data(self.id).has_self_param()
1566 pub fn self_param(self, db: &dyn HirDatabase) -> Option<SelfParam> {
1567 self.has_self_param(db).then_some(SelfParam { func: self.id })
1570 pub fn assoc_fn_params(self, db: &dyn HirDatabase) -> Vec<Param> {
1571 let environment = db.trait_environment(self.id.into());
1572 let substs = TyBuilder::placeholder_subst(db, self.id);
1573 let callable_sig = db.callable_item_signature(self.id.into()).substitute(Interner, &substs);
1579 let ty = Type { env: environment.clone(), ty: ty.clone() };
1580 Param { func: self, ty, idx }
1585 pub fn method_params(self, db: &dyn HirDatabase) -> Option<Vec<Param>> {
1586 if self.self_param(db).is_none() {
1589 Some(self.params_without_self(db))
1592 pub fn params_without_self(self, db: &dyn HirDatabase) -> Vec<Param> {
1593 let environment = db.trait_environment(self.id.into());
1594 let substs = TyBuilder::placeholder_subst(db, self.id);
1595 let callable_sig = db.callable_item_signature(self.id.into()).substitute(Interner, &substs);
1596 let skip = if db.function_data(self.id).has_self_param() { 1 } else { 0 };
1603 let ty = Type { env: environment.clone(), ty: ty.clone() };
1604 Param { func: self, ty, idx }
1609 pub fn is_const(self, db: &dyn HirDatabase) -> bool {
1610 db.function_data(self.id).has_const_kw()
1613 pub fn is_async(self, db: &dyn HirDatabase) -> bool {
1614 db.function_data(self.id).has_async_kw()
1617 pub fn is_unsafe_to_call(self, db: &dyn HirDatabase) -> bool {
1618 hir_ty::is_fn_unsafe_to_call(db, self.id)
1621 /// Whether this function declaration has a definition.
1623 /// This is false in the case of required (not provided) trait methods.
1624 pub fn has_body(self, db: &dyn HirDatabase) -> bool {
1625 db.function_data(self.id).has_body()
1628 pub fn as_proc_macro(self, db: &dyn HirDatabase) -> Option<Macro> {
1629 let function_data = db.function_data(self.id);
1630 let attrs = &function_data.attrs;
1631 // FIXME: Store this in FunctionData flags?
1632 if !(attrs.is_proc_macro()
1633 || attrs.is_proc_macro_attribute()
1634 || attrs.is_proc_macro_derive())
1638 let loc = self.id.lookup(db.upcast());
1639 let def_map = db.crate_def_map(loc.krate(db).into());
1640 def_map.fn_as_proc_macro(self.id).map(|id| Macro { id: id.into() })
1644 // Note: logically, this belongs to `hir_ty`, but we are not using it there yet.
1645 #[derive(Clone, Copy, PartialEq, Eq)]
1652 impl From<hir_ty::Mutability> for Access {
1653 fn from(mutability: hir_ty::Mutability) -> Access {
1655 hir_ty::Mutability::Not => Access::Shared,
1656 hir_ty::Mutability::Mut => Access::Exclusive,
1661 #[derive(Clone, Debug)]
1664 /// The index in parameter list, including self parameter.
1670 pub fn ty(&self) -> &Type {
1674 pub fn name(&self, db: &dyn HirDatabase) -> Option<Name> {
1675 db.function_data(self.func.id).params[self.idx].0.clone()
1678 pub fn as_local(&self, db: &dyn HirDatabase) -> Option<Local> {
1679 let parent = DefWithBodyId::FunctionId(self.func.into());
1680 let body = db.body(parent);
1681 let pat_id = body.params[self.idx];
1682 if let Pat::Bind { .. } = &body[pat_id] {
1683 Some(Local { parent, pat_id: body.params[self.idx] })
1689 pub fn pattern_source(&self, db: &dyn HirDatabase) -> Option<ast::Pat> {
1690 self.source(db).and_then(|p| p.value.pat())
1693 pub fn source(&self, db: &dyn HirDatabase) -> Option<InFile<ast::Param>> {
1694 let InFile { file_id, value } = self.func.source(db)?;
1695 let params = value.param_list()?;
1696 if params.self_param().is_some() {
1697 params.params().nth(self.idx.checked_sub(1)?)
1699 params.params().nth(self.idx)
1701 .map(|value| InFile { file_id, value })
1705 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1706 pub struct SelfParam {
1711 pub fn access(self, db: &dyn HirDatabase) -> Access {
1712 let func_data = db.function_data(self.func);
1716 .map(|(_, param)| match &**param {
1717 TypeRef::Reference(.., mutability) => match mutability {
1718 hir_def::type_ref::Mutability::Shared => Access::Shared,
1719 hir_def::type_ref::Mutability::Mut => Access::Exclusive,
1723 .unwrap_or(Access::Owned)
1726 pub fn display(self, db: &dyn HirDatabase) -> &'static str {
1727 match self.access(db) {
1728 Access::Shared => "&self",
1729 Access::Exclusive => "&mut self",
1730 Access::Owned => "self",
1734 pub fn source(&self, db: &dyn HirDatabase) -> Option<InFile<ast::SelfParam>> {
1735 let InFile { file_id, value } = Function::from(self.func).source(db)?;
1738 .and_then(|params| params.self_param())
1739 .map(|value| InFile { file_id, value })
1742 pub fn ty(&self, db: &dyn HirDatabase) -> Type {
1743 let substs = TyBuilder::placeholder_subst(db, self.func);
1745 db.callable_item_signature(self.func.into()).substitute(Interner, &substs);
1746 let environment = db.trait_environment(self.func.into());
1747 let ty = callable_sig.params()[0].clone();
1748 Type { env: environment, ty }
1752 impl HasVisibility for Function {
1753 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1754 db.function_visibility(self.id)
1758 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1760 pub(crate) id: ConstId,
1764 pub fn module(self, db: &dyn HirDatabase) -> Module {
1765 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
1768 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1769 db.const_data(self.id).name.clone()
1772 pub fn value(self, db: &dyn HirDatabase) -> Option<ast::Expr> {
1773 self.source(db)?.value.body()
1776 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1777 let data = db.const_data(self.id);
1778 let resolver = self.id.resolver(db.upcast());
1779 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
1780 let ty = ctx.lower_ty(&data.type_ref);
1781 Type::new_with_resolver_inner(db, &resolver, ty)
1784 pub fn eval(self, db: &dyn HirDatabase) -> Result<ComputedExpr, ConstEvalError> {
1785 db.const_eval(self.id)
1789 impl HasVisibility for Const {
1790 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1791 db.const_visibility(self.id)
1795 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1797 pub(crate) id: StaticId,
1801 pub fn module(self, db: &dyn HirDatabase) -> Module {
1802 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
1805 pub fn name(self, db: &dyn HirDatabase) -> Name {
1806 db.static_data(self.id).name.clone()
1809 pub fn is_mut(self, db: &dyn HirDatabase) -> bool {
1810 db.static_data(self.id).mutable
1813 pub fn value(self, db: &dyn HirDatabase) -> Option<ast::Expr> {
1814 self.source(db)?.value.body()
1817 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1818 let data = db.static_data(self.id);
1819 let resolver = self.id.resolver(db.upcast());
1820 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
1821 let ty = ctx.lower_ty(&data.type_ref);
1822 Type::new_with_resolver_inner(db, &resolver, ty)
1826 impl HasVisibility for Static {
1827 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1828 db.static_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1832 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1834 pub(crate) id: TraitId,
1838 pub fn lang(db: &dyn HirDatabase, krate: Crate, name: &Name) -> Option<Trait> {
1839 db.lang_item(krate.into(), LangItem::from_name(name)?)
1840 .and_then(LangItemTarget::as_trait)
1844 pub fn module(self, db: &dyn HirDatabase) -> Module {
1845 Module { id: self.id.lookup(db.upcast()).container }
1848 pub fn name(self, db: &dyn HirDatabase) -> Name {
1849 db.trait_data(self.id).name.clone()
1852 pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
1853 db.trait_data(self.id).items.iter().map(|(_name, it)| (*it).into()).collect()
1856 pub fn items_with_supertraits(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
1857 let traits = all_super_traits(db.upcast(), self.into());
1858 traits.iter().flat_map(|tr| Trait::from(*tr).items(db)).collect()
1861 pub fn is_auto(self, db: &dyn HirDatabase) -> bool {
1862 db.trait_data(self.id).is_auto
1865 pub fn is_unsafe(&self, db: &dyn HirDatabase) -> bool {
1866 db.trait_data(self.id).is_unsafe
1869 pub fn type_or_const_param_count(
1871 db: &dyn HirDatabase,
1872 count_required_only: bool,
1874 db.generic_params(GenericDefId::from(self.id))
1877 .filter(|(_, ty)| match ty {
1878 TypeOrConstParamData::TypeParamData(ty)
1879 if ty.provenance != TypeParamProvenance::TypeParamList =>
1885 .filter(|(_, ty)| !count_required_only || !ty.has_default())
1890 impl HasVisibility for Trait {
1891 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1892 db.trait_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1896 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1897 pub struct TypeAlias {
1898 pub(crate) id: TypeAliasId,
1902 pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
1903 let subst = db.generic_defaults(self.id.into());
1904 subst.iter().any(|ty| match ty.skip_binders().data(Interner) {
1905 GenericArgData::Ty(x) => x.is_unknown(),
1910 pub fn module(self, db: &dyn HirDatabase) -> Module {
1911 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
1914 pub fn type_ref(self, db: &dyn HirDatabase) -> Option<TypeRef> {
1915 db.type_alias_data(self.id).type_ref.as_deref().cloned()
1918 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1919 Type::from_def(db, self.id)
1922 pub fn name(self, db: &dyn HirDatabase) -> Name {
1923 db.type_alias_data(self.id).name.clone()
1927 impl HasVisibility for TypeAlias {
1928 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1929 let function_data = db.type_alias_data(self.id);
1930 let visibility = &function_data.visibility;
1931 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1935 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1936 pub struct BuiltinType {
1937 pub(crate) inner: hir_def::builtin_type::BuiltinType,
1941 pub fn str() -> BuiltinType {
1942 BuiltinType { inner: hir_def::builtin_type::BuiltinType::Str }
1945 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1946 Type::new_for_crate(db.crate_graph().iter().next().unwrap(), TyBuilder::builtin(self.inner))
1949 pub fn name(self) -> Name {
1950 self.inner.as_name()
1953 pub fn is_int(&self) -> bool {
1954 matches!(self.inner, hir_def::builtin_type::BuiltinType::Int(_))
1957 pub fn is_uint(&self) -> bool {
1958 matches!(self.inner, hir_def::builtin_type::BuiltinType::Uint(_))
1961 pub fn is_float(&self) -> bool {
1962 matches!(self.inner, hir_def::builtin_type::BuiltinType::Float(_))
1965 pub fn is_char(&self) -> bool {
1966 matches!(self.inner, hir_def::builtin_type::BuiltinType::Char)
1969 pub fn is_bool(&self) -> bool {
1970 matches!(self.inner, hir_def::builtin_type::BuiltinType::Bool)
1973 pub fn is_str(&self) -> bool {
1974 matches!(self.inner, hir_def::builtin_type::BuiltinType::Str)
1978 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1979 pub enum MacroKind {
1980 /// `macro_rules!` or Macros 2.0 macro.
1982 /// A built-in or custom derive.
1984 /// A built-in function-like macro.
1986 /// A procedural attribute macro.
1988 /// A function-like procedural macro.
1992 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1994 pub(crate) id: MacroId,
1998 pub fn module(self, db: &dyn HirDatabase) -> Module {
1999 Module { id: self.id.module(db.upcast()) }
2002 pub fn name(self, db: &dyn HirDatabase) -> Name {
2004 MacroId::Macro2Id(id) => db.macro2_data(id).name.clone(),
2005 MacroId::MacroRulesId(id) => db.macro_rules_data(id).name.clone(),
2006 MacroId::ProcMacroId(id) => db.proc_macro_data(id).name.clone(),
2010 pub fn is_macro_export(self, db: &dyn HirDatabase) -> bool {
2011 matches!(self.id, MacroId::MacroRulesId(id) if db.macro_rules_data(id).macro_export)
2014 pub fn kind(&self, db: &dyn HirDatabase) -> MacroKind {
2016 MacroId::Macro2Id(it) => match it.lookup(db.upcast()).expander {
2017 MacroExpander::Declarative => MacroKind::Declarative,
2018 MacroExpander::BuiltIn(_) | MacroExpander::BuiltInEager(_) => MacroKind::BuiltIn,
2019 MacroExpander::BuiltInAttr(_) => MacroKind::Attr,
2020 MacroExpander::BuiltInDerive(_) => MacroKind::Derive,
2022 MacroId::MacroRulesId(it) => match it.lookup(db.upcast()).expander {
2023 MacroExpander::Declarative => MacroKind::Declarative,
2024 MacroExpander::BuiltIn(_) | MacroExpander::BuiltInEager(_) => MacroKind::BuiltIn,
2025 MacroExpander::BuiltInAttr(_) => MacroKind::Attr,
2026 MacroExpander::BuiltInDerive(_) => MacroKind::Derive,
2028 MacroId::ProcMacroId(it) => match it.lookup(db.upcast()).kind {
2029 ProcMacroKind::CustomDerive => MacroKind::Derive,
2030 ProcMacroKind::FuncLike => MacroKind::ProcMacro,
2031 ProcMacroKind::Attr => MacroKind::Attr,
2036 pub fn is_fn_like(&self, db: &dyn HirDatabase) -> bool {
2037 match self.kind(db) {
2038 MacroKind::Declarative | MacroKind::BuiltIn | MacroKind::ProcMacro => true,
2039 MacroKind::Attr | MacroKind::Derive => false,
2043 pub fn is_builtin_derive(&self, db: &dyn HirDatabase) -> bool {
2045 MacroId::Macro2Id(it) => {
2046 matches!(it.lookup(db.upcast()).expander, MacroExpander::BuiltInDerive(_))
2048 MacroId::MacroRulesId(it) => {
2049 matches!(it.lookup(db.upcast()).expander, MacroExpander::BuiltInDerive(_))
2051 MacroId::ProcMacroId(_) => false,
2055 pub fn is_attr(&self, db: &dyn HirDatabase) -> bool {
2056 matches!(self.kind(db), MacroKind::Attr)
2059 pub fn is_derive(&self, db: &dyn HirDatabase) -> bool {
2060 matches!(self.kind(db), MacroKind::Derive)
2064 impl HasVisibility for Macro {
2065 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
2067 MacroId::Macro2Id(id) => {
2068 let data = db.macro2_data(id);
2069 let visibility = &data.visibility;
2070 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
2072 MacroId::MacroRulesId(_) => Visibility::Public,
2073 MacroId::ProcMacroId(_) => Visibility::Public,
2078 #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
2085 impl From<Macro> for ItemInNs {
2086 fn from(it: Macro) -> Self {
2091 impl From<ModuleDef> for ItemInNs {
2092 fn from(module_def: ModuleDef) -> Self {
2094 ModuleDef::Static(_) | ModuleDef::Const(_) | ModuleDef::Function(_) => {
2095 ItemInNs::Values(module_def)
2097 _ => ItemInNs::Types(module_def),
2103 pub fn as_module_def(self) -> Option<ModuleDef> {
2105 ItemInNs::Types(id) | ItemInNs::Values(id) => Some(id),
2106 ItemInNs::Macros(_) => None,
2110 /// Returns the crate defining this item (or `None` if `self` is built-in).
2111 pub fn krate(&self, db: &dyn HirDatabase) -> Option<Crate> {
2113 ItemInNs::Types(did) | ItemInNs::Values(did) => did.module(db).map(|m| m.krate()),
2114 ItemInNs::Macros(id) => Some(id.module(db).krate()),
2118 pub fn attrs(&self, db: &dyn HirDatabase) -> Option<AttrsWithOwner> {
2120 ItemInNs::Types(it) | ItemInNs::Values(it) => it.attrs(db),
2121 ItemInNs::Macros(it) => Some(it.attrs(db)),
2126 /// Invariant: `inner.as_assoc_item(db).is_some()`
2127 /// We do not actively enforce this invariant.
2128 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2129 pub enum AssocItem {
2132 TypeAlias(TypeAlias),
2134 #[derive(Debug, Clone)]
2135 pub enum AssocItemContainer {
2139 pub trait AsAssocItem {
2140 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem>;
2143 impl AsAssocItem for Function {
2144 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
2145 as_assoc_item(db, AssocItem::Function, self.id)
2148 impl AsAssocItem for Const {
2149 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
2150 as_assoc_item(db, AssocItem::Const, self.id)
2153 impl AsAssocItem for TypeAlias {
2154 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
2155 as_assoc_item(db, AssocItem::TypeAlias, self.id)
2158 impl AsAssocItem for ModuleDef {
2159 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
2161 ModuleDef::Function(it) => it.as_assoc_item(db),
2162 ModuleDef::Const(it) => it.as_assoc_item(db),
2163 ModuleDef::TypeAlias(it) => it.as_assoc_item(db),
2168 impl AsAssocItem for DefWithBody {
2169 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
2171 DefWithBody::Function(it) => it.as_assoc_item(db),
2172 DefWithBody::Const(it) => it.as_assoc_item(db),
2173 DefWithBody::Static(_) | DefWithBody::Variant(_) => None,
2178 fn as_assoc_item<ID, DEF, CTOR, AST>(db: &dyn HirDatabase, ctor: CTOR, id: ID) -> Option<AssocItem>
2180 ID: Lookup<Data = AssocItemLoc<AST>>,
2182 CTOR: FnOnce(DEF) -> AssocItem,
2185 match id.lookup(db.upcast()).container {
2186 ItemContainerId::TraitId(_) | ItemContainerId::ImplId(_) => Some(ctor(DEF::from(id))),
2187 ItemContainerId::ModuleId(_) | ItemContainerId::ExternBlockId(_) => None,
2192 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
2194 AssocItem::Function(it) => Some(it.name(db)),
2195 AssocItem::Const(it) => it.name(db),
2196 AssocItem::TypeAlias(it) => Some(it.name(db)),
2199 pub fn module(self, db: &dyn HirDatabase) -> Module {
2201 AssocItem::Function(f) => f.module(db),
2202 AssocItem::Const(c) => c.module(db),
2203 AssocItem::TypeAlias(t) => t.module(db),
2206 pub fn container(self, db: &dyn HirDatabase) -> AssocItemContainer {
2207 let container = match self {
2208 AssocItem::Function(it) => it.id.lookup(db.upcast()).container,
2209 AssocItem::Const(it) => it.id.lookup(db.upcast()).container,
2210 AssocItem::TypeAlias(it) => it.id.lookup(db.upcast()).container,
2213 ItemContainerId::TraitId(id) => AssocItemContainer::Trait(id.into()),
2214 ItemContainerId::ImplId(id) => AssocItemContainer::Impl(id.into()),
2215 ItemContainerId::ModuleId(_) | ItemContainerId::ExternBlockId(_) => {
2216 panic!("invalid AssocItem")
2221 pub fn containing_trait(self, db: &dyn HirDatabase) -> Option<Trait> {
2222 match self.container(db) {
2223 AssocItemContainer::Trait(t) => Some(t),
2228 pub fn containing_trait_impl(self, db: &dyn HirDatabase) -> Option<Trait> {
2229 match self.container(db) {
2230 AssocItemContainer::Impl(i) => i.trait_(db),
2235 pub fn containing_trait_or_trait_impl(self, db: &dyn HirDatabase) -> Option<Trait> {
2236 match self.container(db) {
2237 AssocItemContainer::Trait(t) => Some(t),
2238 AssocItemContainer::Impl(i) => i.trait_(db),
2243 impl HasVisibility for AssocItem {
2244 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
2246 AssocItem::Function(f) => f.visibility(db),
2247 AssocItem::Const(c) => c.visibility(db),
2248 AssocItem::TypeAlias(t) => t.visibility(db),
2253 impl From<AssocItem> for ModuleDef {
2254 fn from(assoc: AssocItem) -> Self {
2256 AssocItem::Function(it) => ModuleDef::Function(it),
2257 AssocItem::Const(it) => ModuleDef::Const(it),
2258 AssocItem::TypeAlias(it) => ModuleDef::TypeAlias(it),
2263 #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
2264 pub enum GenericDef {
2268 TypeAlias(TypeAlias),
2270 // enum variants cannot have generics themselves, but their parent enums
2271 // can, and this makes some code easier to write
2273 // consts can have type parameters from their parents (i.e. associated consts of traits)
2278 Adt(Struct, Enum, Union),
2288 pub fn params(self, db: &dyn HirDatabase) -> Vec<GenericParam> {
2289 let generics = db.generic_params(self.into());
2290 let ty_params = generics.type_or_consts.iter().map(|(local_id, _)| {
2291 let toc = TypeOrConstParam { id: TypeOrConstParamId { parent: self.into(), local_id } };
2292 match toc.split(db) {
2293 Either::Left(x) => GenericParam::ConstParam(x),
2294 Either::Right(x) => GenericParam::TypeParam(x),
2297 let lt_params = generics
2300 .map(|(local_id, _)| LifetimeParam {
2301 id: LifetimeParamId { parent: self.into(), local_id },
2303 .map(GenericParam::LifetimeParam);
2304 lt_params.chain(ty_params).collect()
2307 pub fn type_params(self, db: &dyn HirDatabase) -> Vec<TypeOrConstParam> {
2308 let generics = db.generic_params(self.into());
2312 .map(|(local_id, _)| TypeOrConstParam {
2313 id: TypeOrConstParamId { parent: self.into(), local_id },
2319 /// A single local definition.
2321 /// If the definition of this is part of a "MultiLocal", that is a local that has multiple declarations due to or-patterns
2322 /// then this only references a single one of those.
2323 /// To retrieve the other locals you should use [`Local::associated_locals`]
2324 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2326 pub(crate) parent: DefWithBodyId,
2327 pub(crate) pat_id: PatId,
2331 pub fn is_param(self, db: &dyn HirDatabase) -> bool {
2332 let src = self.source(db);
2334 Either::Left(pat) => pat
2337 .map(|it| it.kind())
2338 .take_while(|&kind| ast::Pat::can_cast(kind) || ast::Param::can_cast(kind))
2339 .any(ast::Param::can_cast),
2340 Either::Right(_) => true,
2344 pub fn as_self_param(self, db: &dyn HirDatabase) -> Option<SelfParam> {
2346 DefWithBodyId::FunctionId(func) if self.is_self(db) => Some(SelfParam { func }),
2351 pub fn name(self, db: &dyn HirDatabase) -> Name {
2352 let body = db.body(self.parent);
2353 match &body[self.pat_id] {
2354 Pat::Bind { name, .. } => name.clone(),
2356 stdx::never!("hir::Local is missing a name!");
2362 pub fn is_self(self, db: &dyn HirDatabase) -> bool {
2363 self.name(db) == name![self]
2366 pub fn is_mut(self, db: &dyn HirDatabase) -> bool {
2367 let body = db.body(self.parent);
2368 matches!(&body[self.pat_id], Pat::Bind { mode: BindingAnnotation::Mutable, .. })
2371 pub fn is_ref(self, db: &dyn HirDatabase) -> bool {
2372 let body = db.body(self.parent);
2375 Pat::Bind { mode: BindingAnnotation::Ref | BindingAnnotation::RefMut, .. }
2379 pub fn parent(self, _db: &dyn HirDatabase) -> DefWithBody {
2383 pub fn module(self, db: &dyn HirDatabase) -> Module {
2384 self.parent(db).module(db)
2387 pub fn ty(self, db: &dyn HirDatabase) -> Type {
2388 let def = self.parent;
2389 let infer = db.infer(def);
2390 let ty = infer[self.pat_id].clone();
2391 Type::new(db, def, ty)
2394 pub fn associated_locals(self, db: &dyn HirDatabase) -> Box<[Local]> {
2395 let body = db.body(self.parent);
2396 body.ident_patterns_for(&self.pat_id)
2398 .map(|&pat_id| Local { parent: self.parent, pat_id })
2402 /// If this local is part of a multi-local, retrieve the representative local.
2403 /// That is the local that references are being resolved to.
2404 pub fn representative(self, db: &dyn HirDatabase) -> Local {
2405 let body = db.body(self.parent);
2406 Local { pat_id: body.pattern_representative(self.pat_id), ..self }
2409 pub fn source(self, db: &dyn HirDatabase) -> InFile<Either<ast::IdentPat, ast::SelfParam>> {
2410 let (_body, source_map) = db.body_with_source_map(self.parent);
2411 let src = source_map.pat_syntax(self.pat_id).unwrap(); // Hmm...
2412 let root = src.file_syntax(db.upcast());
2413 src.map(|ast| match ast {
2414 // Suspicious unwrap
2415 Either::Left(it) => Either::Left(it.cast().unwrap().to_node(&root)),
2416 Either::Right(it) => Either::Right(it.to_node(&root)),
2421 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2422 pub struct DeriveHelper {
2423 pub(crate) derive: MacroId,
2424 pub(crate) idx: u32,
2428 pub fn derive(&self) -> Macro {
2429 Macro { id: self.derive }
2432 pub fn name(&self, db: &dyn HirDatabase) -> Name {
2434 MacroId::Macro2Id(it) => db
2438 .and_then(|it| it.get(self.idx as usize))
2440 MacroId::MacroRulesId(_) => None,
2441 MacroId::ProcMacroId(proc_macro) => db
2442 .proc_macro_data(proc_macro)
2445 .and_then(|it| it.get(self.idx as usize))
2448 .unwrap_or_else(|| Name::missing())
2452 // FIXME: Wrong name? This is could also be a registered attribute
2453 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2454 pub struct BuiltinAttr {
2455 krate: Option<CrateId>,
2460 // FIXME: consider crates\hir_def\src\nameres\attr_resolution.rs?
2461 pub(crate) fn by_name(db: &dyn HirDatabase, krate: Crate, name: &str) -> Option<Self> {
2462 if let builtin @ Some(_) = Self::builtin(name) {
2466 db.crate_def_map(krate.id).registered_attrs().iter().position(|it| it == name)? as u32;
2467 Some(BuiltinAttr { krate: Some(krate.id), idx })
2470 fn builtin(name: &str) -> Option<Self> {
2471 hir_def::builtin_attr::INERT_ATTRIBUTES
2473 .position(|tool| tool.name == name)
2474 .map(|idx| BuiltinAttr { krate: None, idx: idx as u32 })
2477 pub fn name(&self, db: &dyn HirDatabase) -> SmolStr {
2478 // FIXME: Return a `Name` here
2480 Some(krate) => db.crate_def_map(krate).registered_attrs()[self.idx as usize].clone(),
2481 None => SmolStr::new(hir_def::builtin_attr::INERT_ATTRIBUTES[self.idx as usize].name),
2485 pub fn template(&self, _: &dyn HirDatabase) -> Option<AttributeTemplate> {
2488 None => Some(hir_def::builtin_attr::INERT_ATTRIBUTES[self.idx as usize].template),
2493 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2494 pub struct ToolModule {
2495 krate: Option<CrateId>,
2500 // FIXME: consider crates\hir_def\src\nameres\attr_resolution.rs?
2501 pub(crate) fn by_name(db: &dyn HirDatabase, krate: Crate, name: &str) -> Option<Self> {
2502 if let builtin @ Some(_) = Self::builtin(name) {
2506 db.crate_def_map(krate.id).registered_tools().iter().position(|it| it == name)? as u32;
2507 Some(ToolModule { krate: Some(krate.id), idx })
2510 fn builtin(name: &str) -> Option<Self> {
2511 hir_def::builtin_attr::TOOL_MODULES
2513 .position(|&tool| tool == name)
2514 .map(|idx| ToolModule { krate: None, idx: idx as u32 })
2517 pub fn name(&self, db: &dyn HirDatabase) -> SmolStr {
2518 // FIXME: Return a `Name` here
2520 Some(krate) => db.crate_def_map(krate).registered_tools()[self.idx as usize].clone(),
2521 None => SmolStr::new(hir_def::builtin_attr::TOOL_MODULES[self.idx as usize]),
2526 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2528 pub(crate) parent: DefWithBodyId,
2529 pub(crate) label_id: LabelId,
2533 pub fn module(self, db: &dyn HirDatabase) -> Module {
2534 self.parent(db).module(db)
2537 pub fn parent(self, _db: &dyn HirDatabase) -> DefWithBody {
2541 pub fn name(self, db: &dyn HirDatabase) -> Name {
2542 let body = db.body(self.parent);
2543 body[self.label_id].name.clone()
2546 pub fn source(self, db: &dyn HirDatabase) -> InFile<ast::Label> {
2547 let (_body, source_map) = db.body_with_source_map(self.parent);
2548 let src = source_map.label_syntax(self.label_id);
2549 let root = src.file_syntax(db.upcast());
2550 src.map(|ast| ast.to_node(&root))
2554 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2555 pub enum GenericParam {
2556 TypeParam(TypeParam),
2557 ConstParam(ConstParam),
2558 LifetimeParam(LifetimeParam),
2560 impl_from!(TypeParam, ConstParam, LifetimeParam for GenericParam);
2563 pub fn module(self, db: &dyn HirDatabase) -> Module {
2565 GenericParam::TypeParam(it) => it.module(db),
2566 GenericParam::ConstParam(it) => it.module(db),
2567 GenericParam::LifetimeParam(it) => it.module(db),
2571 pub fn name(self, db: &dyn HirDatabase) -> Name {
2573 GenericParam::TypeParam(it) => it.name(db),
2574 GenericParam::ConstParam(it) => it.name(db),
2575 GenericParam::LifetimeParam(it) => it.name(db),
2579 pub fn parent(self) -> GenericDef {
2581 GenericParam::TypeParam(it) => it.id.parent().into(),
2582 GenericParam::ConstParam(it) => it.id.parent().into(),
2583 GenericParam::LifetimeParam(it) => it.id.parent.into(),
2588 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2589 pub struct TypeParam {
2590 pub(crate) id: TypeParamId,
2594 pub fn merge(self) -> TypeOrConstParam {
2595 TypeOrConstParam { id: self.id.into() }
2598 pub fn name(self, db: &dyn HirDatabase) -> Name {
2599 self.merge().name(db)
2602 pub fn module(self, db: &dyn HirDatabase) -> Module {
2603 self.id.parent().module(db.upcast()).into()
2606 /// Is this type parameter implicitly introduced (eg. `Self` in a trait or an `impl Trait`
2608 pub fn is_implicit(self, db: &dyn HirDatabase) -> bool {
2609 let params = db.generic_params(self.id.parent());
2610 let data = ¶ms.type_or_consts[self.id.local_id()];
2611 match data.type_param().unwrap().provenance {
2612 hir_def::generics::TypeParamProvenance::TypeParamList => false,
2613 hir_def::generics::TypeParamProvenance::TraitSelf
2614 | hir_def::generics::TypeParamProvenance::ArgumentImplTrait => true,
2618 pub fn ty(self, db: &dyn HirDatabase) -> Type {
2619 let resolver = self.id.parent().resolver(db.upcast());
2621 TyKind::Placeholder(hir_ty::to_placeholder_idx(db, self.id.into())).intern(Interner);
2622 Type::new_with_resolver_inner(db, &resolver, ty)
2625 /// FIXME: this only lists trait bounds from the item defining the type
2626 /// parameter, not additional bounds that might be added e.g. by a method if
2627 /// the parameter comes from an impl!
2628 pub fn trait_bounds(self, db: &dyn HirDatabase) -> Vec<Trait> {
2629 db.generic_predicates_for_param(self.id.parent(), self.id.into(), None)
2631 .filter_map(|pred| match &pred.skip_binders().skip_binders() {
2632 hir_ty::WhereClause::Implemented(trait_ref) => {
2633 Some(Trait::from(trait_ref.hir_trait_id()))
2640 pub fn default(self, db: &dyn HirDatabase) -> Option<Type> {
2641 let params = db.generic_defaults(self.id.parent());
2642 let local_idx = hir_ty::param_idx(db, self.id.into())?;
2643 let resolver = self.id.parent().resolver(db.upcast());
2644 let ty = params.get(local_idx)?.clone();
2645 let subst = TyBuilder::placeholder_subst(db, self.id.parent());
2646 let ty = ty.substitute(Interner, &subst);
2647 match ty.data(Interner) {
2648 GenericArgData::Ty(x) => Some(Type::new_with_resolver_inner(db, &resolver, x.clone())),
2654 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2655 pub struct LifetimeParam {
2656 pub(crate) id: LifetimeParamId,
2659 impl LifetimeParam {
2660 pub fn name(self, db: &dyn HirDatabase) -> Name {
2661 let params = db.generic_params(self.id.parent);
2662 params.lifetimes[self.id.local_id].name.clone()
2665 pub fn module(self, db: &dyn HirDatabase) -> Module {
2666 self.id.parent.module(db.upcast()).into()
2669 pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef {
2670 self.id.parent.into()
2674 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2675 pub struct ConstParam {
2676 pub(crate) id: ConstParamId,
2680 pub fn merge(self) -> TypeOrConstParam {
2681 TypeOrConstParam { id: self.id.into() }
2684 pub fn name(self, db: &dyn HirDatabase) -> Name {
2685 let params = db.generic_params(self.id.parent());
2686 match params.type_or_consts[self.id.local_id()].name() {
2687 Some(x) => x.clone(),
2695 pub fn module(self, db: &dyn HirDatabase) -> Module {
2696 self.id.parent().module(db.upcast()).into()
2699 pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef {
2700 self.id.parent().into()
2703 pub fn ty(self, db: &dyn HirDatabase) -> Type {
2704 Type::new(db, self.id.parent(), db.const_param_ty(self.id))
2708 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2709 pub struct TypeOrConstParam {
2710 pub(crate) id: TypeOrConstParamId,
2713 impl TypeOrConstParam {
2714 pub fn name(self, db: &dyn HirDatabase) -> Name {
2715 let params = db.generic_params(self.id.parent);
2716 match params.type_or_consts[self.id.local_id].name() {
2717 Some(n) => n.clone(),
2718 _ => Name::missing(),
2722 pub fn module(self, db: &dyn HirDatabase) -> Module {
2723 self.id.parent.module(db.upcast()).into()
2726 pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef {
2727 self.id.parent.into()
2730 pub fn split(self, db: &dyn HirDatabase) -> Either<ConstParam, TypeParam> {
2731 let params = db.generic_params(self.id.parent);
2732 match ¶ms.type_or_consts[self.id.local_id] {
2733 hir_def::generics::TypeOrConstParamData::TypeParamData(_) => {
2734 Either::Right(TypeParam { id: TypeParamId::from_unchecked(self.id) })
2736 hir_def::generics::TypeOrConstParamData::ConstParamData(_) => {
2737 Either::Left(ConstParam { id: ConstParamId::from_unchecked(self.id) })
2742 pub fn ty(self, db: &dyn HirDatabase) -> Type {
2743 match self.split(db) {
2744 Either::Left(x) => x.ty(db),
2745 Either::Right(x) => x.ty(db),
2750 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2752 pub(crate) id: ImplId,
2756 pub fn all_in_crate(db: &dyn HirDatabase, krate: Crate) -> Vec<Impl> {
2757 let inherent = db.inherent_impls_in_crate(krate.id);
2758 let trait_ = db.trait_impls_in_crate(krate.id);
2760 inherent.all_impls().chain(trait_.all_impls()).map(Self::from).collect()
2763 pub fn all_for_type(db: &dyn HirDatabase, Type { ty, env }: Type) -> Vec<Impl> {
2764 let def_crates = match method_resolution::def_crates(db, &ty, env.krate) {
2765 Some(def_crates) => def_crates,
2766 None => return Vec::new(),
2769 let filter = |impl_def: &Impl| {
2770 let self_ty = impl_def.self_ty(db);
2771 let rref = self_ty.remove_ref();
2772 ty.equals_ctor(rref.as_ref().map_or(&self_ty.ty, |it| &it.ty))
2775 let fp = TyFingerprint::for_inherent_impl(&ty);
2778 None => return Vec::new(),
2781 let mut all = Vec::new();
2782 def_crates.iter().for_each(|&id| {
2784 db.inherent_impls_in_crate(id)
2792 for id in def_crates
2794 .flat_map(|&id| Crate { id }.transitive_reverse_dependencies(db))
2795 .map(|Crate { id }| id)
2796 .chain(def_crates.iter().copied())
2800 db.trait_impls_in_crate(id)
2801 .for_self_ty_without_blanket_impls(fp)
2809 pub fn all_for_trait(db: &dyn HirDatabase, trait_: Trait) -> Vec<Impl> {
2810 let krate = trait_.module(db).krate();
2811 let mut all = Vec::new();
2812 for Crate { id } in krate.transitive_reverse_dependencies(db) {
2813 let impls = db.trait_impls_in_crate(id);
2814 all.extend(impls.for_trait(trait_.id).map(Self::from))
2819 pub fn trait_(self, db: &dyn HirDatabase) -> Option<Trait> {
2820 let trait_ref = db.impl_trait(self.id)?;
2821 let id = trait_ref.skip_binders().hir_trait_id();
2825 pub fn trait_ref(self, db: &dyn HirDatabase) -> Option<TraitRef> {
2826 let substs = TyBuilder::placeholder_subst(db, self.id);
2827 let trait_ref = db.impl_trait(self.id)?.substitute(Interner, &substs);
2828 let resolver = self.id.resolver(db.upcast());
2829 Some(TraitRef::new_with_resolver(db, &resolver, trait_ref))
2832 pub fn self_ty(self, db: &dyn HirDatabase) -> Type {
2833 let resolver = self.id.resolver(db.upcast());
2834 let substs = TyBuilder::placeholder_subst(db, self.id);
2835 let ty = db.impl_self_ty(self.id).substitute(Interner, &substs);
2836 Type::new_with_resolver_inner(db, &resolver, ty)
2839 pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
2840 db.impl_data(self.id).items.iter().map(|it| (*it).into()).collect()
2843 pub fn is_negative(self, db: &dyn HirDatabase) -> bool {
2844 db.impl_data(self.id).is_negative
2847 pub fn module(self, db: &dyn HirDatabase) -> Module {
2848 self.id.lookup(db.upcast()).container.into()
2851 pub fn is_builtin_derive(self, db: &dyn HirDatabase) -> Option<InFile<ast::Attr>> {
2852 let src = self.source(db)?;
2853 src.file_id.is_builtin_derive(db.upcast())
2857 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
2858 pub struct TraitRef {
2859 env: Arc<TraitEnvironment>,
2860 trait_ref: hir_ty::TraitRef,
2864 pub(crate) fn new_with_resolver(
2865 db: &dyn HirDatabase,
2866 resolver: &Resolver,
2867 trait_ref: hir_ty::TraitRef,
2869 let env = resolver.generic_def().map_or_else(
2870 || Arc::new(TraitEnvironment::empty(resolver.krate())),
2871 |d| db.trait_environment(d),
2873 TraitRef { env, trait_ref }
2876 pub fn trait_(&self) -> Trait {
2877 let id = self.trait_ref.hir_trait_id();
2881 pub fn self_ty(&self) -> Type {
2882 let ty = self.trait_ref.self_type_parameter(Interner);
2883 Type { env: self.env.clone(), ty }
2886 /// Returns `idx`-th argument of this trait reference if it is a type argument. Note that the
2887 /// first argument is the `Self` type.
2888 pub fn get_type_argument(&self, idx: usize) -> Option<Type> {
2893 .and_then(|arg| arg.ty(Interner))
2895 .map(|ty| Type { env: self.env.clone(), ty })
2899 #[derive(Clone, PartialEq, Eq, Debug)]
2901 env: Arc<TraitEnvironment>,
2906 pub(crate) fn new_with_resolver(db: &dyn HirDatabase, resolver: &Resolver, ty: Ty) -> Type {
2907 Type::new_with_resolver_inner(db, resolver, ty)
2910 pub(crate) fn new_with_resolver_inner(
2911 db: &dyn HirDatabase,
2912 resolver: &Resolver,
2915 let environment = resolver.generic_def().map_or_else(
2916 || Arc::new(TraitEnvironment::empty(resolver.krate())),
2917 |d| db.trait_environment(d),
2919 Type { env: environment, ty }
2922 pub(crate) fn new_for_crate(krate: CrateId, ty: Ty) -> Type {
2923 Type { env: Arc::new(TraitEnvironment::empty(krate)), ty }
2926 pub fn reference(inner: &Type, m: Mutability) -> Type {
2929 if m.is_mut() { hir_ty::Mutability::Mut } else { hir_ty::Mutability::Not },
2930 hir_ty::static_lifetime(),
2937 fn new(db: &dyn HirDatabase, lexical_env: impl HasResolver, ty: Ty) -> Type {
2938 let resolver = lexical_env.resolver(db.upcast());
2939 let environment = resolver.generic_def().map_or_else(
2940 || Arc::new(TraitEnvironment::empty(resolver.krate())),
2941 |d| db.trait_environment(d),
2943 Type { env: environment, ty }
2946 fn from_def(db: &dyn HirDatabase, def: impl HasResolver + Into<TyDefId>) -> Type {
2947 let ty_def = def.into();
2948 let parent_subst = match ty_def {
2949 TyDefId::TypeAliasId(id) => match id.lookup(db.upcast()).container {
2950 ItemContainerId::TraitId(id) => {
2951 let subst = TyBuilder::subst_for_def(db, id, None).fill_with_unknown().build();
2954 ItemContainerId::ImplId(id) => {
2955 let subst = TyBuilder::subst_for_def(db, id, None).fill_with_unknown().build();
2962 let ty = TyBuilder::def_ty(db, ty_def, parent_subst).fill_with_unknown().build();
2963 Type::new(db, def, ty)
2966 pub fn new_slice(ty: Type) -> Type {
2967 Type { env: ty.env, ty: TyBuilder::slice(ty.ty) }
2970 pub fn is_unit(&self) -> bool {
2971 matches!(self.ty.kind(Interner), TyKind::Tuple(0, ..))
2974 pub fn is_bool(&self) -> bool {
2975 matches!(self.ty.kind(Interner), TyKind::Scalar(Scalar::Bool))
2978 pub fn is_never(&self) -> bool {
2979 matches!(self.ty.kind(Interner), TyKind::Never)
2982 pub fn is_mutable_reference(&self) -> bool {
2983 matches!(self.ty.kind(Interner), TyKind::Ref(hir_ty::Mutability::Mut, ..))
2986 pub fn is_reference(&self) -> bool {
2987 matches!(self.ty.kind(Interner), TyKind::Ref(..))
2990 pub fn as_reference(&self) -> Option<(Type, Mutability)> {
2991 let (ty, _lt, m) = self.ty.as_reference()?;
2992 let m = Mutability::from_mutable(matches!(m, hir_ty::Mutability::Mut));
2993 Some((self.derived(ty.clone()), m))
2996 pub fn is_slice(&self) -> bool {
2997 matches!(self.ty.kind(Interner), TyKind::Slice(..))
3000 pub fn is_usize(&self) -> bool {
3001 matches!(self.ty.kind(Interner), TyKind::Scalar(Scalar::Uint(UintTy::Usize)))
3004 pub fn is_int_or_uint(&self) -> bool {
3005 match self.ty.kind(Interner) {
3006 TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_)) => true,
3011 pub fn remove_ref(&self) -> Option<Type> {
3012 match &self.ty.kind(Interner) {
3013 TyKind::Ref(.., ty) => Some(self.derived(ty.clone())),
3018 pub fn strip_references(&self) -> Type {
3019 self.derived(self.ty.strip_references().clone())
3022 pub fn strip_reference(&self) -> Type {
3023 self.derived(self.ty.strip_reference().clone())
3026 pub fn is_unknown(&self) -> bool {
3027 self.ty.is_unknown()
3030 /// Checks that particular type `ty` implements `std::future::IntoFuture` or
3031 /// `std::future::Future`.
3032 /// This function is used in `.await` syntax completion.
3033 pub fn impls_into_future(&self, db: &dyn HirDatabase) -> bool {
3035 .lang_item(self.env.krate, LangItem::IntoFutureIntoFuture)
3037 let into_future_fn = it.as_function()?;
3038 let assoc_item = as_assoc_item(db, AssocItem::Function, into_future_fn)?;
3039 let into_future_trait = assoc_item.containing_trait_or_trait_impl(db)?;
3040 Some(into_future_trait.id)
3043 let future_trait = db.lang_item(self.env.krate, LangItem::Future)?;
3044 future_trait.as_trait()
3047 let trait_ = match trait_ {
3049 None => return false,
3053 Canonical { value: self.ty.clone(), binders: CanonicalVarKinds::empty(Interner) };
3054 method_resolution::implements_trait(&canonical_ty, db, self.env.clone(), trait_)
3057 /// Checks that particular type `ty` implements `std::ops::FnOnce`.
3059 /// This function can be used to check if a particular type is callable, since FnOnce is a
3060 /// supertrait of Fn and FnMut, so all callable types implements at least FnOnce.
3061 pub fn impls_fnonce(&self, db: &dyn HirDatabase) -> bool {
3062 let fnonce_trait = match FnTrait::FnOnce.get_id(db, self.env.krate) {
3064 None => return false,
3068 Canonical { value: self.ty.clone(), binders: CanonicalVarKinds::empty(Interner) };
3069 method_resolution::implements_trait_unique(
3077 pub fn impls_trait(&self, db: &dyn HirDatabase, trait_: Trait, args: &[Type]) -> bool {
3078 let mut it = args.iter().map(|t| t.ty.clone());
3079 let trait_ref = TyBuilder::trait_ref(db, trait_.id)
3080 .push(self.ty.clone())
3082 let r = it.next().unwrap();
3084 ParamKind::Type => GenericArgData::Ty(r).intern(Interner),
3085 ParamKind::Const(ty) => {
3086 // FIXME: this code is not covered in tests.
3087 unknown_const_as_generic(ty.clone())
3093 let goal = Canonical {
3094 value: hir_ty::InEnvironment::new(&self.env.env, trait_ref.cast(Interner)),
3095 binders: CanonicalVarKinds::empty(Interner),
3098 db.trait_solve(self.env.krate, goal).is_some()
3101 pub fn normalize_trait_assoc_type(
3103 db: &dyn HirDatabase,
3107 let mut args = args.iter();
3108 let trait_id = match alias.id.lookup(db.upcast()).container {
3109 ItemContainerId::TraitId(id) => id,
3110 _ => unreachable!("non assoc type alias reached in normalize_trait_assoc_type()"),
3112 let parent_subst = TyBuilder::subst_for_def(db, trait_id, None)
3113 .push(self.ty.clone())
3115 // FIXME: this code is not covered in tests.
3117 ParamKind::Type => {
3118 GenericArgData::Ty(args.next().unwrap().ty.clone()).intern(Interner)
3120 ParamKind::Const(ty) => unknown_const_as_generic(ty.clone()),
3124 // FIXME: We don't handle GATs yet.
3125 let projection = TyBuilder::assoc_type_projection(db, alias.id, Some(parent_subst)).build();
3127 let ty = db.normalize_projection(projection, self.env.clone());
3128 if ty.is_unknown() {
3131 Some(self.derived(ty))
3135 pub fn is_copy(&self, db: &dyn HirDatabase) -> bool {
3136 let lang_item = db.lang_item(self.env.krate, LangItem::Copy);
3137 let copy_trait = match lang_item {
3138 Some(LangItemTarget::Trait(it)) => it,
3141 self.impls_trait(db, copy_trait.into(), &[])
3144 pub fn as_callable(&self, db: &dyn HirDatabase) -> Option<Callable> {
3145 let callee = match self.ty.kind(Interner) {
3146 TyKind::Closure(id, _) => Callee::Closure(*id),
3147 TyKind::Function(_) => Callee::FnPtr,
3148 TyKind::FnDef(..) => Callee::Def(self.ty.callable_def(db)?),
3150 let sig = hir_ty::callable_sig_from_fnonce(&self.ty, self.env.clone(), db)?;
3151 return Some(Callable {
3154 callee: Callee::Other,
3155 is_bound_method: false,
3160 let sig = self.ty.callable_sig(db)?;
3161 Some(Callable { ty: self.clone(), sig, callee, is_bound_method: false })
3164 pub fn is_closure(&self) -> bool {
3165 matches!(self.ty.kind(Interner), TyKind::Closure { .. })
3168 pub fn is_fn(&self) -> bool {
3169 matches!(self.ty.kind(Interner), TyKind::FnDef(..) | TyKind::Function { .. })
3172 pub fn is_array(&self) -> bool {
3173 matches!(self.ty.kind(Interner), TyKind::Array(..))
3176 pub fn is_packed(&self, db: &dyn HirDatabase) -> bool {
3177 let adt_id = match *self.ty.kind(Interner) {
3178 TyKind::Adt(hir_ty::AdtId(adt_id), ..) => adt_id,
3182 let adt = adt_id.into();
3184 Adt::Struct(s) => s.repr(db).unwrap_or_default().pack.is_some(),
3189 pub fn is_raw_ptr(&self) -> bool {
3190 matches!(self.ty.kind(Interner), TyKind::Raw(..))
3193 pub fn contains_unknown(&self) -> bool {
3194 // FIXME: When we get rid of `ConstScalar::Unknown`, we can just look at precomputed
3195 // `TypeFlags` in `TyData`.
3196 return go(&self.ty);
3198 fn go(ty: &Ty) -> bool {
3199 match ty.kind(Interner) {
3200 TyKind::Error => true,
3202 TyKind::Adt(_, substs)
3203 | TyKind::AssociatedType(_, substs)
3204 | TyKind::Tuple(_, substs)
3205 | TyKind::OpaqueType(_, substs)
3206 | TyKind::FnDef(_, substs)
3207 | TyKind::Closure(_, substs) => {
3208 substs.iter(Interner).filter_map(|a| a.ty(Interner)).any(go)
3211 TyKind::Array(_ty, len) if len.is_unknown() => true,
3212 TyKind::Array(ty, _)
3214 | TyKind::Raw(_, ty)
3215 | TyKind::Ref(_, _, ty) => go(ty),
3220 | TyKind::Placeholder(_)
3221 | TyKind::BoundVar(_)
3222 | TyKind::InferenceVar(_, _)
3224 | TyKind::Function(_)
3226 | TyKind::Foreign(_)
3227 | TyKind::Generator(..)
3228 | TyKind::GeneratorWitness(..) => false,
3233 pub fn fields(&self, db: &dyn HirDatabase) -> Vec<(Field, Type)> {
3234 let (variant_id, substs) = match self.ty.kind(Interner) {
3235 TyKind::Adt(hir_ty::AdtId(AdtId::StructId(s)), substs) => ((*s).into(), substs),
3236 TyKind::Adt(hir_ty::AdtId(AdtId::UnionId(u)), substs) => ((*u).into(), substs),
3237 _ => return Vec::new(),
3240 db.field_types(variant_id)
3242 .map(|(local_id, ty)| {
3243 let def = Field { parent: variant_id.into(), id: local_id };
3244 let ty = ty.clone().substitute(Interner, substs);
3245 (def, self.derived(ty))
3250 pub fn tuple_fields(&self, _db: &dyn HirDatabase) -> Vec<Type> {
3251 if let TyKind::Tuple(_, substs) = &self.ty.kind(Interner) {
3254 .map(|ty| self.derived(ty.assert_ty_ref(Interner).clone()))
3261 pub fn as_array(&self, _db: &dyn HirDatabase) -> Option<(Type, usize)> {
3262 if let TyKind::Array(ty, len) = &self.ty.kind(Interner) {
3263 match len.data(Interner).value {
3264 ConstValue::Concrete(ConcreteConst { interned: ConstScalar::UInt(len) }) => {
3265 Some((self.derived(ty.clone()), len as usize))
3274 pub fn autoderef<'a>(&'a self, db: &'a dyn HirDatabase) -> impl Iterator<Item = Type> + 'a {
3275 self.autoderef_(db).map(move |ty| self.derived(ty))
3278 fn autoderef_<'a>(&'a self, db: &'a dyn HirDatabase) -> impl Iterator<Item = Ty> + 'a {
3279 // There should be no inference vars in types passed here
3280 let canonical = hir_ty::replace_errors_with_variables(&self.ty);
3281 let environment = self.env.clone();
3282 autoderef(db, environment, canonical).map(|canonical| canonical.value)
3285 // This would be nicer if it just returned an iterator, but that runs into
3286 // lifetime problems, because we need to borrow temp `CrateImplDefs`.
3287 pub fn iterate_assoc_items<T>(
3289 db: &dyn HirDatabase,
3291 mut callback: impl FnMut(AssocItem) -> Option<T>,
3293 let mut slot = None;
3294 self.iterate_assoc_items_dyn(db, krate, &mut |assoc_item_id| {
3295 slot = callback(assoc_item_id.into());
3301 fn iterate_assoc_items_dyn(
3303 db: &dyn HirDatabase,
3305 callback: &mut dyn FnMut(AssocItemId) -> bool,
3307 let def_crates = match method_resolution::def_crates(db, &self.ty, krate.id) {
3311 for krate in def_crates {
3312 let impls = db.inherent_impls_in_crate(krate);
3314 for impl_def in impls.for_self_ty(&self.ty) {
3315 for &item in db.impl_data(*impl_def).items.iter() {
3324 pub fn type_arguments(&self) -> impl Iterator<Item = Type> + '_ {
3329 .flat_map(|(_, substs)| substs.iter(Interner))
3330 .filter_map(|arg| arg.ty(Interner).cloned())
3331 .map(move |ty| self.derived(ty))
3334 pub fn iterate_method_candidates<T>(
3336 db: &dyn HirDatabase,
3337 scope: &SemanticsScope<'_>,
3338 // FIXME this can be retrieved from `scope`, except autoimport uses this
3339 // to specify a different set, so the method needs to be split
3340 traits_in_scope: &FxHashSet<TraitId>,
3341 with_local_impls: Option<Module>,
3342 name: Option<&Name>,
3343 mut callback: impl FnMut(Function) -> Option<T>,
3345 let _p = profile::span("iterate_method_candidates");
3346 let mut slot = None;
3348 self.iterate_method_candidates_dyn(
3354 &mut |assoc_item_id| {
3355 if let AssocItemId::FunctionId(func) = assoc_item_id {
3356 if let Some(res) = callback(func.into()) {
3358 return ControlFlow::Break(());
3361 ControlFlow::Continue(())
3367 fn iterate_method_candidates_dyn(
3369 db: &dyn HirDatabase,
3370 scope: &SemanticsScope<'_>,
3371 traits_in_scope: &FxHashSet<TraitId>,
3372 with_local_impls: Option<Module>,
3373 name: Option<&Name>,
3374 callback: &mut dyn FnMut(AssocItemId) -> ControlFlow<()>,
3376 // There should be no inference vars in types passed here
3377 let canonical = hir_ty::replace_errors_with_variables(&self.ty);
3379 let krate = scope.krate();
3380 let environment = scope.resolver().generic_def().map_or_else(
3381 || Arc::new(TraitEnvironment::empty(krate.id)),
3382 |d| db.trait_environment(d),
3385 method_resolution::iterate_method_candidates_dyn(
3390 with_local_impls.and_then(|b| b.id.containing_block()).into(),
3392 method_resolution::LookupMode::MethodCall,
3393 &mut |_adj, id, _| callback(id),
3397 pub fn iterate_path_candidates<T>(
3399 db: &dyn HirDatabase,
3400 scope: &SemanticsScope<'_>,
3401 traits_in_scope: &FxHashSet<TraitId>,
3402 with_local_impls: Option<Module>,
3403 name: Option<&Name>,
3404 mut callback: impl FnMut(AssocItem) -> Option<T>,
3406 let _p = profile::span("iterate_path_candidates");
3407 let mut slot = None;
3408 self.iterate_path_candidates_dyn(
3414 &mut |assoc_item_id| {
3415 if let Some(res) = callback(assoc_item_id.into()) {
3417 return ControlFlow::Break(());
3419 ControlFlow::Continue(())
3425 fn iterate_path_candidates_dyn(
3427 db: &dyn HirDatabase,
3428 scope: &SemanticsScope<'_>,
3429 traits_in_scope: &FxHashSet<TraitId>,
3430 with_local_impls: Option<Module>,
3431 name: Option<&Name>,
3432 callback: &mut dyn FnMut(AssocItemId) -> ControlFlow<()>,
3434 let canonical = hir_ty::replace_errors_with_variables(&self.ty);
3436 let krate = scope.krate();
3437 let environment = scope.resolver().generic_def().map_or_else(
3438 || Arc::new(TraitEnvironment::empty(krate.id)),
3439 |d| db.trait_environment(d),
3442 method_resolution::iterate_path_candidates(
3447 with_local_impls.and_then(|b| b.id.containing_block()).into(),
3449 &mut |id| callback(id),
3453 pub fn as_adt(&self) -> Option<Adt> {
3454 let (adt, _subst) = self.ty.as_adt()?;
3458 pub fn as_builtin(&self) -> Option<BuiltinType> {
3459 self.ty.as_builtin().map(|inner| BuiltinType { inner })
3462 pub fn as_dyn_trait(&self) -> Option<Trait> {
3463 self.ty.dyn_trait().map(Into::into)
3466 /// If a type can be represented as `dyn Trait`, returns all traits accessible via this type,
3467 /// or an empty iterator otherwise.
3468 pub fn applicable_inherent_traits<'a>(
3470 db: &'a dyn HirDatabase,
3471 ) -> impl Iterator<Item = Trait> + 'a {
3472 let _p = profile::span("applicable_inherent_traits");
3474 .filter_map(|ty| ty.dyn_trait())
3475 .flat_map(move |dyn_trait_id| hir_ty::all_super_traits(db.upcast(), dyn_trait_id))
3479 pub fn env_traits<'a>(&'a self, db: &'a dyn HirDatabase) -> impl Iterator<Item = Trait> + 'a {
3480 let _p = profile::span("env_traits");
3482 .filter(|ty| matches!(ty.kind(Interner), TyKind::Placeholder(_)))
3485 .traits_in_scope_from_clauses(ty)
3486 .flat_map(|t| hir_ty::all_super_traits(db.upcast(), t))
3491 pub fn as_impl_traits(&self, db: &dyn HirDatabase) -> Option<impl Iterator<Item = Trait>> {
3492 self.ty.impl_trait_bounds(db).map(|it| {
3493 it.into_iter().filter_map(|pred| match pred.skip_binders() {
3494 hir_ty::WhereClause::Implemented(trait_ref) => {
3495 Some(Trait::from(trait_ref.hir_trait_id()))
3502 pub fn as_associated_type_parent_trait(&self, db: &dyn HirDatabase) -> Option<Trait> {
3503 self.ty.associated_type_parent_trait(db).map(Into::into)
3506 fn derived(&self, ty: Ty) -> Type {
3507 Type { env: self.env.clone(), ty }
3510 /// Visits every type, including generic arguments, in this type. `cb` is called with type
3511 /// itself first, and then with its generic arguments.
3512 pub fn walk(&self, db: &dyn HirDatabase, mut cb: impl FnMut(Type)) {
3514 db: &dyn HirDatabase,
3516 substs: &Substitution,
3517 cb: &mut impl FnMut(Type),
3519 for ty in substs.iter(Interner).filter_map(|a| a.ty(Interner)) {
3520 walk_type(db, &type_.derived(ty.clone()), cb);
3525 db: &dyn HirDatabase,
3527 bounds: &[QuantifiedWhereClause],
3528 cb: &mut impl FnMut(Type),
3530 for pred in bounds {
3531 if let WhereClause::Implemented(trait_ref) = pred.skip_binders() {
3533 // skip the self type. it's likely the type we just got the bounds from
3535 trait_ref.substitution.iter(Interner).skip(1).filter_map(|a| a.ty(Interner))
3537 walk_type(db, &type_.derived(ty.clone()), cb);
3543 fn walk_type(db: &dyn HirDatabase, type_: &Type, cb: &mut impl FnMut(Type)) {
3544 let ty = type_.ty.strip_references();
3545 match ty.kind(Interner) {
3546 TyKind::Adt(_, substs) => {
3547 cb(type_.derived(ty.clone()));
3548 walk_substs(db, type_, substs, cb);
3550 TyKind::AssociatedType(_, substs) => {
3551 if ty.associated_type_parent_trait(db).is_some() {
3552 cb(type_.derived(ty.clone()));
3554 walk_substs(db, type_, substs, cb);
3556 TyKind::OpaqueType(_, subst) => {
3557 if let Some(bounds) = ty.impl_trait_bounds(db) {
3558 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
3561 walk_substs(db, type_, subst, cb);
3563 TyKind::Alias(AliasTy::Opaque(opaque_ty)) => {
3564 if let Some(bounds) = ty.impl_trait_bounds(db) {
3565 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
3568 walk_substs(db, type_, &opaque_ty.substitution, cb);
3570 TyKind::Placeholder(_) => {
3571 if let Some(bounds) = ty.impl_trait_bounds(db) {
3572 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
3575 TyKind::Dyn(bounds) => {
3578 &type_.derived(ty.clone()),
3579 bounds.bounds.skip_binders().interned(),
3584 TyKind::Ref(_, _, ty)
3585 | TyKind::Raw(_, ty)
3586 | TyKind::Array(ty, _)
3587 | TyKind::Slice(ty) => {
3588 walk_type(db, &type_.derived(ty.clone()), cb);
3591 TyKind::FnDef(_, substs)
3592 | TyKind::Tuple(_, substs)
3593 | TyKind::Closure(.., substs) => {
3594 walk_substs(db, type_, substs, cb);
3596 TyKind::Function(hir_ty::FnPointer { substitution, .. }) => {
3597 walk_substs(db, type_, &substitution.0, cb);
3604 walk_type(db, self, &mut cb);
3607 pub fn could_unify_with(&self, db: &dyn HirDatabase, other: &Type) -> bool {
3608 let tys = hir_ty::replace_errors_with_variables(&(self.ty.clone(), other.ty.clone()));
3609 hir_ty::could_unify(db, self.env.clone(), &tys)
3612 pub fn could_coerce_to(&self, db: &dyn HirDatabase, to: &Type) -> bool {
3613 let tys = hir_ty::replace_errors_with_variables(&(self.ty.clone(), to.ty.clone()));
3614 hir_ty::could_coerce(db, self.env.clone(), &tys)
3617 pub fn as_type_param(&self, db: &dyn HirDatabase) -> Option<TypeParam> {
3618 match self.ty.kind(Interner) {
3619 TyKind::Placeholder(p) => Some(TypeParam {
3620 id: TypeParamId::from_unchecked(hir_ty::from_placeholder_idx(db, *p)),
3626 /// Returns unique `GenericParam`s contained in this type.
3627 pub fn generic_params(&self, db: &dyn HirDatabase) -> FxHashSet<GenericParam> {
3628 hir_ty::collect_placeholders(&self.ty, db)
3630 .map(|id| TypeOrConstParam { id }.split(db).either_into())
3636 pub struct Callable {
3640 pub(crate) is_bound_method: bool,
3651 pub enum CallableKind {
3653 TupleStruct(Struct),
3654 TupleEnumVariant(Variant),
3657 /// Some other type that implements `FnOnce`.
3662 pub fn kind(&self) -> CallableKind {
3665 Def(CallableDefId::FunctionId(it)) => CallableKind::Function(it.into()),
3666 Def(CallableDefId::StructId(it)) => CallableKind::TupleStruct(it.into()),
3667 Def(CallableDefId::EnumVariantId(it)) => CallableKind::TupleEnumVariant(it.into()),
3668 Closure(_) => CallableKind::Closure,
3669 FnPtr => CallableKind::FnPtr,
3670 Other => CallableKind::Other,
3673 pub fn receiver_param(&self, db: &dyn HirDatabase) -> Option<ast::SelfParam> {
3674 let func = match self.callee {
3675 Callee::Def(CallableDefId::FunctionId(it)) if self.is_bound_method => it,
3678 let src = func.lookup(db.upcast()).source(db.upcast());
3679 let param_list = src.value.param_list()?;
3680 param_list.self_param()
3682 pub fn n_params(&self) -> usize {
3683 self.sig.params().len() - if self.is_bound_method { 1 } else { 0 }
3687 db: &dyn HirDatabase,
3688 ) -> Vec<(Option<Either<ast::SelfParam, ast::Pat>>, Type)> {
3693 .skip(if self.is_bound_method { 1 } else { 0 })
3694 .map(|ty| self.ty.derived(ty.clone()));
3695 let map_param = |it: ast::Param| it.pat().map(Either::Right);
3696 let patterns = match self.callee {
3697 Callee::Def(CallableDefId::FunctionId(func)) => {
3698 let src = func.lookup(db.upcast()).source(db.upcast());
3699 src.value.param_list().map(|param_list| {
3702 .map(|it| Some(Either::Left(it)))
3703 .filter(|_| !self.is_bound_method)
3705 .chain(param_list.params().map(map_param))
3708 Callee::Closure(closure_id) => match closure_source(db, closure_id) {
3709 Some(src) => src.param_list().map(|param_list| {
3712 .map(|it| Some(Either::Left(it)))
3713 .filter(|_| !self.is_bound_method)
3715 .chain(param_list.params().map(map_param))
3721 patterns.into_iter().flatten().chain(iter::repeat(None)).zip(types).collect()
3723 pub fn return_type(&self) -> Type {
3724 self.ty.derived(self.sig.ret().clone())
3728 fn closure_source(db: &dyn HirDatabase, closure: ClosureId) -> Option<ast::ClosureExpr> {
3729 let (owner, expr_id) = db.lookup_intern_closure(closure.into());
3730 let (_, source_map) = db.body_with_source_map(owner);
3731 let ast = source_map.expr_syntax(expr_id).ok()?;
3732 let root = ast.file_syntax(db.upcast());
3733 let expr = ast.value.to_node(&root);
3735 ast::Expr::ClosureExpr(it) => Some(it),
3740 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
3741 pub enum BindingMode {
3747 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
3749 ModuleDef(ModuleDef),
3750 GenericParam(GenericParam),
3759 pub fn all_items(def: PerNs) -> ArrayVec<Self, 3> {
3760 let mut items = ArrayVec::new();
3762 match (def.take_types(), def.take_values()) {
3763 (Some(m1), None) => items.push(ScopeDef::ModuleDef(m1.into())),
3764 (None, Some(m2)) => items.push(ScopeDef::ModuleDef(m2.into())),
3765 (Some(m1), Some(m2)) => {
3766 // Some items, like unit structs and enum variants, are
3767 // returned as both a type and a value. Here we want
3768 // to de-duplicate them.
3770 items.push(ScopeDef::ModuleDef(m1.into()));
3771 items.push(ScopeDef::ModuleDef(m2.into()));
3773 items.push(ScopeDef::ModuleDef(m1.into()));
3779 if let Some(macro_def_id) = def.take_macros() {
3780 items.push(ScopeDef::ModuleDef(ModuleDef::Macro(macro_def_id.into())));
3783 if items.is_empty() {
3784 items.push(ScopeDef::Unknown);
3790 pub fn attrs(&self, db: &dyn HirDatabase) -> Option<AttrsWithOwner> {
3792 ScopeDef::ModuleDef(it) => it.attrs(db),
3793 ScopeDef::GenericParam(it) => Some(it.attrs(db)),
3794 ScopeDef::ImplSelfType(_)
3795 | ScopeDef::AdtSelfType(_)
3796 | ScopeDef::Local(_)
3797 | ScopeDef::Label(_)
3798 | ScopeDef::Unknown => None,
3802 pub fn krate(&self, db: &dyn HirDatabase) -> Option<Crate> {
3804 ScopeDef::ModuleDef(it) => it.module(db).map(|m| m.krate()),
3805 ScopeDef::GenericParam(it) => Some(it.module(db).krate()),
3806 ScopeDef::ImplSelfType(_) => None,
3807 ScopeDef::AdtSelfType(it) => Some(it.module(db).krate()),
3808 ScopeDef::Local(it) => Some(it.module(db).krate()),
3809 ScopeDef::Label(it) => Some(it.module(db).krate()),
3810 ScopeDef::Unknown => None,
3815 impl From<ItemInNs> for ScopeDef {
3816 fn from(item: ItemInNs) -> Self {
3818 ItemInNs::Types(id) => ScopeDef::ModuleDef(id),
3819 ItemInNs::Values(id) => ScopeDef::ModuleDef(id),
3820 ItemInNs::Macros(id) => ScopeDef::ModuleDef(ModuleDef::Macro(id)),
3825 #[derive(Clone, Debug, PartialEq, Eq)]
3826 pub struct Adjustment {
3832 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
3834 /// Go from ! to any type.
3836 /// Dereference once, producing a place.
3837 Deref(Option<OverloadedDeref>),
3838 /// Take the address and produce either a `&` or `*` pointer.
3840 Pointer(PointerCast),
3843 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
3844 pub enum AutoBorrow {
3845 /// Converts from T to &T.
3847 /// Converts from T to *T.
3851 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
3852 pub struct OverloadedDeref(pub Mutability);
3854 pub trait HasVisibility {
3855 fn visibility(&self, db: &dyn HirDatabase) -> Visibility;
3856 fn is_visible_from(&self, db: &dyn HirDatabase, module: Module) -> bool {
3857 let vis = self.visibility(db);
3858 vis.is_visible_from(db.upcast(), module.id)
3862 /// Trait for obtaining the defining crate of an item.
3863 pub trait HasCrate {
3864 fn krate(&self, db: &dyn HirDatabase) -> Crate;
3867 impl<T: hir_def::HasModule> HasCrate for T {
3868 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3869 self.module(db.upcast()).krate().into()
3873 impl HasCrate for AssocItem {
3874 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3875 self.module(db).krate()
3879 impl HasCrate for Struct {
3880 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3881 self.module(db).krate()
3885 impl HasCrate for Union {
3886 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3887 self.module(db).krate()
3891 impl HasCrate for Field {
3892 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3893 self.parent_def(db).module(db).krate()
3897 impl HasCrate for Variant {
3898 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3899 self.module(db).krate()
3903 impl HasCrate for Function {
3904 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3905 self.module(db).krate()
3909 impl HasCrate for Const {
3910 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3911 self.module(db).krate()
3915 impl HasCrate for TypeAlias {
3916 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3917 self.module(db).krate()
3921 impl HasCrate for Type {
3922 fn krate(&self, _db: &dyn HirDatabase) -> Crate {
3923 self.env.krate.into()
3927 impl HasCrate for Macro {
3928 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3929 self.module(db).krate()
3933 impl HasCrate for Trait {
3934 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3935 self.module(db).krate()
3939 impl HasCrate for Static {
3940 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3941 self.module(db).krate()
3945 impl HasCrate for Adt {
3946 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3947 self.module(db).krate()
3951 impl HasCrate for Module {
3952 fn krate(&self, _: &dyn HirDatabase) -> Crate {
3953 Module::krate(*self)