1 //! HIR (previously known as descriptors) provides a high-level object oriented
2 //! access to Rust code.
4 //! The principal difference between HIR and syntax trees is that HIR is bound
5 //! to a particular crate instance. That is, it has cfg flags and features
6 //! applied. So, the relation between syntax and HIR is many-to-one.
8 //! HIR is the public API of the all of the compiler logic above syntax trees.
9 //! It is written in "OO" style. Each type is self contained (as in, it knows it's
10 //! parents and full context). It should be "clean code".
12 //! `hir_*` crates are the implementation of the compiler logic.
13 //! They are written in "ECS" style, with relatively little abstractions.
14 //! Many types are not self-contained, and explicitly use local indexes, arenas, etc.
16 //! `hir` is what insulates the "we don't know how to actually write an incremental compiler"
17 //! from the ide with completions, hovers, etc. It is a (soft, internal) boundary:
18 //! <https://www.tedinski.com/2018/02/06/system-boundaries.html>.
20 #![recursion_limit = "512"]
34 use std::{iter, ops::ControlFlow, sync::Arc};
36 use arrayvec::ArrayVec;
37 use base_db::{CrateDisplayName, CrateId, Edition, FileId};
40 adt::{ReprKind, VariantData},
41 body::{BodyDiagnostic, SyntheticSyntax},
42 expr::{BindingAnnotation, LabelId, Pat, PatId},
43 lang_item::LangItemTarget,
46 resolver::{HasResolver, Resolver},
47 AttrDefId, ConstId, ConstParamId, EnumId, FunctionId, GenericDefId, HasModule, LifetimeParamId,
48 LocalEnumVariantId, LocalFieldId, StaticId, StructId, TypeAliasId, TypeParamId, UnionId,
50 use hir_expand::{name::name, MacroCallKind, MacroDefKind};
55 diagnostics::BodyValidationDiagnostic,
56 method_resolution::{self, TyFingerprint},
60 AliasEq, AliasTy, BoundVar, CallableDefId, CallableSig, Canonical, CanonicalVarKinds, Cast,
61 DebruijnIndex, InEnvironment, Interner, QuantifiedWhereClause, Scalar, Solution, Substitution,
62 TraitEnvironment, TraitRefExt, Ty, TyBuilder, TyDefId, TyExt, TyKind, TyVariableKind,
65 use itertools::Itertools;
66 use nameres::diagnostics::DefDiagnosticKind;
67 use once_cell::unsync::Lazy;
68 use rustc_hash::FxHashSet;
69 use stdx::{format_to, impl_from};
71 ast::{self, HasAttrs as _, HasName},
72 AstNode, AstPtr, SmolStr, SyntaxKind, SyntaxNodePtr,
74 use tt::{Ident, Leaf, Literal, TokenTree};
76 use crate::db::{DefDatabase, HirDatabase};
79 attrs::{HasAttrs, Namespace},
81 AddReferenceHere, AnyDiagnostic, BreakOutsideOfLoop, InactiveCode, IncorrectCase,
82 InvalidDeriveTarget, MacroError, MalformedDerive, MismatchedArgCount, MissingFields,
83 MissingMatchArms, MissingOkOrSomeInTailExpr, MissingUnsafe, NoSuchField,
84 RemoveThisSemicolon, ReplaceFilterMapNextWithFindMap, UnimplementedBuiltinMacro,
85 UnresolvedExternCrate, UnresolvedImport, UnresolvedMacroCall, UnresolvedModule,
88 has_source::HasSource,
89 semantics::{PathResolution, Semantics, SemanticsScope, TypeInfo},
92 // Be careful with these re-exports.
94 // `hir` is the boundary between the compiler and the IDE. It should try hard to
95 // isolate the compiler from the ide, to allow the two to be refactored
96 // independently. Re-exporting something from the compiler is the sure way to
97 // breach the boundary.
99 // Generally, a refactoring which *removes* a name from this list is a good
102 cfg::{CfgAtom, CfgExpr, CfgOptions},
105 attr::{Attr, Attrs, AttrsWithOwner, Documentation},
107 find_path::PrefixKind,
109 item_scope::ItemScope,
110 item_tree::ItemTreeNode,
111 nameres::{DefMap, ModuleData, ModuleOrigin, ModuleSource},
112 path::{ModPath, PathKind},
113 src::HasSource as DefHasSource, // xx: I don't like this shadowing of HasSource... :(
114 type_ref::{Mutability, TypeRef},
115 visibility::Visibility,
130 ExpandResult, HirFileId, InFile, MacroDefId, MacroFile, Origin,
132 hir_ty::display::HirDisplay,
135 // These are negative re-exports: pub using these names is forbidden, they
136 // should remain private to hir internals.
140 hir_expand::{hygiene::Hygiene, name::AsName},
143 /// hir::Crate describes a single crate. It's the main interface with which
144 /// a crate's dependencies interact. Mostly, it should be just a proxy for the
146 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
148 pub(crate) id: CrateId,
152 pub struct CrateDependency {
158 pub fn dependencies(self, db: &dyn HirDatabase) -> Vec<CrateDependency> {
159 db.crate_graph()[self.id]
163 let krate = Crate { id: dep.crate_id };
164 let name = dep.as_name();
165 CrateDependency { krate, name }
170 pub fn reverse_dependencies(self, db: &dyn HirDatabase) -> Vec<Crate> {
171 let crate_graph = db.crate_graph();
175 crate_graph[krate].dependencies.iter().any(|it| it.crate_id == self.id)
177 .map(|id| Crate { id })
181 pub fn transitive_reverse_dependencies(self, db: &dyn HirDatabase) -> Vec<Crate> {
182 db.crate_graph().transitive_rev_deps(self.id).into_iter().map(|id| Crate { id }).collect()
185 pub fn root_module(self, db: &dyn HirDatabase) -> Module {
186 let def_map = db.crate_def_map(self.id);
187 Module { id: def_map.module_id(def_map.root()) }
190 pub fn root_file(self, db: &dyn HirDatabase) -> FileId {
191 db.crate_graph()[self.id].root_file_id
194 pub fn edition(self, db: &dyn HirDatabase) -> Edition {
195 db.crate_graph()[self.id].edition
198 pub fn version(self, db: &dyn HirDatabase) -> Option<String> {
199 db.crate_graph()[self.id].version.clone()
202 pub fn display_name(self, db: &dyn HirDatabase) -> Option<CrateDisplayName> {
203 db.crate_graph()[self.id].display_name.clone()
206 pub fn query_external_importables(
208 db: &dyn DefDatabase,
209 query: import_map::Query,
210 ) -> impl Iterator<Item = Either<ModuleDef, MacroDef>> {
211 let _p = profile::span("query_external_importables");
212 import_map::search_dependencies(db, self.into(), query).into_iter().map(|item| {
213 match ItemInNs::from(item) {
214 ItemInNs::Types(mod_id) | ItemInNs::Values(mod_id) => Either::Left(mod_id),
215 ItemInNs::Macros(mac_id) => Either::Right(mac_id),
220 pub fn all(db: &dyn HirDatabase) -> Vec<Crate> {
221 db.crate_graph().iter().map(|id| Crate { id }).collect()
224 /// Try to get the root URL of the documentation of a crate.
225 pub fn get_html_root_url(self: &Crate, db: &dyn HirDatabase) -> Option<String> {
226 // Look for #![doc(html_root_url = "...")]
227 let attrs = db.attrs(AttrDefId::ModuleId(self.root_module(db).into()));
228 let doc_attr_q = attrs.by_key("doc");
230 if !doc_attr_q.exists() {
234 let doc_url = doc_attr_q.tt_values().map(|tt| {
235 let name = tt.token_trees.iter()
236 .skip_while(|tt| !matches!(tt, TokenTree::Leaf(Leaf::Ident(Ident { text, ..} )) if text == "html_root_url"))
240 Some(TokenTree::Leaf(Leaf::Literal(Literal{ref text, ..}))) => Some(text),
245 doc_url.map(|s| s.trim_matches('"').trim_end_matches('/').to_owned() + "/")
248 pub fn cfg(&self, db: &dyn HirDatabase) -> CfgOptions {
249 db.crate_graph()[self.id].cfg_options.clone()
252 pub fn potential_cfg(&self, db: &dyn HirDatabase) -> CfgOptions {
253 db.crate_graph()[self.id].potential_cfg_options.clone()
257 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
259 pub(crate) id: ModuleId,
262 /// The defs which can be visible in the module.
263 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
268 // Can't be directly declared, but can be imported.
273 TypeAlias(TypeAlias),
274 BuiltinType(BuiltinType),
279 Adt(Struct, Enum, Union),
289 impl From<VariantDef> for ModuleDef {
290 fn from(var: VariantDef) -> Self {
292 VariantDef::Struct(t) => Adt::from(t).into(),
293 VariantDef::Union(t) => Adt::from(t).into(),
294 VariantDef::Variant(t) => t.into(),
300 pub fn module(self, db: &dyn HirDatabase) -> Option<Module> {
302 ModuleDef::Module(it) => it.parent(db),
303 ModuleDef::Function(it) => Some(it.module(db)),
304 ModuleDef::Adt(it) => Some(it.module(db)),
305 ModuleDef::Variant(it) => Some(it.module(db)),
306 ModuleDef::Const(it) => Some(it.module(db)),
307 ModuleDef::Static(it) => Some(it.module(db)),
308 ModuleDef::Trait(it) => Some(it.module(db)),
309 ModuleDef::TypeAlias(it) => Some(it.module(db)),
310 ModuleDef::BuiltinType(_) => None,
314 pub fn canonical_path(&self, db: &dyn HirDatabase) -> Option<String> {
315 let mut segments = vec![self.name(db)?];
316 for m in self.module(db)?.path_to_root(db) {
317 segments.extend(m.name(db))
320 Some(segments.into_iter().join("::"))
323 pub fn canonical_module_path(
325 db: &dyn HirDatabase,
326 ) -> Option<impl Iterator<Item = Module>> {
327 self.module(db).map(|it| it.path_to_root(db).into_iter().rev())
330 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
331 let name = match self {
332 ModuleDef::Module(it) => it.name(db)?,
333 ModuleDef::Const(it) => it.name(db)?,
334 ModuleDef::Adt(it) => it.name(db),
335 ModuleDef::Trait(it) => it.name(db),
336 ModuleDef::Function(it) => it.name(db),
337 ModuleDef::Variant(it) => it.name(db),
338 ModuleDef::TypeAlias(it) => it.name(db),
339 ModuleDef::Static(it) => it.name(db),
340 ModuleDef::BuiltinType(it) => it.name(),
345 pub fn diagnostics(self, db: &dyn HirDatabase) -> Vec<AnyDiagnostic> {
346 let id = match self {
347 ModuleDef::Adt(it) => match it {
348 Adt::Struct(it) => it.id.into(),
349 Adt::Enum(it) => it.id.into(),
350 Adt::Union(it) => it.id.into(),
352 ModuleDef::Trait(it) => it.id.into(),
353 ModuleDef::Function(it) => it.id.into(),
354 ModuleDef::TypeAlias(it) => it.id.into(),
355 ModuleDef::Module(it) => it.id.into(),
356 ModuleDef::Const(it) => it.id.into(),
357 ModuleDef::Static(it) => it.id.into(),
358 _ => return Vec::new(),
361 let module = match self.module(db) {
363 None => return Vec::new(),
366 let mut acc = Vec::new();
368 match self.as_def_with_body() {
370 def.diagnostics(db, &mut acc);
373 for diag in hir_ty::diagnostics::incorrect_case(db, module.id.krate(), id) {
374 acc.push(diag.into())
382 pub fn as_def_with_body(self) -> Option<DefWithBody> {
384 ModuleDef::Function(it) => Some(it.into()),
385 ModuleDef::Const(it) => Some(it.into()),
386 ModuleDef::Static(it) => Some(it.into()),
390 | ModuleDef::Variant(_)
391 | ModuleDef::Trait(_)
392 | ModuleDef::TypeAlias(_)
393 | ModuleDef::BuiltinType(_) => None,
397 pub fn attrs(&self, db: &dyn HirDatabase) -> Option<AttrsWithOwner> {
399 ModuleDef::Module(it) => it.attrs(db),
400 ModuleDef::Function(it) => it.attrs(db),
401 ModuleDef::Adt(it) => it.attrs(db),
402 ModuleDef::Variant(it) => it.attrs(db),
403 ModuleDef::Const(it) => it.attrs(db),
404 ModuleDef::Static(it) => it.attrs(db),
405 ModuleDef::Trait(it) => it.attrs(db),
406 ModuleDef::TypeAlias(it) => it.attrs(db),
407 ModuleDef::BuiltinType(_) => return None,
412 impl HasVisibility for ModuleDef {
413 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
415 ModuleDef::Module(it) => it.visibility(db),
416 ModuleDef::Function(it) => it.visibility(db),
417 ModuleDef::Adt(it) => it.visibility(db),
418 ModuleDef::Const(it) => it.visibility(db),
419 ModuleDef::Static(it) => it.visibility(db),
420 ModuleDef::Trait(it) => it.visibility(db),
421 ModuleDef::TypeAlias(it) => it.visibility(db),
422 ModuleDef::Variant(it) => it.visibility(db),
423 ModuleDef::BuiltinType(_) => Visibility::Public,
429 /// Name of this module.
430 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
431 let def_map = self.id.def_map(db.upcast());
432 let parent = def_map[self.id.local_id].parent?;
433 def_map[parent].children.iter().find_map(|(name, module_id)| {
434 if *module_id == self.id.local_id {
442 /// Returns the crate this module is part of.
443 pub fn krate(self) -> Crate {
444 Crate { id: self.id.krate() }
447 /// Topmost parent of this module. Every module has a `crate_root`, but some
448 /// might be missing `krate`. This can happen if a module's file is not included
449 /// in the module tree of any target in `Cargo.toml`.
450 pub fn crate_root(self, db: &dyn HirDatabase) -> Module {
451 let def_map = db.crate_def_map(self.id.krate());
452 Module { id: def_map.module_id(def_map.root()) }
455 /// Iterates over all child modules.
456 pub fn children(self, db: &dyn HirDatabase) -> impl Iterator<Item = Module> {
457 let def_map = self.id.def_map(db.upcast());
458 let children = def_map[self.id.local_id]
461 .map(|(_, module_id)| Module { id: def_map.module_id(*module_id) })
462 .collect::<Vec<_>>();
466 /// Finds a parent module.
467 pub fn parent(self, db: &dyn HirDatabase) -> Option<Module> {
468 // FIXME: handle block expressions as modules (their parent is in a different DefMap)
469 let def_map = self.id.def_map(db.upcast());
470 let parent_id = def_map[self.id.local_id].parent?;
471 Some(Module { id: def_map.module_id(parent_id) })
474 pub fn path_to_root(self, db: &dyn HirDatabase) -> Vec<Module> {
475 let mut res = vec![self];
477 while let Some(next) = curr.parent(db) {
484 /// Returns a `ModuleScope`: a set of items, visible in this module.
487 db: &dyn HirDatabase,
488 visible_from: Option<Module>,
489 ) -> Vec<(Name, ScopeDef)> {
490 self.id.def_map(db.upcast())[self.id.local_id]
493 .filter_map(|(name, def)| {
494 if let Some(m) = visible_from {
496 def.filter_visibility(|vis| vis.is_visible_from(db.upcast(), m.id));
497 if filtered.is_none() && !def.is_none() {
500 Some((name, filtered))
506 .flat_map(|(name, def)| {
507 ScopeDef::all_items(def).into_iter().map(move |item| (name.clone(), item))
512 pub fn diagnostics(self, db: &dyn HirDatabase, acc: &mut Vec<AnyDiagnostic>) {
513 let _p = profile::span("Module::diagnostics").detail(|| {
514 format!("{:?}", self.name(db).map_or("<unknown>".into(), |name| name.to_string()))
516 let def_map = self.id.def_map(db.upcast());
517 for diag in def_map.diagnostics() {
518 if diag.in_module != self.id.local_id {
519 // FIXME: This is accidentally quadratic.
523 DefDiagnosticKind::UnresolvedModule { ast: declaration, candidate } => {
524 let decl = declaration.to_node(db.upcast());
527 decl: InFile::new(declaration.file_id, AstPtr::new(&decl)),
528 candidate: candidate.clone(),
533 DefDiagnosticKind::UnresolvedExternCrate { ast } => {
534 let item = ast.to_node(db.upcast());
536 UnresolvedExternCrate {
537 decl: InFile::new(ast.file_id, AstPtr::new(&item)),
543 DefDiagnosticKind::UnresolvedImport { id, index } => {
544 let file_id = id.file_id();
545 let item_tree = id.item_tree(db.upcast());
546 let import = &item_tree[id.value];
548 let use_tree = import.use_tree_to_ast(db.upcast(), file_id, *index);
550 UnresolvedImport { decl: InFile::new(file_id, AstPtr::new(&use_tree)) }
555 DefDiagnosticKind::UnconfiguredCode { ast, cfg, opts } => {
556 let item = ast.to_node(db.upcast());
559 node: ast.with_value(AstPtr::new(&item).into()),
567 DefDiagnosticKind::UnresolvedProcMacro { ast } => {
568 let mut precise_location = None;
569 let (node, name) = match ast {
570 MacroCallKind::FnLike { ast_id, .. } => {
571 let node = ast_id.to_node(db.upcast());
572 (ast_id.with_value(SyntaxNodePtr::from(AstPtr::new(&node))), None)
574 MacroCallKind::Derive { ast_id, derive_name, .. } => {
575 let node = ast_id.to_node(db.upcast());
577 // Compute the precise location of the macro name's token in the derive
579 // FIXME: This does not handle paths to the macro, but neither does the
582 node.attrs().filter_map(|attr| match attr.as_simple_call() {
583 Some((name, args)) if name == "derive" => Some(args),
586 'outer: for attr in derive_attrs {
588 attr.syntax().children_with_tokens().filter_map(|elem| {
590 syntax::NodeOrToken::Node(_) => None,
591 syntax::NodeOrToken::Token(tok) => Some(tok),
594 for token in tokens {
595 if token.kind() == SyntaxKind::IDENT
596 && token.text() == &**derive_name
598 precise_location = Some(token.text_range());
605 ast_id.with_value(SyntaxNodePtr::from(AstPtr::new(&node))),
606 Some(derive_name.clone()),
609 MacroCallKind::Attr { ast_id, invoc_attr_index, attr_name, .. } => {
610 let node = ast_id.to_node(db.upcast());
612 node.attrs().nth((*invoc_attr_index) as usize).unwrap_or_else(
613 || panic!("cannot find attribute #{}", invoc_attr_index),
616 ast_id.with_value(SyntaxNodePtr::from(AstPtr::new(&attr))),
617 Some(attr_name.clone()),
622 UnresolvedProcMacro {
625 macro_name: name.map(Into::into),
631 DefDiagnosticKind::UnresolvedMacroCall { ast, path } => {
632 let node = ast.to_node(db.upcast());
634 UnresolvedMacroCall {
635 macro_call: InFile::new(ast.file_id, AstPtr::new(&node)),
642 DefDiagnosticKind::MacroError { ast, message } => {
643 let node = match ast {
644 MacroCallKind::FnLike { ast_id, .. } => {
645 let node = ast_id.to_node(db.upcast());
646 ast_id.with_value(SyntaxNodePtr::from(AstPtr::new(&node)))
648 MacroCallKind::Derive { ast_id, .. }
649 | MacroCallKind::Attr { ast_id, .. } => {
650 // FIXME: point to the attribute instead, this creates very large diagnostics
651 let node = ast_id.to_node(db.upcast());
652 ast_id.with_value(SyntaxNodePtr::from(AstPtr::new(&node)))
655 acc.push(MacroError { node, message: message.clone() }.into());
658 DefDiagnosticKind::UnimplementedBuiltinMacro { ast } => {
659 let node = ast.to_node(db.upcast());
660 // Must have a name, otherwise we wouldn't emit it.
661 let name = node.name().expect("unimplemented builtin macro with no name");
663 UnimplementedBuiltinMacro {
664 node: ast.with_value(SyntaxNodePtr::from(AstPtr::new(&name))),
669 DefDiagnosticKind::InvalidDeriveTarget { ast, id } => {
670 let node = ast.to_node(db.upcast());
671 let derive = node.attrs().nth(*id as usize);
675 InvalidDeriveTarget {
676 node: ast.with_value(SyntaxNodePtr::from(AstPtr::new(&derive))),
681 None => stdx::never!("derive diagnostic on item without derive attribute"),
684 DefDiagnosticKind::MalformedDerive { ast, id } => {
685 let node = ast.to_node(db.upcast());
686 let derive = node.attrs().nth(*id as usize);
691 node: ast.with_value(SyntaxNodePtr::from(AstPtr::new(&derive))),
696 None => stdx::never!("derive diagnostic on item without derive attribute"),
701 for decl in self.declarations(db) {
703 ModuleDef::Module(m) => {
704 // Only add diagnostics from inline modules
705 if def_map[m.id.local_id].origin.is_inline() {
706 m.diagnostics(db, acc)
709 _ => acc.extend(decl.diagnostics(db)),
713 for impl_def in self.impl_defs(db) {
714 for item in impl_def.items(db) {
715 let def: DefWithBody = match item {
716 AssocItem::Function(it) => it.into(),
717 AssocItem::Const(it) => it.into(),
718 AssocItem::TypeAlias(_) => continue,
721 def.diagnostics(db, acc);
726 pub fn declarations(self, db: &dyn HirDatabase) -> Vec<ModuleDef> {
727 let def_map = self.id.def_map(db.upcast());
728 let scope = &def_map[self.id.local_id].scope;
731 .map(ModuleDef::from)
732 .chain(scope.unnamed_consts().map(|id| ModuleDef::Const(Const::from(id))))
736 pub fn impl_defs(self, db: &dyn HirDatabase) -> Vec<Impl> {
737 let def_map = self.id.def_map(db.upcast());
738 def_map[self.id.local_id].scope.impls().map(Impl::from).collect()
741 /// Finds a path that can be used to refer to the given item from within
742 /// this module, if possible.
743 pub fn find_use_path(self, db: &dyn DefDatabase, item: impl Into<ItemInNs>) -> Option<ModPath> {
744 hir_def::find_path::find_path(db, item.into().into(), self.into())
747 /// Finds a path that can be used to refer to the given item from within
748 /// this module, if possible. This is used for returning import paths for use-statements.
749 pub fn find_use_path_prefixed(
751 db: &dyn DefDatabase,
752 item: impl Into<ItemInNs>,
753 prefix_kind: PrefixKind,
754 ) -> Option<ModPath> {
755 hir_def::find_path::find_path_prefixed(db, item.into().into(), self.into(), prefix_kind)
759 impl HasVisibility for Module {
760 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
761 let def_map = self.id.def_map(db.upcast());
762 let module_data = &def_map[self.id.local_id];
763 module_data.visibility
767 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
769 pub(crate) parent: VariantDef,
770 pub(crate) id: LocalFieldId,
773 #[derive(Debug, PartialEq, Eq)]
774 pub enum FieldSource {
775 Named(ast::RecordField),
776 Pos(ast::TupleField),
780 pub fn name(&self, db: &dyn HirDatabase) -> Name {
781 self.parent.variant_data(db).fields()[self.id].name.clone()
784 /// Returns the type as in the signature of the struct (i.e., with
785 /// placeholder types for type parameters). Only use this in the context of
786 /// the field definition.
787 pub fn ty(&self, db: &dyn HirDatabase) -> Type {
788 let var_id = self.parent.into();
789 let generic_def_id: GenericDefId = match self.parent {
790 VariantDef::Struct(it) => it.id.into(),
791 VariantDef::Union(it) => it.id.into(),
792 VariantDef::Variant(it) => it.parent.id.into(),
794 let substs = TyBuilder::type_params_subst(db, generic_def_id);
795 let ty = db.field_types(var_id)[self.id].clone().substitute(&Interner, &substs);
796 Type::new(db, self.parent.module(db).id.krate(), var_id, ty)
799 pub fn parent_def(&self, _db: &dyn HirDatabase) -> VariantDef {
804 impl HasVisibility for Field {
805 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
806 let variant_data = self.parent.variant_data(db);
807 let visibility = &variant_data.fields()[self.id].visibility;
808 let parent_id: hir_def::VariantId = self.parent.into();
809 visibility.resolve(db.upcast(), &parent_id.resolver(db.upcast()))
813 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
815 pub(crate) id: StructId,
819 pub fn module(self, db: &dyn HirDatabase) -> Module {
820 Module { id: self.id.lookup(db.upcast()).container }
823 pub fn name(self, db: &dyn HirDatabase) -> Name {
824 db.struct_data(self.id).name.clone()
827 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
828 db.struct_data(self.id)
832 .map(|(id, _)| Field { parent: self.into(), id })
836 pub fn ty(self, db: &dyn HirDatabase) -> Type {
837 Type::from_def(db, self.id.lookup(db.upcast()).container.krate(), self.id)
840 pub fn repr(self, db: &dyn HirDatabase) -> Option<ReprKind> {
841 db.struct_data(self.id).repr.clone()
844 pub fn kind(self, db: &dyn HirDatabase) -> StructKind {
845 self.variant_data(db).kind()
848 fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
849 db.struct_data(self.id).variant_data.clone()
853 impl HasVisibility for Struct {
854 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
855 db.struct_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
859 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
861 pub(crate) id: UnionId,
865 pub fn name(self, db: &dyn HirDatabase) -> Name {
866 db.union_data(self.id).name.clone()
869 pub fn module(self, db: &dyn HirDatabase) -> Module {
870 Module { id: self.id.lookup(db.upcast()).container }
873 pub fn ty(self, db: &dyn HirDatabase) -> Type {
874 Type::from_def(db, self.id.lookup(db.upcast()).container.krate(), self.id)
877 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
878 db.union_data(self.id)
882 .map(|(id, _)| Field { parent: self.into(), id })
886 fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
887 db.union_data(self.id).variant_data.clone()
891 impl HasVisibility for Union {
892 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
893 db.union_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
897 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
899 pub(crate) id: EnumId,
903 pub fn module(self, db: &dyn HirDatabase) -> Module {
904 Module { id: self.id.lookup(db.upcast()).container }
907 pub fn name(self, db: &dyn HirDatabase) -> Name {
908 db.enum_data(self.id).name.clone()
911 pub fn variants(self, db: &dyn HirDatabase) -> Vec<Variant> {
912 db.enum_data(self.id).variants.iter().map(|(id, _)| Variant { parent: self, id }).collect()
915 pub fn ty(self, db: &dyn HirDatabase) -> Type {
916 Type::from_def(db, self.id.lookup(db.upcast()).container.krate(), self.id)
920 impl HasVisibility for Enum {
921 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
922 db.enum_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
926 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
928 pub(crate) parent: Enum,
929 pub(crate) id: LocalEnumVariantId,
933 pub fn module(self, db: &dyn HirDatabase) -> Module {
934 self.parent.module(db)
937 pub fn parent_enum(self, _db: &dyn HirDatabase) -> Enum {
941 pub fn name(self, db: &dyn HirDatabase) -> Name {
942 db.enum_data(self.parent.id).variants[self.id].name.clone()
945 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
946 self.variant_data(db)
949 .map(|(id, _)| Field { parent: self.into(), id })
953 pub fn kind(self, db: &dyn HirDatabase) -> StructKind {
954 self.variant_data(db).kind()
957 pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
958 db.enum_data(self.parent.id).variants[self.id].variant_data.clone()
962 /// Variants inherit visibility from the parent enum.
963 impl HasVisibility for Variant {
964 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
965 self.parent_enum(db).visibility(db)
970 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
976 impl_from!(Struct, Union, Enum for Adt);
979 pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
980 let subst = db.generic_defaults(self.into());
981 subst.iter().any(|ty| ty.skip_binders().is_unknown())
984 /// Turns this ADT into a type. Any type parameters of the ADT will be
985 /// turned into unknown types, which is good for e.g. finding the most
986 /// general set of completions, but will not look very nice when printed.
987 pub fn ty(self, db: &dyn HirDatabase) -> Type {
988 let id = AdtId::from(self);
989 Type::from_def(db, id.module(db.upcast()).krate(), id)
992 pub fn module(self, db: &dyn HirDatabase) -> Module {
994 Adt::Struct(s) => s.module(db),
995 Adt::Union(s) => s.module(db),
996 Adt::Enum(e) => e.module(db),
1000 pub fn name(self, db: &dyn HirDatabase) -> Name {
1002 Adt::Struct(s) => s.name(db),
1003 Adt::Union(u) => u.name(db),
1004 Adt::Enum(e) => e.name(db),
1009 impl HasVisibility for Adt {
1010 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1012 Adt::Struct(it) => it.visibility(db),
1013 Adt::Union(it) => it.visibility(db),
1014 Adt::Enum(it) => it.visibility(db),
1019 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1020 pub enum VariantDef {
1025 impl_from!(Struct, Union, Variant for VariantDef);
1028 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
1030 VariantDef::Struct(it) => it.fields(db),
1031 VariantDef::Union(it) => it.fields(db),
1032 VariantDef::Variant(it) => it.fields(db),
1036 pub fn module(self, db: &dyn HirDatabase) -> Module {
1038 VariantDef::Struct(it) => it.module(db),
1039 VariantDef::Union(it) => it.module(db),
1040 VariantDef::Variant(it) => it.module(db),
1044 pub fn name(&self, db: &dyn HirDatabase) -> Name {
1046 VariantDef::Struct(s) => s.name(db),
1047 VariantDef::Union(u) => u.name(db),
1048 VariantDef::Variant(e) => e.name(db),
1052 pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
1054 VariantDef::Struct(it) => it.variant_data(db),
1055 VariantDef::Union(it) => it.variant_data(db),
1056 VariantDef::Variant(it) => it.variant_data(db),
1061 /// The defs which have a body.
1062 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1063 pub enum DefWithBody {
1068 impl_from!(Function, Const, Static for DefWithBody);
1071 pub fn module(self, db: &dyn HirDatabase) -> Module {
1073 DefWithBody::Const(c) => c.module(db),
1074 DefWithBody::Function(f) => f.module(db),
1075 DefWithBody::Static(s) => s.module(db),
1079 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1081 DefWithBody::Function(f) => Some(f.name(db)),
1082 DefWithBody::Static(s) => Some(s.name(db)),
1083 DefWithBody::Const(c) => c.name(db),
1087 /// Returns the type this def's body has to evaluate to.
1088 pub fn body_type(self, db: &dyn HirDatabase) -> Type {
1090 DefWithBody::Function(it) => it.ret_type(db),
1091 DefWithBody::Static(it) => it.ty(db),
1092 DefWithBody::Const(it) => it.ty(db),
1096 pub fn diagnostics(self, db: &dyn HirDatabase, acc: &mut Vec<AnyDiagnostic>) {
1097 let krate = self.module(db).id.krate();
1099 let source_map = db.body_with_source_map(self.into()).1;
1100 for diag in source_map.diagnostics() {
1102 BodyDiagnostic::InactiveCode { node, cfg, opts } => acc.push(
1103 InactiveCode { node: node.clone(), cfg: cfg.clone(), opts: opts.clone() }
1106 BodyDiagnostic::MacroError { node, message } => acc.push(
1108 node: node.clone().map(|it| it.into()),
1109 message: message.to_string(),
1113 BodyDiagnostic::UnresolvedProcMacro { node } => acc.push(
1114 UnresolvedProcMacro {
1115 node: node.clone().map(|it| it.into()),
1116 precise_location: None,
1121 BodyDiagnostic::UnresolvedMacroCall { node, path } => acc.push(
1122 UnresolvedMacroCall { macro_call: node.clone(), path: path.clone() }.into(),
1127 let infer = db.infer(self.into());
1128 let source_map = Lazy::new(|| db.body_with_source_map(self.into()).1);
1129 for d in &infer.diagnostics {
1131 hir_ty::InferenceDiagnostic::NoSuchField { expr } => {
1132 let field = source_map.field_syntax(*expr);
1133 acc.push(NoSuchField { field }.into())
1135 hir_ty::InferenceDiagnostic::BreakOutsideOfLoop { expr } => {
1136 let expr = source_map
1138 .expect("break outside of loop in synthetic syntax");
1139 acc.push(BreakOutsideOfLoop { expr }.into())
1144 for expr in hir_ty::diagnostics::missing_unsafe(db, self.into()) {
1145 match source_map.expr_syntax(expr) {
1146 Ok(expr) => acc.push(MissingUnsafe { expr }.into()),
1147 Err(SyntheticSyntax) => {
1148 // FIXME: Here and eslwhere in this file, the `expr` was
1149 // desugared, report or assert that this doesn't happen.
1154 for diagnostic in BodyValidationDiagnostic::collect(db, self.into()) {
1156 BodyValidationDiagnostic::RecordMissingFields {
1161 let variant_data = variant.variant_data(db.upcast());
1162 let missed_fields = missed_fields
1164 .map(|idx| variant_data.fields()[idx].name.clone())
1168 Either::Left(record_expr) => match source_map.expr_syntax(record_expr) {
1170 let root = source_ptr.file_syntax(db.upcast());
1171 if let ast::Expr::RecordExpr(record_expr) =
1172 &source_ptr.value.to_node(&root)
1174 if record_expr.record_expr_field_list().is_some() {
1177 file: source_ptr.file_id,
1178 field_list_parent: Either::Left(AstPtr::new(
1181 field_list_parent_path: record_expr
1183 .map(|path| AstPtr::new(&path)),
1191 Err(SyntheticSyntax) => (),
1193 Either::Right(record_pat) => match source_map.pat_syntax(record_pat) {
1195 if let Some(expr) = source_ptr.value.as_ref().left() {
1196 let root = source_ptr.file_syntax(db.upcast());
1197 if let ast::Pat::RecordPat(record_pat) = expr.to_node(&root) {
1198 if record_pat.record_pat_field_list().is_some() {
1201 file: source_ptr.file_id,
1202 field_list_parent: Either::Right(AstPtr::new(
1205 field_list_parent_path: record_pat
1207 .map(|path| AstPtr::new(&path)),
1216 Err(SyntheticSyntax) => (),
1220 BodyValidationDiagnostic::ReplaceFilterMapNextWithFindMap { method_call_expr } => {
1221 if let Ok(next_source_ptr) = source_map.expr_syntax(method_call_expr) {
1223 ReplaceFilterMapNextWithFindMap {
1224 file: next_source_ptr.file_id,
1225 next_expr: next_source_ptr.value,
1231 BodyValidationDiagnostic::MismatchedArgCount { call_expr, expected, found } => {
1232 match source_map.expr_syntax(call_expr) {
1233 Ok(source_ptr) => acc.push(
1234 MismatchedArgCount { call_expr: source_ptr, expected, found }.into(),
1236 Err(SyntheticSyntax) => (),
1239 BodyValidationDiagnostic::RemoveThisSemicolon { expr } => {
1240 match source_map.expr_syntax(expr) {
1241 Ok(expr) => acc.push(RemoveThisSemicolon { expr }.into()),
1242 Err(SyntheticSyntax) => (),
1245 BodyValidationDiagnostic::MissingOkOrSomeInTailExpr { expr, required } => {
1246 match source_map.expr_syntax(expr) {
1247 Ok(expr) => acc.push(
1248 MissingOkOrSomeInTailExpr {
1251 expected: self.body_type(db),
1255 Err(SyntheticSyntax) => (),
1258 BodyValidationDiagnostic::MissingMatchArms { match_expr } => {
1259 match source_map.expr_syntax(match_expr) {
1261 let root = source_ptr.file_syntax(db.upcast());
1262 if let ast::Expr::MatchExpr(match_expr) =
1263 &source_ptr.value.to_node(&root)
1265 if let (Some(match_expr), Some(arms)) =
1266 (match_expr.expr(), match_expr.match_arm_list())
1270 file: source_ptr.file_id,
1271 match_expr: AstPtr::new(&match_expr),
1272 arms: AstPtr::new(&arms),
1279 Err(SyntheticSyntax) => (),
1282 BodyValidationDiagnostic::AddReferenceHere { arg_expr, mutability } => {
1283 match source_map.expr_syntax(arg_expr) {
1284 Ok(expr) => acc.push(AddReferenceHere { expr, mutability }.into()),
1285 Err(SyntheticSyntax) => (),
1291 let def: ModuleDef = match self {
1292 DefWithBody::Function(it) => it.into(),
1293 DefWithBody::Static(it) => it.into(),
1294 DefWithBody::Const(it) => it.into(),
1296 for diag in hir_ty::diagnostics::incorrect_case(db, krate, def.into()) {
1297 acc.push(diag.into())
1302 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1303 pub struct Function {
1304 pub(crate) id: FunctionId,
1308 pub fn module(self, db: &dyn HirDatabase) -> Module {
1309 self.id.lookup(db.upcast()).module(db.upcast()).into()
1312 pub fn name(self, db: &dyn HirDatabase) -> Name {
1313 db.function_data(self.id).name.clone()
1316 /// Get this function's return type
1317 pub fn ret_type(self, db: &dyn HirDatabase) -> Type {
1318 let resolver = self.id.resolver(db.upcast());
1319 let krate = self.id.lookup(db.upcast()).container.module(db.upcast()).krate();
1320 let ret_type = &db.function_data(self.id).ret_type;
1321 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
1322 let ty = ctx.lower_ty(ret_type);
1323 Type::new_with_resolver_inner(db, krate, &resolver, ty)
1326 pub fn self_param(self, db: &dyn HirDatabase) -> Option<SelfParam> {
1327 if !db.function_data(self.id).has_self_param() {
1330 Some(SelfParam { func: self.id })
1333 pub fn assoc_fn_params(self, db: &dyn HirDatabase) -> Vec<Param> {
1334 let resolver = self.id.resolver(db.upcast());
1335 let krate = self.id.lookup(db.upcast()).container.module(db.upcast()).krate();
1336 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
1337 let environment = db.trait_environment(self.id.into());
1338 db.function_data(self.id)
1342 .map(|(idx, type_ref)| {
1343 let ty = Type { krate, env: environment.clone(), ty: ctx.lower_ty(type_ref) };
1344 Param { func: self, ty, idx }
1349 pub fn method_params(self, db: &dyn HirDatabase) -> Option<Vec<Param>> {
1350 if self.self_param(db).is_none() {
1353 let mut res = self.assoc_fn_params(db);
1358 pub fn is_unsafe(self, db: &dyn HirDatabase) -> bool {
1359 db.function_data(self.id).is_unsafe()
1362 pub fn is_const(self, db: &dyn HirDatabase) -> bool {
1363 db.function_data(self.id).is_const()
1366 pub fn is_async(self, db: &dyn HirDatabase) -> bool {
1367 db.function_data(self.id).is_async()
1370 /// Whether this function declaration has a definition.
1372 /// This is false in the case of required (not provided) trait methods.
1373 pub fn has_body(self, db: &dyn HirDatabase) -> bool {
1374 db.function_data(self.id).has_body()
1377 /// A textual representation of the HIR of this function for debugging purposes.
1378 pub fn debug_hir(self, db: &dyn HirDatabase) -> String {
1379 let body = db.body(self.id.into());
1381 let mut result = String::new();
1382 format_to!(result, "HIR expressions in the body of `{}`:\n", self.name(db));
1383 for (id, expr) in body.exprs.iter() {
1384 format_to!(result, "{:?}: {:?}\n", id, expr);
1391 // Note: logically, this belongs to `hir_ty`, but we are not using it there yet.
1398 impl From<hir_ty::Mutability> for Access {
1399 fn from(mutability: hir_ty::Mutability) -> Access {
1401 hir_ty::Mutability::Not => Access::Shared,
1402 hir_ty::Mutability::Mut => Access::Exclusive,
1407 #[derive(Clone, Debug)]
1410 /// The index in parameter list, including self parameter.
1416 pub fn ty(&self) -> &Type {
1420 pub fn as_local(&self, db: &dyn HirDatabase) -> Local {
1421 let parent = DefWithBodyId::FunctionId(self.func.into());
1422 let body = db.body(parent);
1423 Local { parent, pat_id: body.params[self.idx] }
1426 pub fn pattern_source(&self, db: &dyn HirDatabase) -> Option<ast::Pat> {
1427 self.source(db).and_then(|p| p.value.pat())
1430 pub fn source(&self, db: &dyn HirDatabase) -> Option<InFile<ast::Param>> {
1431 let InFile { file_id, value } = self.func.source(db)?;
1432 let params = value.param_list()?;
1433 if params.self_param().is_some() {
1434 params.params().nth(self.idx.checked_sub(1)?)
1436 params.params().nth(self.idx)
1438 .map(|value| InFile { file_id, value })
1442 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1443 pub struct SelfParam {
1448 pub fn access(self, db: &dyn HirDatabase) -> Access {
1449 let func_data = db.function_data(self.func);
1453 .map(|param| match &**param {
1454 TypeRef::Reference(.., mutability) => match mutability {
1455 hir_def::type_ref::Mutability::Shared => Access::Shared,
1456 hir_def::type_ref::Mutability::Mut => Access::Exclusive,
1460 .unwrap_or(Access::Owned)
1463 pub fn display(self, db: &dyn HirDatabase) -> &'static str {
1464 match self.access(db) {
1465 Access::Shared => "&self",
1466 Access::Exclusive => "&mut self",
1467 Access::Owned => "self",
1471 pub fn source(&self, db: &dyn HirDatabase) -> Option<InFile<ast::SelfParam>> {
1472 let InFile { file_id, value } = Function::from(self.func).source(db)?;
1475 .and_then(|params| params.self_param())
1476 .map(|value| InFile { file_id, value })
1480 impl HasVisibility for Function {
1481 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1482 let function_data = db.function_data(self.id);
1483 let visibility = &function_data.visibility;
1484 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1488 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1490 pub(crate) id: ConstId,
1494 pub fn module(self, db: &dyn HirDatabase) -> Module {
1495 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
1498 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1499 db.const_data(self.id).name.clone()
1502 pub fn value(self, db: &dyn HirDatabase) -> Option<ast::Expr> {
1503 self.source(db)?.value.body()
1506 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1507 let data = db.const_data(self.id);
1508 let resolver = self.id.resolver(db.upcast());
1509 let krate = self.id.lookup(db.upcast()).container.krate(db);
1510 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
1511 let ty = ctx.lower_ty(&data.type_ref);
1512 Type::new_with_resolver_inner(db, krate.id, &resolver, ty)
1516 impl HasVisibility for Const {
1517 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1518 let function_data = db.const_data(self.id);
1519 let visibility = &function_data.visibility;
1520 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1524 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1526 pub(crate) id: StaticId,
1530 pub fn module(self, db: &dyn HirDatabase) -> Module {
1531 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
1534 pub fn name(self, db: &dyn HirDatabase) -> Name {
1535 db.static_data(self.id).name.clone()
1538 pub fn is_mut(self, db: &dyn HirDatabase) -> bool {
1539 db.static_data(self.id).mutable
1542 pub fn value(self, db: &dyn HirDatabase) -> Option<ast::Expr> {
1543 self.source(db)?.value.body()
1546 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1547 let data = db.static_data(self.id);
1548 let resolver = self.id.resolver(db.upcast());
1549 let krate = self.id.lookup(db.upcast()).container.krate();
1550 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
1551 let ty = ctx.lower_ty(&data.type_ref);
1552 Type::new_with_resolver_inner(db, krate, &resolver, ty)
1556 impl HasVisibility for Static {
1557 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1558 db.static_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1562 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1564 pub(crate) id: TraitId,
1568 pub fn module(self, db: &dyn HirDatabase) -> Module {
1569 Module { id: self.id.lookup(db.upcast()).container }
1572 pub fn name(self, db: &dyn HirDatabase) -> Name {
1573 db.trait_data(self.id).name.clone()
1576 pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
1577 db.trait_data(self.id).items.iter().map(|(_name, it)| (*it).into()).collect()
1580 pub fn is_auto(self, db: &dyn HirDatabase) -> bool {
1581 db.trait_data(self.id).is_auto
1584 pub fn is_unsafe(&self, db: &dyn HirDatabase) -> bool {
1585 db.trait_data(self.id).is_unsafe
1589 impl HasVisibility for Trait {
1590 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1591 db.trait_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1595 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1596 pub struct TypeAlias {
1597 pub(crate) id: TypeAliasId,
1601 pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
1602 let subst = db.generic_defaults(self.id.into());
1603 subst.iter().any(|ty| ty.skip_binders().is_unknown())
1606 pub fn module(self, db: &dyn HirDatabase) -> Module {
1607 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
1610 pub fn type_ref(self, db: &dyn HirDatabase) -> Option<TypeRef> {
1611 db.type_alias_data(self.id).type_ref.as_deref().cloned()
1614 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1615 Type::from_def(db, self.id.lookup(db.upcast()).module(db.upcast()).krate(), self.id)
1618 pub fn name(self, db: &dyn HirDatabase) -> Name {
1619 db.type_alias_data(self.id).name.clone()
1623 impl HasVisibility for TypeAlias {
1624 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1625 let function_data = db.type_alias_data(self.id);
1626 let visibility = &function_data.visibility;
1627 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1631 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1632 pub struct BuiltinType {
1633 pub(crate) inner: hir_def::builtin_type::BuiltinType,
1637 pub fn str() -> BuiltinType {
1638 BuiltinType { inner: hir_def::builtin_type::BuiltinType::Str }
1641 pub fn ty(self, db: &dyn HirDatabase, module: Module) -> Type {
1642 let resolver = module.id.resolver(db.upcast());
1643 Type::new_with_resolver(db, &resolver, TyBuilder::builtin(self.inner))
1644 .expect("crate not present in resolver")
1647 pub fn name(self) -> Name {
1648 self.inner.as_name()
1652 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1653 pub enum MacroKind {
1654 /// `macro_rules!` or Macros 2.0 macro.
1656 /// A built-in or custom derive.
1658 /// A built-in function-like macro.
1660 /// A procedural attribute macro.
1662 /// A function-like procedural macro.
1666 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1667 pub struct MacroDef {
1668 pub(crate) id: MacroDefId,
1672 /// FIXME: right now, this just returns the root module of the crate that
1673 /// defines this macro. The reasons for this is that macros are expanded
1674 /// early, in `hir_expand`, where modules simply do not exist yet.
1675 pub fn module(self, db: &dyn HirDatabase) -> Option<Module> {
1676 let krate = self.id.krate;
1677 let def_map = db.crate_def_map(krate);
1678 let module_id = def_map.root();
1679 Some(Module { id: def_map.module_id(module_id) })
1682 /// XXX: this parses the file
1683 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1684 match self.source(db)?.value {
1685 Either::Left(it) => it.name().map(|it| it.as_name()),
1686 Either::Right(_) => {
1687 let krate = self.id.krate;
1688 let def_map = db.crate_def_map(krate);
1689 let (_, name) = def_map.exported_proc_macros().find(|&(id, _)| id == self.id)?;
1695 pub fn kind(&self) -> MacroKind {
1696 match self.id.kind {
1697 MacroDefKind::Declarative(_) => MacroKind::Declarative,
1698 MacroDefKind::BuiltIn(_, _) | MacroDefKind::BuiltInEager(_, _) => MacroKind::BuiltIn,
1699 MacroDefKind::BuiltInDerive(_, _) => MacroKind::Derive,
1700 MacroDefKind::BuiltInAttr(_, _) => MacroKind::Attr,
1701 MacroDefKind::ProcMacro(_, base_db::ProcMacroKind::CustomDerive, _) => {
1704 MacroDefKind::ProcMacro(_, base_db::ProcMacroKind::Attr, _) => MacroKind::Attr,
1705 MacroDefKind::ProcMacro(_, base_db::ProcMacroKind::FuncLike, _) => MacroKind::ProcMacro,
1709 pub fn is_fn_like(&self) -> bool {
1711 MacroKind::Declarative | MacroKind::BuiltIn | MacroKind::ProcMacro => true,
1712 MacroKind::Attr | MacroKind::Derive => false,
1717 #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
1724 impl From<MacroDef> for ItemInNs {
1725 fn from(it: MacroDef) -> Self {
1730 impl From<ModuleDef> for ItemInNs {
1731 fn from(module_def: ModuleDef) -> Self {
1733 ModuleDef::Static(_) | ModuleDef::Const(_) | ModuleDef::Function(_) => {
1734 ItemInNs::Values(module_def)
1736 _ => ItemInNs::Types(module_def),
1742 pub fn as_module_def(self) -> Option<ModuleDef> {
1744 ItemInNs::Types(id) | ItemInNs::Values(id) => Some(id),
1745 ItemInNs::Macros(_) => None,
1749 /// Returns the crate defining this item (or `None` if `self` is built-in).
1750 pub fn krate(&self, db: &dyn HirDatabase) -> Option<Crate> {
1752 ItemInNs::Types(did) | ItemInNs::Values(did) => did.module(db).map(|m| m.krate()),
1753 ItemInNs::Macros(id) => id.module(db).map(|m| m.krate()),
1757 pub fn attrs(&self, db: &dyn HirDatabase) -> Option<AttrsWithOwner> {
1759 ItemInNs::Types(it) | ItemInNs::Values(it) => it.attrs(db),
1760 ItemInNs::Macros(it) => Some(it.attrs(db)),
1765 /// Invariant: `inner.as_assoc_item(db).is_some()`
1766 /// We do not actively enforce this invariant.
1767 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1768 pub enum AssocItem {
1771 TypeAlias(TypeAlias),
1774 pub enum AssocItemContainer {
1778 pub trait AsAssocItem {
1779 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem>;
1782 impl AsAssocItem for Function {
1783 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1784 as_assoc_item(db, AssocItem::Function, self.id)
1787 impl AsAssocItem for Const {
1788 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1789 as_assoc_item(db, AssocItem::Const, self.id)
1792 impl AsAssocItem for TypeAlias {
1793 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1794 as_assoc_item(db, AssocItem::TypeAlias, self.id)
1797 impl AsAssocItem for ModuleDef {
1798 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1800 ModuleDef::Function(it) => it.as_assoc_item(db),
1801 ModuleDef::Const(it) => it.as_assoc_item(db),
1802 ModuleDef::TypeAlias(it) => it.as_assoc_item(db),
1807 fn as_assoc_item<ID, DEF, CTOR, AST>(db: &dyn HirDatabase, ctor: CTOR, id: ID) -> Option<AssocItem>
1809 ID: Lookup<Data = AssocItemLoc<AST>>,
1811 CTOR: FnOnce(DEF) -> AssocItem,
1814 match id.lookup(db.upcast()).container {
1815 AssocContainerId::TraitId(_) | AssocContainerId::ImplId(_) => Some(ctor(DEF::from(id))),
1816 AssocContainerId::ModuleId(_) => None,
1821 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1823 AssocItem::Function(it) => Some(it.name(db)),
1824 AssocItem::Const(it) => it.name(db),
1825 AssocItem::TypeAlias(it) => Some(it.name(db)),
1828 pub fn module(self, db: &dyn HirDatabase) -> Module {
1830 AssocItem::Function(f) => f.module(db),
1831 AssocItem::Const(c) => c.module(db),
1832 AssocItem::TypeAlias(t) => t.module(db),
1835 pub fn container(self, db: &dyn HirDatabase) -> AssocItemContainer {
1836 let container = match self {
1837 AssocItem::Function(it) => it.id.lookup(db.upcast()).container,
1838 AssocItem::Const(it) => it.id.lookup(db.upcast()).container,
1839 AssocItem::TypeAlias(it) => it.id.lookup(db.upcast()).container,
1842 AssocContainerId::TraitId(id) => AssocItemContainer::Trait(id.into()),
1843 AssocContainerId::ImplId(id) => AssocItemContainer::Impl(id.into()),
1844 AssocContainerId::ModuleId(_) => panic!("invalid AssocItem"),
1848 pub fn containing_trait(self, db: &dyn HirDatabase) -> Option<Trait> {
1849 match self.container(db) {
1850 AssocItemContainer::Trait(t) => Some(t),
1855 pub fn containing_trait_impl(self, db: &dyn HirDatabase) -> Option<Trait> {
1856 match self.container(db) {
1857 AssocItemContainer::Impl(i) => i.trait_(db),
1862 pub fn containing_trait_or_trait_impl(self, db: &dyn HirDatabase) -> Option<Trait> {
1863 match self.container(db) {
1864 AssocItemContainer::Trait(t) => Some(t),
1865 AssocItemContainer::Impl(i) => i.trait_(db),
1870 impl HasVisibility for AssocItem {
1871 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1873 AssocItem::Function(f) => f.visibility(db),
1874 AssocItem::Const(c) => c.visibility(db),
1875 AssocItem::TypeAlias(t) => t.visibility(db),
1880 impl From<AssocItem> for ModuleDef {
1881 fn from(assoc: AssocItem) -> Self {
1883 AssocItem::Function(it) => ModuleDef::Function(it),
1884 AssocItem::Const(it) => ModuleDef::Const(it),
1885 AssocItem::TypeAlias(it) => ModuleDef::TypeAlias(it),
1890 #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
1891 pub enum GenericDef {
1895 TypeAlias(TypeAlias),
1897 // enum variants cannot have generics themselves, but their parent enums
1898 // can, and this makes some code easier to write
1900 // consts can have type parameters from their parents (i.e. associated consts of traits)
1905 Adt(Struct, Enum, Union),
1915 pub fn params(self, db: &dyn HirDatabase) -> Vec<GenericParam> {
1916 let generics = db.generic_params(self.into());
1917 let ty_params = generics
1920 .map(|(local_id, _)| TypeParam { id: TypeParamId { parent: self.into(), local_id } })
1921 .map(GenericParam::TypeParam);
1922 let lt_params = generics
1925 .map(|(local_id, _)| LifetimeParam {
1926 id: LifetimeParamId { parent: self.into(), local_id },
1928 .map(GenericParam::LifetimeParam);
1929 let const_params = generics
1932 .map(|(local_id, _)| ConstParam { id: ConstParamId { parent: self.into(), local_id } })
1933 .map(GenericParam::ConstParam);
1934 ty_params.chain(lt_params).chain(const_params).collect()
1937 pub fn type_params(self, db: &dyn HirDatabase) -> Vec<TypeParam> {
1938 let generics = db.generic_params(self.into());
1942 .map(|(local_id, _)| TypeParam { id: TypeParamId { parent: self.into(), local_id } })
1947 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1949 pub(crate) parent: DefWithBodyId,
1950 pub(crate) pat_id: PatId,
1954 pub fn is_param(self, db: &dyn HirDatabase) -> bool {
1955 let src = self.source(db);
1957 Either::Left(bind_pat) => {
1958 bind_pat.syntax().ancestors().any(|it| ast::Param::can_cast(it.kind()))
1960 Either::Right(_self_param) => true,
1964 pub fn as_self_param(self, db: &dyn HirDatabase) -> Option<SelfParam> {
1966 DefWithBodyId::FunctionId(func) if self.is_self(db) => Some(SelfParam { func }),
1971 // FIXME: why is this an option? It shouldn't be?
1972 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1973 let body = db.body(self.parent);
1974 match &body[self.pat_id] {
1975 Pat::Bind { name, .. } => Some(name.clone()),
1980 pub fn is_self(self, db: &dyn HirDatabase) -> bool {
1981 self.name(db) == Some(name![self])
1984 pub fn is_mut(self, db: &dyn HirDatabase) -> bool {
1985 let body = db.body(self.parent);
1986 matches!(&body[self.pat_id], Pat::Bind { mode: BindingAnnotation::Mutable, .. })
1989 pub fn is_ref(self, db: &dyn HirDatabase) -> bool {
1990 let body = db.body(self.parent);
1993 Pat::Bind { mode: BindingAnnotation::Ref | BindingAnnotation::RefMut, .. }
1997 pub fn parent(self, _db: &dyn HirDatabase) -> DefWithBody {
2001 pub fn module(self, db: &dyn HirDatabase) -> Module {
2002 self.parent(db).module(db)
2005 pub fn ty(self, db: &dyn HirDatabase) -> Type {
2006 let def = self.parent;
2007 let infer = db.infer(def);
2008 let ty = infer[self.pat_id].clone();
2009 let krate = def.module(db.upcast()).krate();
2010 Type::new(db, krate, def, ty)
2013 pub fn source(self, db: &dyn HirDatabase) -> InFile<Either<ast::IdentPat, ast::SelfParam>> {
2014 let (_body, source_map) = db.body_with_source_map(self.parent);
2015 let src = source_map.pat_syntax(self.pat_id).unwrap(); // Hmm...
2016 let root = src.file_syntax(db.upcast());
2018 ast.map_left(|it| it.cast().unwrap().to_node(&root)).map_right(|it| it.to_node(&root))
2023 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2025 pub(crate) parent: DefWithBodyId,
2026 pub(crate) label_id: LabelId,
2030 pub fn module(self, db: &dyn HirDatabase) -> Module {
2031 self.parent(db).module(db)
2034 pub fn parent(self, _db: &dyn HirDatabase) -> DefWithBody {
2038 pub fn name(self, db: &dyn HirDatabase) -> Name {
2039 let body = db.body(self.parent);
2040 body[self.label_id].name.clone()
2043 pub fn source(self, db: &dyn HirDatabase) -> InFile<ast::Label> {
2044 let (_body, source_map) = db.body_with_source_map(self.parent);
2045 let src = source_map.label_syntax(self.label_id);
2046 let root = src.file_syntax(db.upcast());
2047 src.map(|ast| ast.to_node(&root))
2051 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2052 pub enum GenericParam {
2053 TypeParam(TypeParam),
2054 LifetimeParam(LifetimeParam),
2055 ConstParam(ConstParam),
2057 impl_from!(TypeParam, LifetimeParam, ConstParam for GenericParam);
2060 pub fn module(self, db: &dyn HirDatabase) -> Module {
2062 GenericParam::TypeParam(it) => it.module(db),
2063 GenericParam::LifetimeParam(it) => it.module(db),
2064 GenericParam::ConstParam(it) => it.module(db),
2068 pub fn name(self, db: &dyn HirDatabase) -> Name {
2070 GenericParam::TypeParam(it) => it.name(db),
2071 GenericParam::LifetimeParam(it) => it.name(db),
2072 GenericParam::ConstParam(it) => it.name(db),
2077 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2078 pub struct TypeParam {
2079 pub(crate) id: TypeParamId,
2083 pub fn name(self, db: &dyn HirDatabase) -> Name {
2084 let params = db.generic_params(self.id.parent);
2085 params.types[self.id.local_id].name.clone().unwrap_or_else(Name::missing)
2088 pub fn module(self, db: &dyn HirDatabase) -> Module {
2089 self.id.parent.module(db.upcast()).into()
2092 pub fn ty(self, db: &dyn HirDatabase) -> Type {
2093 let resolver = self.id.parent.resolver(db.upcast());
2094 let krate = self.id.parent.module(db.upcast()).krate();
2095 let ty = TyKind::Placeholder(hir_ty::to_placeholder_idx(db, self.id)).intern(&Interner);
2096 Type::new_with_resolver_inner(db, krate, &resolver, ty)
2099 pub fn trait_bounds(self, db: &dyn HirDatabase) -> Vec<Trait> {
2100 db.generic_predicates_for_param(self.id, None)
2102 .filter_map(|pred| match &pred.skip_binders().skip_binders() {
2103 hir_ty::WhereClause::Implemented(trait_ref) => {
2104 Some(Trait::from(trait_ref.hir_trait_id()))
2111 pub fn default(self, db: &dyn HirDatabase) -> Option<Type> {
2112 let params = db.generic_defaults(self.id.parent);
2113 let local_idx = hir_ty::param_idx(db, self.id)?;
2114 let resolver = self.id.parent.resolver(db.upcast());
2115 let krate = self.id.parent.module(db.upcast()).krate();
2116 let ty = params.get(local_idx)?.clone();
2117 let subst = TyBuilder::type_params_subst(db, self.id.parent);
2118 let ty = ty.substitute(&Interner, &subst_prefix(&subst, local_idx));
2119 Some(Type::new_with_resolver_inner(db, krate, &resolver, ty))
2123 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2124 pub struct LifetimeParam {
2125 pub(crate) id: LifetimeParamId,
2128 impl LifetimeParam {
2129 pub fn name(self, db: &dyn HirDatabase) -> Name {
2130 let params = db.generic_params(self.id.parent);
2131 params.lifetimes[self.id.local_id].name.clone()
2134 pub fn module(self, db: &dyn HirDatabase) -> Module {
2135 self.id.parent.module(db.upcast()).into()
2138 pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef {
2139 self.id.parent.into()
2143 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2144 pub struct ConstParam {
2145 pub(crate) id: ConstParamId,
2149 pub fn name(self, db: &dyn HirDatabase) -> Name {
2150 let params = db.generic_params(self.id.parent);
2151 params.consts[self.id.local_id].name.clone()
2154 pub fn module(self, db: &dyn HirDatabase) -> Module {
2155 self.id.parent.module(db.upcast()).into()
2158 pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef {
2159 self.id.parent.into()
2162 pub fn ty(self, db: &dyn HirDatabase) -> Type {
2163 let def = self.id.parent;
2164 let krate = def.module(db.upcast()).krate();
2165 Type::new(db, krate, def, db.const_param_ty(self.id))
2169 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2171 pub(crate) id: ImplId,
2175 pub fn all_in_crate(db: &dyn HirDatabase, krate: Crate) -> Vec<Impl> {
2176 let inherent = db.inherent_impls_in_crate(krate.id);
2177 let trait_ = db.trait_impls_in_crate(krate.id);
2179 inherent.all_impls().chain(trait_.all_impls()).map(Self::from).collect()
2182 pub fn all_for_type(db: &dyn HirDatabase, Type { krate, ty, .. }: Type) -> Vec<Impl> {
2183 let def_crates = match method_resolution::def_crates(db, &ty, krate) {
2184 Some(def_crates) => def_crates,
2185 None => return Vec::new(),
2188 let filter = |impl_def: &Impl| {
2189 let self_ty = impl_def.self_ty(db);
2190 let rref = self_ty.remove_ref();
2191 ty.equals_ctor(rref.as_ref().map_or(&self_ty.ty, |it| &it.ty))
2194 let fp = TyFingerprint::for_inherent_impl(&ty);
2197 None => return Vec::new(),
2200 let mut all = Vec::new();
2201 def_crates.iter().for_each(|&id| {
2203 db.inherent_impls_in_crate(id)
2211 for id in def_crates
2213 .flat_map(|&id| Crate { id }.transitive_reverse_dependencies(db))
2214 .map(|Crate { id }| id)
2215 .chain(def_crates.iter().copied())
2219 db.trait_impls_in_crate(id)
2220 .for_self_ty_without_blanket_impls(fp)
2228 pub fn all_for_trait(db: &dyn HirDatabase, trait_: Trait) -> Vec<Impl> {
2229 let krate = trait_.module(db).krate();
2230 let mut all = Vec::new();
2231 for Crate { id } in krate.transitive_reverse_dependencies(db).into_iter() {
2232 let impls = db.trait_impls_in_crate(id);
2233 all.extend(impls.for_trait(trait_.id).map(Self::from))
2238 // FIXME: the return type is wrong. This should be a hir version of
2239 // `TraitRef` (to account for parameters and qualifiers)
2240 pub fn trait_(self, db: &dyn HirDatabase) -> Option<Trait> {
2241 let trait_ref = db.impl_trait(self.id)?.skip_binders().clone();
2242 let id = hir_ty::from_chalk_trait_id(trait_ref.trait_id);
2246 pub fn self_ty(self, db: &dyn HirDatabase) -> Type {
2247 let impl_data = db.impl_data(self.id);
2248 let resolver = self.id.resolver(db.upcast());
2249 let krate = self.id.lookup(db.upcast()).container.krate();
2250 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
2251 let ty = ctx.lower_ty(&impl_data.self_ty);
2252 Type::new_with_resolver_inner(db, krate, &resolver, ty)
2255 pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
2256 db.impl_data(self.id).items.iter().map(|it| (*it).into()).collect()
2259 pub fn is_negative(self, db: &dyn HirDatabase) -> bool {
2260 db.impl_data(self.id).is_negative
2263 pub fn module(self, db: &dyn HirDatabase) -> Module {
2264 self.id.lookup(db.upcast()).container.into()
2267 pub fn is_builtin_derive(self, db: &dyn HirDatabase) -> Option<InFile<ast::Attr>> {
2268 let src = self.source(db)?;
2269 let item = src.file_id.is_builtin_derive(db.upcast())?;
2270 let hygenic = hir_expand::hygiene::Hygiene::new(db.upcast(), item.file_id);
2272 // FIXME: handle `cfg_attr`
2277 let path = ModPath::from_src(db.upcast(), it.path()?, &hygenic)?;
2278 if path.as_ident()?.to_smol_str() == "derive" {
2286 Some(item.with_value(attr))
2290 #[derive(Clone, PartialEq, Eq, Debug)]
2293 env: Arc<TraitEnvironment>,
2298 pub(crate) fn new_with_resolver(
2299 db: &dyn HirDatabase,
2300 resolver: &Resolver,
2303 let krate = resolver.krate()?;
2304 Some(Type::new_with_resolver_inner(db, krate, resolver, ty))
2306 pub(crate) fn new_with_resolver_inner(
2307 db: &dyn HirDatabase,
2309 resolver: &Resolver,
2312 let environment = resolver
2314 .map_or_else(|| Arc::new(TraitEnvironment::empty(krate)), |d| db.trait_environment(d));
2315 Type { krate, env: environment, ty }
2318 fn new(db: &dyn HirDatabase, krate: CrateId, lexical_env: impl HasResolver, ty: Ty) -> Type {
2319 let resolver = lexical_env.resolver(db.upcast());
2320 let environment = resolver
2322 .map_or_else(|| Arc::new(TraitEnvironment::empty(krate)), |d| db.trait_environment(d));
2323 Type { krate, env: environment, ty }
2327 db: &dyn HirDatabase,
2329 def: impl HasResolver + Into<TyDefId>,
2331 let ty = TyBuilder::def_ty(db, def.into()).fill_with_unknown().build();
2332 Type::new(db, krate, def, ty)
2335 pub fn new_slice(ty: Type) -> Type {
2336 Type { krate: ty.krate, env: ty.env, ty: TyBuilder::slice(ty.ty) }
2339 pub fn is_unit(&self) -> bool {
2340 matches!(self.ty.kind(&Interner), TyKind::Tuple(0, ..))
2343 pub fn is_bool(&self) -> bool {
2344 matches!(self.ty.kind(&Interner), TyKind::Scalar(Scalar::Bool))
2347 pub fn is_never(&self) -> bool {
2348 matches!(self.ty.kind(&Interner), TyKind::Never)
2351 pub fn is_mutable_reference(&self) -> bool {
2352 matches!(self.ty.kind(&Interner), TyKind::Ref(hir_ty::Mutability::Mut, ..))
2355 pub fn is_reference(&self) -> bool {
2356 matches!(self.ty.kind(&Interner), TyKind::Ref(..))
2359 pub fn is_usize(&self) -> bool {
2360 matches!(self.ty.kind(&Interner), TyKind::Scalar(Scalar::Uint(UintTy::Usize)))
2363 pub fn remove_ref(&self) -> Option<Type> {
2364 match &self.ty.kind(&Interner) {
2365 TyKind::Ref(.., ty) => Some(self.derived(ty.clone())),
2370 pub fn strip_references(&self) -> Type {
2371 self.derived(self.ty.strip_references().clone())
2374 pub fn is_unknown(&self) -> bool {
2375 self.ty.is_unknown()
2378 /// Checks that particular type `ty` implements `std::future::Future`.
2379 /// This function is used in `.await` syntax completion.
2380 pub fn impls_future(&self, db: &dyn HirDatabase) -> bool {
2381 // No special case for the type of async block, since Chalk can figure it out.
2383 let krate = self.krate;
2385 let std_future_trait =
2386 db.lang_item(krate, "future_trait".into()).and_then(|it| it.as_trait());
2387 let std_future_trait = match std_future_trait {
2389 None => return false,
2393 Canonical { value: self.ty.clone(), binders: CanonicalVarKinds::empty(&Interner) };
2394 method_resolution::implements_trait(
2403 /// Checks that particular type `ty` implements `std::ops::FnOnce`.
2405 /// This function can be used to check if a particular type is callable, since FnOnce is a
2406 /// supertrait of Fn and FnMut, so all callable types implements at least FnOnce.
2407 pub fn impls_fnonce(&self, db: &dyn HirDatabase) -> bool {
2408 let krate = self.krate;
2410 let fnonce_trait = match FnTrait::FnOnce.get_id(db, krate) {
2412 None => return false,
2416 Canonical { value: self.ty.clone(), binders: CanonicalVarKinds::empty(&Interner) };
2417 method_resolution::implements_trait_unique(
2426 pub fn impls_trait(&self, db: &dyn HirDatabase, trait_: Trait, args: &[Type]) -> bool {
2427 let trait_ref = TyBuilder::trait_ref(db, trait_.id)
2428 .push(self.ty.clone())
2429 .fill(args.iter().map(|t| t.ty.clone()))
2432 let goal = Canonical {
2433 value: hir_ty::InEnvironment::new(&self.env.env, trait_ref.cast(&Interner)),
2434 binders: CanonicalVarKinds::empty(&Interner),
2437 db.trait_solve(self.krate, goal).is_some()
2440 pub fn normalize_trait_assoc_type(
2442 db: &dyn HirDatabase,
2446 let projection = TyBuilder::assoc_type_projection(db, alias.id)
2447 .push(self.ty.clone())
2448 .fill(args.iter().map(|t| t.ty.clone()))
2450 let goal = hir_ty::make_canonical(
2454 alias: AliasTy::Projection(projection),
2455 ty: TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0))
2460 [TyVariableKind::General].into_iter(),
2463 match db.trait_solve(self.krate, goal)? {
2464 Solution::Unique(s) => s
2467 .as_slice(&Interner)
2469 .map(|ty| self.derived(ty.assert_ty_ref(&Interner).clone())),
2470 Solution::Ambig(_) => None,
2474 pub fn is_copy(&self, db: &dyn HirDatabase) -> bool {
2475 let lang_item = db.lang_item(self.krate, SmolStr::new("copy"));
2476 let copy_trait = match lang_item {
2477 Some(LangItemTarget::TraitId(it)) => it,
2480 self.impls_trait(db, copy_trait.into(), &[])
2483 pub fn as_callable(&self, db: &dyn HirDatabase) -> Option<Callable> {
2484 let def = self.ty.callable_def(db);
2486 let sig = self.ty.callable_sig(db)?;
2487 Some(Callable { ty: self.clone(), sig, def, is_bound_method: false })
2490 pub fn is_closure(&self) -> bool {
2491 matches!(&self.ty.kind(&Interner), TyKind::Closure { .. })
2494 pub fn is_fn(&self) -> bool {
2495 matches!(&self.ty.kind(&Interner), TyKind::FnDef(..) | TyKind::Function { .. })
2498 pub fn is_packed(&self, db: &dyn HirDatabase) -> bool {
2499 let adt_id = match *self.ty.kind(&Interner) {
2500 TyKind::Adt(hir_ty::AdtId(adt_id), ..) => adt_id,
2504 let adt = adt_id.into();
2506 Adt::Struct(s) => matches!(s.repr(db), Some(ReprKind::Packed)),
2511 pub fn is_raw_ptr(&self) -> bool {
2512 matches!(&self.ty.kind(&Interner), TyKind::Raw(..))
2515 pub fn contains_unknown(&self) -> bool {
2516 return go(&self.ty);
2518 fn go(ty: &Ty) -> bool {
2519 match ty.kind(&Interner) {
2520 TyKind::Error => true,
2522 TyKind::Adt(_, substs)
2523 | TyKind::AssociatedType(_, substs)
2524 | TyKind::Tuple(_, substs)
2525 | TyKind::OpaqueType(_, substs)
2526 | TyKind::FnDef(_, substs)
2527 | TyKind::Closure(_, substs) => {
2528 substs.iter(&Interner).filter_map(|a| a.ty(&Interner)).any(go)
2531 TyKind::Array(_ty, len) if len.is_unknown() => true,
2532 TyKind::Array(ty, _)
2534 | TyKind::Raw(_, ty)
2535 | TyKind::Ref(_, _, ty) => go(ty),
2540 | TyKind::Placeholder(_)
2541 | TyKind::BoundVar(_)
2542 | TyKind::InferenceVar(_, _)
2544 | TyKind::Function(_)
2546 | TyKind::Foreign(_)
2547 | TyKind::Generator(..)
2548 | TyKind::GeneratorWitness(..) => false,
2553 pub fn fields(&self, db: &dyn HirDatabase) -> Vec<(Field, Type)> {
2554 let (variant_id, substs) = match self.ty.kind(&Interner) {
2555 TyKind::Adt(hir_ty::AdtId(AdtId::StructId(s)), substs) => ((*s).into(), substs),
2556 TyKind::Adt(hir_ty::AdtId(AdtId::UnionId(u)), substs) => ((*u).into(), substs),
2557 _ => return Vec::new(),
2560 db.field_types(variant_id)
2562 .map(|(local_id, ty)| {
2563 let def = Field { parent: variant_id.into(), id: local_id };
2564 let ty = ty.clone().substitute(&Interner, substs);
2565 (def, self.derived(ty))
2570 pub fn tuple_fields(&self, _db: &dyn HirDatabase) -> Vec<Type> {
2571 if let TyKind::Tuple(_, substs) = &self.ty.kind(&Interner) {
2574 .map(|ty| self.derived(ty.assert_ty_ref(&Interner).clone()))
2581 pub fn autoderef<'a>(&'a self, db: &'a dyn HirDatabase) -> impl Iterator<Item = Type> + 'a {
2582 // There should be no inference vars in types passed here
2583 let canonical = hir_ty::replace_errors_with_variables(&self.ty);
2584 let environment = self.env.env.clone();
2585 let ty = InEnvironment { goal: canonical, environment };
2586 autoderef(db, Some(self.krate), ty)
2587 .map(|canonical| canonical.value)
2588 .map(move |ty| self.derived(ty))
2591 // This would be nicer if it just returned an iterator, but that runs into
2592 // lifetime problems, because we need to borrow temp `CrateImplDefs`.
2593 pub fn iterate_assoc_items<T>(
2595 db: &dyn HirDatabase,
2597 mut callback: impl FnMut(AssocItem) -> Option<T>,
2599 let mut slot = None;
2600 self.iterate_assoc_items_dyn(db, krate, &mut |assoc_item_id| {
2601 slot = callback(assoc_item_id.into());
2607 fn iterate_assoc_items_dyn(
2609 db: &dyn HirDatabase,
2611 callback: &mut dyn FnMut(AssocItemId) -> bool,
2613 let def_crates = match method_resolution::def_crates(db, &self.ty, krate.id) {
2617 for krate in def_crates {
2618 let impls = db.inherent_impls_in_crate(krate);
2620 for impl_def in impls.for_self_ty(&self.ty) {
2621 for &item in db.impl_data(*impl_def).items.iter() {
2630 pub fn type_arguments(&self) -> impl Iterator<Item = Type> + '_ {
2635 .flat_map(|(_, substs)| substs.iter(&Interner))
2636 .filter_map(|arg| arg.ty(&Interner).cloned())
2637 .map(move |ty| self.derived(ty))
2640 pub fn iterate_method_candidates<T>(
2642 db: &dyn HirDatabase,
2644 traits_in_scope: &FxHashSet<TraitId>,
2645 name: Option<&Name>,
2646 mut callback: impl FnMut(Type, Function) -> Option<T>,
2648 let _p = profile::span("iterate_method_candidates");
2649 let mut slot = None;
2650 self.iterate_method_candidates_dyn(
2655 &mut |ty, assoc_item_id| {
2656 if let AssocItemId::FunctionId(func) = assoc_item_id {
2657 if let Some(res) = callback(self.derived(ty.clone()), func.into()) {
2659 return ControlFlow::Break(());
2662 ControlFlow::Continue(())
2668 fn iterate_method_candidates_dyn(
2670 db: &dyn HirDatabase,
2672 traits_in_scope: &FxHashSet<TraitId>,
2673 name: Option<&Name>,
2674 callback: &mut dyn FnMut(&Ty, AssocItemId) -> ControlFlow<()>,
2676 // There should be no inference vars in types passed here
2677 let canonical = hir_ty::replace_errors_with_variables(&self.ty);
2679 let env = self.env.clone();
2680 let krate = krate.id;
2682 method_resolution::iterate_method_candidates_dyn(
2690 method_resolution::LookupMode::MethodCall,
2691 &mut |ty, id| callback(&ty.value, id),
2695 pub fn iterate_path_candidates<T>(
2697 db: &dyn HirDatabase,
2699 traits_in_scope: &FxHashSet<TraitId>,
2700 name: Option<&Name>,
2701 mut callback: impl FnMut(Type, AssocItem) -> Option<T>,
2703 let _p = profile::span("iterate_path_candidates");
2704 let mut slot = None;
2705 self.iterate_path_candidates_dyn(
2710 &mut |ty, assoc_item_id| {
2711 if let Some(res) = callback(self.derived(ty.clone()), assoc_item_id.into()) {
2713 return ControlFlow::Break(());
2715 ControlFlow::Continue(())
2721 fn iterate_path_candidates_dyn(
2723 db: &dyn HirDatabase,
2725 traits_in_scope: &FxHashSet<TraitId>,
2726 name: Option<&Name>,
2727 callback: &mut dyn FnMut(&Ty, AssocItemId) -> ControlFlow<()>,
2729 let canonical = hir_ty::replace_errors_with_variables(&self.ty);
2731 let env = self.env.clone();
2732 let krate = krate.id;
2734 method_resolution::iterate_method_candidates_dyn(
2742 method_resolution::LookupMode::Path,
2743 &mut |ty, id| callback(&ty.value, id),
2747 pub fn as_adt(&self) -> Option<Adt> {
2748 let (adt, _subst) = self.ty.as_adt()?;
2752 pub fn as_builtin(&self) -> Option<BuiltinType> {
2753 self.ty.as_builtin().map(|inner| BuiltinType { inner })
2756 pub fn as_dyn_trait(&self) -> Option<Trait> {
2757 self.ty.dyn_trait().map(Into::into)
2760 /// If a type can be represented as `dyn Trait`, returns all traits accessible via this type,
2761 /// or an empty iterator otherwise.
2762 pub fn applicable_inherent_traits<'a>(
2764 db: &'a dyn HirDatabase,
2765 ) -> impl Iterator<Item = Trait> + 'a {
2766 let _p = profile::span("applicable_inherent_traits");
2768 .filter_map(|derefed_type| derefed_type.ty.dyn_trait())
2769 .flat_map(move |dyn_trait_id| hir_ty::all_super_traits(db.upcast(), dyn_trait_id))
2773 pub fn as_impl_traits(&self, db: &dyn HirDatabase) -> Option<Vec<Trait>> {
2774 self.ty.impl_trait_bounds(db).map(|it| {
2776 .filter_map(|pred| match pred.skip_binders() {
2777 hir_ty::WhereClause::Implemented(trait_ref) => {
2778 Some(Trait::from(trait_ref.hir_trait_id()))
2786 pub fn as_associated_type_parent_trait(&self, db: &dyn HirDatabase) -> Option<Trait> {
2787 self.ty.associated_type_parent_trait(db).map(Into::into)
2790 fn derived(&self, ty: Ty) -> Type {
2791 Type { krate: self.krate, env: self.env.clone(), ty }
2794 pub fn walk(&self, db: &dyn HirDatabase, mut cb: impl FnMut(Type)) {
2795 // TypeWalk::walk for a Ty at first visits parameters and only after that the Ty itself.
2796 // We need a different order here.
2799 db: &dyn HirDatabase,
2801 substs: &Substitution,
2802 cb: &mut impl FnMut(Type),
2804 for ty in substs.iter(&Interner).filter_map(|a| a.ty(&Interner)) {
2805 walk_type(db, &type_.derived(ty.clone()), cb);
2810 db: &dyn HirDatabase,
2812 bounds: &[QuantifiedWhereClause],
2813 cb: &mut impl FnMut(Type),
2815 for pred in bounds {
2816 if let WhereClause::Implemented(trait_ref) = pred.skip_binders() {
2818 // skip the self type. it's likely the type we just got the bounds from
2823 .filter_map(|a| a.ty(&Interner))
2825 walk_type(db, &type_.derived(ty.clone()), cb);
2831 fn walk_type(db: &dyn HirDatabase, type_: &Type, cb: &mut impl FnMut(Type)) {
2832 let ty = type_.ty.strip_references();
2833 match ty.kind(&Interner) {
2834 TyKind::Adt(_, substs) => {
2835 cb(type_.derived(ty.clone()));
2836 walk_substs(db, type_, substs, cb);
2838 TyKind::AssociatedType(_, substs) => {
2839 if ty.associated_type_parent_trait(db).is_some() {
2840 cb(type_.derived(ty.clone()));
2842 walk_substs(db, type_, substs, cb);
2844 TyKind::OpaqueType(_, subst) => {
2845 if let Some(bounds) = ty.impl_trait_bounds(db) {
2846 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
2849 walk_substs(db, type_, subst, cb);
2851 TyKind::Alias(AliasTy::Opaque(opaque_ty)) => {
2852 if let Some(bounds) = ty.impl_trait_bounds(db) {
2853 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
2856 walk_substs(db, type_, &opaque_ty.substitution, cb);
2858 TyKind::Placeholder(_) => {
2859 if let Some(bounds) = ty.impl_trait_bounds(db) {
2860 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
2863 TyKind::Dyn(bounds) => {
2866 &type_.derived(ty.clone()),
2867 bounds.bounds.skip_binders().interned(),
2872 TyKind::Ref(_, _, ty)
2873 | TyKind::Raw(_, ty)
2874 | TyKind::Array(ty, _)
2875 | TyKind::Slice(ty) => {
2876 walk_type(db, &type_.derived(ty.clone()), cb);
2879 TyKind::FnDef(_, substs)
2880 | TyKind::Tuple(_, substs)
2881 | TyKind::Closure(.., substs) => {
2882 walk_substs(db, type_, substs, cb);
2884 TyKind::Function(hir_ty::FnPointer { substitution, .. }) => {
2885 walk_substs(db, type_, &substitution.0, cb);
2892 walk_type(db, self, &mut cb);
2895 pub fn could_unify_with(&self, db: &dyn HirDatabase, other: &Type) -> bool {
2896 let tys = hir_ty::replace_errors_with_variables(&(self.ty.clone(), other.ty.clone()));
2897 could_unify(db, self.env.clone(), &tys)
2903 pub struct Callable {
2906 def: Option<CallableDefId>,
2907 pub(crate) is_bound_method: bool,
2910 pub enum CallableKind {
2912 TupleStruct(Struct),
2913 TupleEnumVariant(Variant),
2918 pub fn kind(&self) -> CallableKind {
2920 Some(CallableDefId::FunctionId(it)) => CallableKind::Function(it.into()),
2921 Some(CallableDefId::StructId(it)) => CallableKind::TupleStruct(it.into()),
2922 Some(CallableDefId::EnumVariantId(it)) => CallableKind::TupleEnumVariant(it.into()),
2923 None => CallableKind::Closure,
2926 pub fn receiver_param(&self, db: &dyn HirDatabase) -> Option<ast::SelfParam> {
2927 let func = match self.def {
2928 Some(CallableDefId::FunctionId(it)) if self.is_bound_method => it,
2931 let src = func.lookup(db.upcast()).source(db.upcast());
2932 let param_list = src.value.param_list()?;
2933 param_list.self_param()
2935 pub fn n_params(&self) -> usize {
2936 self.sig.params().len() - if self.is_bound_method { 1 } else { 0 }
2940 db: &dyn HirDatabase,
2941 ) -> Vec<(Option<Either<ast::SelfParam, ast::Pat>>, Type)> {
2946 .skip(if self.is_bound_method { 1 } else { 0 })
2947 .map(|ty| self.ty.derived(ty.clone()));
2948 let patterns = match self.def {
2949 Some(CallableDefId::FunctionId(func)) => {
2950 let src = func.lookup(db.upcast()).source(db.upcast());
2951 src.value.param_list().map(|param_list| {
2954 .map(|it| Some(Either::Left(it)))
2955 .filter(|_| !self.is_bound_method)
2957 .chain(param_list.params().map(|it| it.pat().map(Either::Right)))
2962 patterns.into_iter().flatten().chain(iter::repeat(None)).zip(types).collect()
2964 pub fn return_type(&self) -> Type {
2965 self.ty.derived(self.sig.ret().clone())
2970 #[derive(Debug, PartialEq, Eq, Hash)]
2972 ModuleDef(ModuleDef),
2974 GenericParam(GenericParam),
2983 pub fn all_items(def: PerNs) -> ArrayVec<Self, 3> {
2984 let mut items = ArrayVec::new();
2986 match (def.take_types(), def.take_values()) {
2987 (Some(m1), None) => items.push(ScopeDef::ModuleDef(m1.into())),
2988 (None, Some(m2)) => items.push(ScopeDef::ModuleDef(m2.into())),
2989 (Some(m1), Some(m2)) => {
2990 // Some items, like unit structs and enum variants, are
2991 // returned as both a type and a value. Here we want
2992 // to de-duplicate them.
2994 items.push(ScopeDef::ModuleDef(m1.into()));
2995 items.push(ScopeDef::ModuleDef(m2.into()));
2997 items.push(ScopeDef::ModuleDef(m1.into()));
3003 if let Some(macro_def_id) = def.take_macros() {
3004 items.push(ScopeDef::MacroDef(macro_def_id.into()));
3007 if items.is_empty() {
3008 items.push(ScopeDef::Unknown);
3014 pub fn attrs(&self, db: &dyn HirDatabase) -> Option<AttrsWithOwner> {
3016 ScopeDef::ModuleDef(it) => it.attrs(db),
3017 ScopeDef::MacroDef(it) => Some(it.attrs(db)),
3018 ScopeDef::GenericParam(it) => Some(it.attrs(db)),
3019 ScopeDef::ImplSelfType(_)
3020 | ScopeDef::AdtSelfType(_)
3021 | ScopeDef::Local(_)
3022 | ScopeDef::Label(_)
3023 | ScopeDef::Unknown => None,
3027 pub fn krate(&self, db: &dyn HirDatabase) -> Option<Crate> {
3029 ScopeDef::ModuleDef(it) => it.module(db).map(|m| m.krate()),
3030 ScopeDef::MacroDef(it) => it.module(db).map(|m| m.krate()),
3031 ScopeDef::GenericParam(it) => Some(it.module(db).krate()),
3032 ScopeDef::ImplSelfType(_) => None,
3033 ScopeDef::AdtSelfType(it) => Some(it.module(db).krate()),
3034 ScopeDef::Local(it) => Some(it.module(db).krate()),
3035 ScopeDef::Label(it) => Some(it.module(db).krate()),
3036 ScopeDef::Unknown => None,
3041 impl From<ItemInNs> for ScopeDef {
3042 fn from(item: ItemInNs) -> Self {
3044 ItemInNs::Types(id) => ScopeDef::ModuleDef(id),
3045 ItemInNs::Values(id) => ScopeDef::ModuleDef(id),
3046 ItemInNs::Macros(id) => ScopeDef::MacroDef(id),
3051 pub trait HasVisibility {
3052 fn visibility(&self, db: &dyn HirDatabase) -> Visibility;
3053 fn is_visible_from(&self, db: &dyn HirDatabase, module: Module) -> bool {
3054 let vis = self.visibility(db);
3055 vis.is_visible_from(db.upcast(), module.id)
3059 /// Trait for obtaining the defining crate of an item.
3060 pub trait HasCrate {
3061 fn krate(&self, db: &dyn HirDatabase) -> Crate;
3064 impl<T: hir_def::HasModule> HasCrate for T {
3065 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3066 self.module(db.upcast()).krate().into()
3070 impl HasCrate for AssocItem {
3071 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3072 self.module(db).krate()
3076 impl HasCrate for Field {
3077 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3078 self.parent_def(db).module(db).krate()
3082 impl HasCrate for Function {
3083 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3084 self.module(db).krate()
3088 impl HasCrate for Const {
3089 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3090 self.module(db).krate()
3094 impl HasCrate for TypeAlias {
3095 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3096 self.module(db).krate()
3100 impl HasCrate for Type {
3101 fn krate(&self, _db: &dyn HirDatabase) -> Crate {