1 //! HIR (previously known as descriptors) provides a high-level object oriented
2 //! access to Rust code.
4 //! The principal difference between HIR and syntax trees is that HIR is bound
5 //! to a particular crate instance. That is, it has cfg flags and features
6 //! applied. So, the relation between syntax and HIR is many-to-one.
8 //! HIR is the public API of the all of the compiler logic above syntax trees.
9 //! It is written in "OO" style. Each type is self contained (as in, it knows it's
10 //! parents and full context). It should be "clean code".
12 //! `hir_*` crates are the implementation of the compiler logic.
13 //! They are written in "ECS" style, with relatively little abstractions.
14 //! Many types are not self-contained, and explicitly use local indexes, arenas, etc.
16 //! `hir` is what insulates the "we don't know how to actually write an incremental compiler"
17 //! from the ide with completions, hovers, etc. It is a (soft, internal) boundary:
18 //! <https://www.tedinski.com/2018/02/06/system-boundaries.html>.
20 #![recursion_limit = "512"]
35 use std::{collections::HashMap, iter, ops::ControlFlow, sync::Arc};
37 use arrayvec::ArrayVec;
38 use base_db::{CrateDisplayName, CrateId, CrateOrigin, Edition, FileId};
41 adt::{ReprKind, VariantData},
42 body::{BodyDiagnostic, SyntheticSyntax},
43 expr::{BindingAnnotation, LabelId, Pat, PatId},
44 item_tree::ItemTreeNode,
45 lang_item::LangItemTarget,
46 nameres::{self, diagnostics::DefDiagnostic},
48 resolver::{HasResolver, Resolver},
50 AdtId, AssocItemId, AssocItemLoc, AttrDefId, ConstId, ConstParamId, DefWithBodyId, EnumId,
51 FunctionId, GenericDefId, HasModule, ImplId, ItemContainerId, LifetimeParamId,
52 LocalEnumVariantId, LocalFieldId, Lookup, ModuleId, StaticId, StructId, TraitId, TypeAliasId,
55 use hir_expand::{name::name, MacroCallKind, MacroDefId, MacroDefKind};
58 consteval::{eval_const, ComputedExpr, ConstEvalCtx, ConstEvalError, ConstExt},
60 diagnostics::BodyValidationDiagnostic,
61 method_resolution::{self, TyFingerprint},
65 AliasEq, AliasTy, BoundVar, CallableDefId, CallableSig, Canonical, CanonicalVarKinds, Cast,
66 DebruijnIndex, InEnvironment, Interner, QuantifiedWhereClause, Scalar, Solution, Substitution,
67 TraitEnvironment, TraitRefExt, Ty, TyBuilder, TyDefId, TyExt, TyKind, TyVariableKind,
70 use itertools::Itertools;
71 use nameres::diagnostics::DefDiagnosticKind;
72 use once_cell::unsync::Lazy;
73 use rustc_hash::FxHashSet;
74 use stdx::{format_to, impl_from};
76 ast::{self, HasAttrs as _, HasDocComments, HasName},
77 AstNode, AstPtr, SmolStr, SyntaxKind, SyntaxNodePtr,
79 use tt::{Ident, Leaf, Literal, TokenTree};
81 use crate::db::{DefDatabase, HirDatabase};
84 attrs::{HasAttrs, Namespace},
86 AddReferenceHere, AnyDiagnostic, BreakOutsideOfLoop, InactiveCode, IncorrectCase,
87 InvalidDeriveTarget, MacroError, MalformedDerive, MismatchedArgCount, MissingFields,
88 MissingMatchArms, MissingOkOrSomeInTailExpr, MissingUnsafe, NoSuchField,
89 RemoveThisSemicolon, ReplaceFilterMapNextWithFindMap, UnimplementedBuiltinMacro,
90 UnresolvedExternCrate, UnresolvedImport, UnresolvedMacroCall, UnresolvedModule,
93 has_source::HasSource,
94 semantics::{PathResolution, Semantics, SemanticsScope, TypeInfo},
97 // Be careful with these re-exports.
99 // `hir` is the boundary between the compiler and the IDE. It should try hard to
100 // isolate the compiler from the ide, to allow the two to be refactored
101 // independently. Re-exporting something from the compiler is the sure way to
102 // breach the boundary.
104 // Generally, a refactoring which *removes* a name from this list is a good
107 cfg::{CfgAtom, CfgExpr, CfgOptions},
110 attr::{Attr, Attrs, AttrsWithOwner, Documentation},
111 builtin_attr::AttributeTemplate,
112 find_path::PrefixKind,
114 nameres::ModuleSource,
115 path::{ModPath, PathKind},
116 type_ref::{Mutability, TypeRef},
117 visibility::Visibility,
121 ExpandResult, HirFileId, InFile, MacroFile, Origin,
123 hir_ty::display::HirDisplay,
126 // These are negative re-exports: pub using these names is forbidden, they
127 // should remain private to hir internals.
131 hir_expand::{hygiene::Hygiene, name::AsName},
134 /// hir::Crate describes a single crate. It's the main interface with which
135 /// a crate's dependencies interact. Mostly, it should be just a proxy for the
137 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
139 pub(crate) id: CrateId,
143 pub struct CrateDependency {
149 pub fn origin(self, db: &dyn HirDatabase) -> CrateOrigin {
150 db.crate_graph()[self.id].origin.clone()
153 pub fn dependencies(self, db: &dyn HirDatabase) -> Vec<CrateDependency> {
154 db.crate_graph()[self.id]
158 let krate = Crate { id: dep.crate_id };
159 let name = dep.as_name();
160 CrateDependency { krate, name }
165 pub fn reverse_dependencies(self, db: &dyn HirDatabase) -> Vec<Crate> {
166 let crate_graph = db.crate_graph();
170 crate_graph[krate].dependencies.iter().any(|it| it.crate_id == self.id)
172 .map(|id| Crate { id })
176 pub fn transitive_reverse_dependencies(self, db: &dyn HirDatabase) -> Vec<Crate> {
177 db.crate_graph().transitive_rev_deps(self.id).into_iter().map(|id| Crate { id }).collect()
180 pub fn root_module(self, db: &dyn HirDatabase) -> Module {
181 let def_map = db.crate_def_map(self.id);
182 Module { id: def_map.module_id(def_map.root()) }
185 pub fn modules(self, db: &dyn HirDatabase) -> Vec<Module> {
186 let def_map = db.crate_def_map(self.id);
187 def_map.modules().map(|(id, _)| def_map.module_id(id).into()).collect()
190 pub fn root_file(self, db: &dyn HirDatabase) -> FileId {
191 db.crate_graph()[self.id].root_file_id
194 pub fn edition(self, db: &dyn HirDatabase) -> Edition {
195 db.crate_graph()[self.id].edition
198 pub fn version(self, db: &dyn HirDatabase) -> Option<String> {
199 db.crate_graph()[self.id].version.clone()
202 pub fn display_name(self, db: &dyn HirDatabase) -> Option<CrateDisplayName> {
203 db.crate_graph()[self.id].display_name.clone()
206 pub fn query_external_importables(
208 db: &dyn DefDatabase,
209 query: import_map::Query,
210 ) -> impl Iterator<Item = Either<ModuleDef, MacroDef>> {
211 let _p = profile::span("query_external_importables");
212 import_map::search_dependencies(db, self.into(), query).into_iter().map(|item| {
213 match ItemInNs::from(item) {
214 ItemInNs::Types(mod_id) | ItemInNs::Values(mod_id) => Either::Left(mod_id),
215 ItemInNs::Macros(mac_id) => Either::Right(mac_id),
220 pub fn all(db: &dyn HirDatabase) -> Vec<Crate> {
221 db.crate_graph().iter().map(|id| Crate { id }).collect()
224 /// Try to get the root URL of the documentation of a crate.
225 pub fn get_html_root_url(self: &Crate, db: &dyn HirDatabase) -> Option<String> {
226 // Look for #![doc(html_root_url = "...")]
227 let attrs = db.attrs(AttrDefId::ModuleId(self.root_module(db).into()));
228 let doc_attr_q = attrs.by_key("doc");
230 if !doc_attr_q.exists() {
234 let doc_url = doc_attr_q.tt_values().map(|tt| {
235 let name = tt.token_trees.iter()
236 .skip_while(|tt| !matches!(tt, TokenTree::Leaf(Leaf::Ident(Ident { text, ..} )) if text == "html_root_url"))
240 Some(TokenTree::Leaf(Leaf::Literal(Literal{ref text, ..}))) => Some(text),
245 doc_url.map(|s| s.trim_matches('"').trim_end_matches('/').to_owned() + "/")
248 pub fn cfg(&self, db: &dyn HirDatabase) -> CfgOptions {
249 db.crate_graph()[self.id].cfg_options.clone()
252 pub fn potential_cfg(&self, db: &dyn HirDatabase) -> CfgOptions {
253 db.crate_graph()[self.id].potential_cfg_options.clone()
257 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
259 pub(crate) id: ModuleId,
262 /// The defs which can be visible in the module.
263 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
268 // Can't be directly declared, but can be imported.
273 TypeAlias(TypeAlias),
274 BuiltinType(BuiltinType),
279 Adt(Struct, Enum, Union),
289 impl From<VariantDef> for ModuleDef {
290 fn from(var: VariantDef) -> Self {
292 VariantDef::Struct(t) => Adt::from(t).into(),
293 VariantDef::Union(t) => Adt::from(t).into(),
294 VariantDef::Variant(t) => t.into(),
300 pub fn module(self, db: &dyn HirDatabase) -> Option<Module> {
302 ModuleDef::Module(it) => it.parent(db),
303 ModuleDef::Function(it) => Some(it.module(db)),
304 ModuleDef::Adt(it) => Some(it.module(db)),
305 ModuleDef::Variant(it) => Some(it.module(db)),
306 ModuleDef::Const(it) => Some(it.module(db)),
307 ModuleDef::Static(it) => Some(it.module(db)),
308 ModuleDef::Trait(it) => Some(it.module(db)),
309 ModuleDef::TypeAlias(it) => Some(it.module(db)),
310 ModuleDef::BuiltinType(_) => None,
314 pub fn canonical_path(&self, db: &dyn HirDatabase) -> Option<String> {
315 let mut segments = vec![self.name(db)?];
316 for m in self.module(db)?.path_to_root(db) {
317 segments.extend(m.name(db))
320 Some(segments.into_iter().join("::"))
323 pub fn canonical_module_path(
325 db: &dyn HirDatabase,
326 ) -> Option<impl Iterator<Item = Module>> {
327 self.module(db).map(|it| it.path_to_root(db).into_iter().rev())
330 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
331 let name = match self {
332 ModuleDef::Module(it) => it.name(db)?,
333 ModuleDef::Const(it) => it.name(db)?,
334 ModuleDef::Adt(it) => it.name(db),
335 ModuleDef::Trait(it) => it.name(db),
336 ModuleDef::Function(it) => it.name(db),
337 ModuleDef::Variant(it) => it.name(db),
338 ModuleDef::TypeAlias(it) => it.name(db),
339 ModuleDef::Static(it) => it.name(db),
340 ModuleDef::BuiltinType(it) => it.name(),
345 pub fn diagnostics(self, db: &dyn HirDatabase) -> Vec<AnyDiagnostic> {
346 let id = match self {
347 ModuleDef::Adt(it) => match it {
348 Adt::Struct(it) => it.id.into(),
349 Adt::Enum(it) => it.id.into(),
350 Adt::Union(it) => it.id.into(),
352 ModuleDef::Trait(it) => it.id.into(),
353 ModuleDef::Function(it) => it.id.into(),
354 ModuleDef::TypeAlias(it) => it.id.into(),
355 ModuleDef::Module(it) => it.id.into(),
356 ModuleDef::Const(it) => it.id.into(),
357 ModuleDef::Static(it) => it.id.into(),
358 _ => return Vec::new(),
361 let module = match self.module(db) {
363 None => return Vec::new(),
366 let mut acc = Vec::new();
368 match self.as_def_with_body() {
370 def.diagnostics(db, &mut acc);
373 for diag in hir_ty::diagnostics::incorrect_case(db, module.id.krate(), id) {
374 acc.push(diag.into())
382 pub fn as_def_with_body(self) -> Option<DefWithBody> {
384 ModuleDef::Function(it) => Some(it.into()),
385 ModuleDef::Const(it) => Some(it.into()),
386 ModuleDef::Static(it) => Some(it.into()),
390 | ModuleDef::Variant(_)
391 | ModuleDef::Trait(_)
392 | ModuleDef::TypeAlias(_)
393 | ModuleDef::BuiltinType(_) => None,
397 pub fn attrs(&self, db: &dyn HirDatabase) -> Option<AttrsWithOwner> {
399 ModuleDef::Module(it) => it.attrs(db),
400 ModuleDef::Function(it) => it.attrs(db),
401 ModuleDef::Adt(it) => it.attrs(db),
402 ModuleDef::Variant(it) => it.attrs(db),
403 ModuleDef::Const(it) => it.attrs(db),
404 ModuleDef::Static(it) => it.attrs(db),
405 ModuleDef::Trait(it) => it.attrs(db),
406 ModuleDef::TypeAlias(it) => it.attrs(db),
407 ModuleDef::BuiltinType(_) => return None,
412 impl HasVisibility for ModuleDef {
413 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
415 ModuleDef::Module(it) => it.visibility(db),
416 ModuleDef::Function(it) => it.visibility(db),
417 ModuleDef::Adt(it) => it.visibility(db),
418 ModuleDef::Const(it) => it.visibility(db),
419 ModuleDef::Static(it) => it.visibility(db),
420 ModuleDef::Trait(it) => it.visibility(db),
421 ModuleDef::TypeAlias(it) => it.visibility(db),
422 ModuleDef::Variant(it) => it.visibility(db),
423 ModuleDef::BuiltinType(_) => Visibility::Public,
429 /// Name of this module.
430 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
431 let def_map = self.id.def_map(db.upcast());
432 let parent = def_map[self.id.local_id].parent?;
433 def_map[parent].children.iter().find_map(|(name, module_id)| {
434 if *module_id == self.id.local_id {
442 /// Returns the crate this module is part of.
443 pub fn krate(self) -> Crate {
444 Crate { id: self.id.krate() }
447 /// Topmost parent of this module. Every module has a `crate_root`, but some
448 /// might be missing `krate`. This can happen if a module's file is not included
449 /// in the module tree of any target in `Cargo.toml`.
450 pub fn crate_root(self, db: &dyn HirDatabase) -> Module {
451 let def_map = db.crate_def_map(self.id.krate());
452 Module { id: def_map.module_id(def_map.root()) }
455 /// Iterates over all child modules.
456 pub fn children(self, db: &dyn HirDatabase) -> impl Iterator<Item = Module> {
457 let def_map = self.id.def_map(db.upcast());
458 let children = def_map[self.id.local_id]
461 .map(|(_, module_id)| Module { id: def_map.module_id(*module_id) })
462 .collect::<Vec<_>>();
466 /// Finds a parent module.
467 pub fn parent(self, db: &dyn HirDatabase) -> Option<Module> {
468 // FIXME: handle block expressions as modules (their parent is in a different DefMap)
469 let def_map = self.id.def_map(db.upcast());
470 let parent_id = def_map[self.id.local_id].parent?;
471 Some(Module { id: def_map.module_id(parent_id) })
474 pub fn path_to_root(self, db: &dyn HirDatabase) -> Vec<Module> {
475 let mut res = vec![self];
477 while let Some(next) = curr.parent(db) {
484 /// Returns a `ModuleScope`: a set of items, visible in this module.
487 db: &dyn HirDatabase,
488 visible_from: Option<Module>,
489 ) -> Vec<(Name, ScopeDef)> {
490 self.id.def_map(db.upcast())[self.id.local_id]
493 .filter_map(|(name, def)| {
494 if let Some(m) = visible_from {
496 def.filter_visibility(|vis| vis.is_visible_from(db.upcast(), m.id));
497 if filtered.is_none() && !def.is_none() {
500 Some((name, filtered))
506 .flat_map(|(name, def)| {
507 ScopeDef::all_items(def).into_iter().map(move |item| (name.clone(), item))
512 pub fn diagnostics(self, db: &dyn HirDatabase, acc: &mut Vec<AnyDiagnostic>) {
513 let _p = profile::span("Module::diagnostics").detail(|| {
514 format!("{:?}", self.name(db).map_or("<unknown>".into(), |name| name.to_string()))
516 let def_map = self.id.def_map(db.upcast());
517 for diag in def_map.diagnostics() {
518 if diag.in_module != self.id.local_id {
519 // FIXME: This is accidentally quadratic.
522 emit_def_diagnostic(db, acc, diag);
524 for decl in self.declarations(db) {
526 ModuleDef::Module(m) => {
527 // Only add diagnostics from inline modules
528 if def_map[m.id.local_id].origin.is_inline() {
529 m.diagnostics(db, acc)
532 _ => acc.extend(decl.diagnostics(db)),
536 for impl_def in self.impl_defs(db) {
537 for item in impl_def.items(db) {
538 let def: DefWithBody = match item {
539 AssocItem::Function(it) => it.into(),
540 AssocItem::Const(it) => it.into(),
541 AssocItem::TypeAlias(_) => continue,
544 def.diagnostics(db, acc);
549 pub fn declarations(self, db: &dyn HirDatabase) -> Vec<ModuleDef> {
550 let def_map = self.id.def_map(db.upcast());
551 let scope = &def_map[self.id.local_id].scope;
554 .map(ModuleDef::from)
555 .chain(scope.unnamed_consts().map(|id| ModuleDef::Const(Const::from(id))))
559 pub fn impl_defs(self, db: &dyn HirDatabase) -> Vec<Impl> {
560 let def_map = self.id.def_map(db.upcast());
561 def_map[self.id.local_id].scope.impls().map(Impl::from).collect()
564 /// Finds a path that can be used to refer to the given item from within
565 /// this module, if possible.
566 pub fn find_use_path(self, db: &dyn DefDatabase, item: impl Into<ItemInNs>) -> Option<ModPath> {
567 hir_def::find_path::find_path(db, item.into().into(), self.into())
570 /// Finds a path that can be used to refer to the given item from within
571 /// this module, if possible. This is used for returning import paths for use-statements.
572 pub fn find_use_path_prefixed(
574 db: &dyn DefDatabase,
575 item: impl Into<ItemInNs>,
576 prefix_kind: PrefixKind,
577 ) -> Option<ModPath> {
578 hir_def::find_path::find_path_prefixed(db, item.into().into(), self.into(), prefix_kind)
582 fn emit_def_diagnostic(db: &dyn HirDatabase, acc: &mut Vec<AnyDiagnostic>, diag: &DefDiagnostic) {
584 DefDiagnosticKind::UnresolvedModule { ast: declaration, candidate } => {
585 let decl = declaration.to_node(db.upcast());
588 decl: InFile::new(declaration.file_id, AstPtr::new(&decl)),
589 candidate: candidate.clone(),
594 DefDiagnosticKind::UnresolvedExternCrate { ast } => {
595 let item = ast.to_node(db.upcast());
597 UnresolvedExternCrate { decl: InFile::new(ast.file_id, AstPtr::new(&item)) }.into(),
601 DefDiagnosticKind::UnresolvedImport { id, index } => {
602 let file_id = id.file_id();
603 let item_tree = id.item_tree(db.upcast());
604 let import = &item_tree[id.value];
606 let use_tree = import.use_tree_to_ast(db.upcast(), file_id, *index);
608 UnresolvedImport { decl: InFile::new(file_id, AstPtr::new(&use_tree)) }.into(),
612 DefDiagnosticKind::UnconfiguredCode { ast, cfg, opts } => {
613 let item = ast.to_node(db.upcast());
616 node: ast.with_value(AstPtr::new(&item).into()),
624 DefDiagnosticKind::UnresolvedProcMacro { ast } => {
625 let mut precise_location = None;
626 let (node, name) = match ast {
627 MacroCallKind::FnLike { ast_id, .. } => {
628 let node = ast_id.to_node(db.upcast());
629 (ast_id.with_value(SyntaxNodePtr::from(AstPtr::new(&node))), None)
631 MacroCallKind::Derive { ast_id, derive_name, .. } => {
632 let node = ast_id.to_node(db.upcast());
634 // Compute the precise location of the macro name's token in the derive
636 // FIXME: This does not handle paths to the macro, but neither does the
639 node.attrs().filter_map(|attr| match attr.as_simple_call() {
640 Some((name, args)) if name == "derive" => Some(args),
643 'outer: for attr in derive_attrs {
645 attr.syntax().children_with_tokens().filter_map(|elem| match elem {
646 syntax::NodeOrToken::Node(_) => None,
647 syntax::NodeOrToken::Token(tok) => Some(tok),
649 for token in tokens {
650 if token.kind() == SyntaxKind::IDENT && token.text() == &**derive_name {
651 precise_location = Some(token.text_range());
658 ast_id.with_value(SyntaxNodePtr::from(AstPtr::new(&node))),
659 Some(derive_name.clone()),
662 MacroCallKind::Attr { ast_id, invoc_attr_index, attr_name, .. } => {
663 let node = ast_id.to_node(db.upcast());
665 .doc_comments_and_attrs()
666 .nth((*invoc_attr_index) as usize)
667 .and_then(Either::right)
668 .unwrap_or_else(|| panic!("cannot find attribute #{}", invoc_attr_index));
670 ast_id.with_value(SyntaxNodePtr::from(AstPtr::new(&attr))),
671 Some(attr_name.clone()),
676 UnresolvedProcMacro { node, precise_location, macro_name: name.map(Into::into) }
681 DefDiagnosticKind::UnresolvedMacroCall { ast, path } => {
682 let node = ast.to_node(db.upcast());
684 UnresolvedMacroCall {
685 macro_call: InFile::new(ast.file_id, AstPtr::new(&node)),
692 DefDiagnosticKind::MacroError { ast, message } => {
693 let node = match ast {
694 MacroCallKind::FnLike { ast_id, .. } => {
695 let node = ast_id.to_node(db.upcast());
696 ast_id.with_value(SyntaxNodePtr::from(AstPtr::new(&node)))
698 MacroCallKind::Derive { ast_id, .. } => {
699 // FIXME: point to the attribute instead, this creates very large diagnostics
700 let node = ast_id.to_node(db.upcast());
701 ast_id.with_value(SyntaxNodePtr::from(AstPtr::new(&node)))
703 MacroCallKind::Attr { ast_id, .. } => {
704 // FIXME: point to the attribute instead, this creates very large diagnostics
705 let node = ast_id.to_node(db.upcast());
706 ast_id.with_value(SyntaxNodePtr::from(AstPtr::new(&node)))
709 acc.push(MacroError { node, message: message.clone() }.into());
712 DefDiagnosticKind::UnimplementedBuiltinMacro { ast } => {
713 let node = ast.to_node(db.upcast());
714 // Must have a name, otherwise we wouldn't emit it.
715 let name = node.name().expect("unimplemented builtin macro with no name");
717 UnimplementedBuiltinMacro {
718 node: ast.with_value(SyntaxNodePtr::from(AstPtr::new(&name))),
723 DefDiagnosticKind::InvalidDeriveTarget { ast, id } => {
724 let node = ast.to_node(db.upcast());
725 let derive = node.attrs().nth(*id as usize);
729 InvalidDeriveTarget {
730 node: ast.with_value(SyntaxNodePtr::from(AstPtr::new(&derive))),
735 None => stdx::never!("derive diagnostic on item without derive attribute"),
738 DefDiagnosticKind::MalformedDerive { ast, id } => {
739 let node = ast.to_node(db.upcast());
740 let derive = node.attrs().nth(*id as usize);
745 node: ast.with_value(SyntaxNodePtr::from(AstPtr::new(&derive))),
750 None => stdx::never!("derive diagnostic on item without derive attribute"),
756 impl HasVisibility for Module {
757 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
758 let def_map = self.id.def_map(db.upcast());
759 let module_data = &def_map[self.id.local_id];
760 module_data.visibility
764 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
766 pub(crate) parent: VariantDef,
767 pub(crate) id: LocalFieldId,
770 #[derive(Debug, PartialEq, Eq)]
771 pub enum FieldSource {
772 Named(ast::RecordField),
773 Pos(ast::TupleField),
777 pub fn name(&self, db: &dyn HirDatabase) -> Name {
778 self.parent.variant_data(db).fields()[self.id].name.clone()
781 /// Returns the type as in the signature of the struct (i.e., with
782 /// placeholder types for type parameters). Only use this in the context of
783 /// the field definition.
784 pub fn ty(&self, db: &dyn HirDatabase) -> Type {
785 let var_id = self.parent.into();
786 let generic_def_id: GenericDefId = match self.parent {
787 VariantDef::Struct(it) => it.id.into(),
788 VariantDef::Union(it) => it.id.into(),
789 VariantDef::Variant(it) => it.parent.id.into(),
791 let substs = TyBuilder::type_params_subst(db, generic_def_id);
792 let ty = db.field_types(var_id)[self.id].clone().substitute(Interner, &substs);
793 Type::new(db, self.parent.module(db).id.krate(), var_id, ty)
796 pub fn parent_def(&self, _db: &dyn HirDatabase) -> VariantDef {
801 impl HasVisibility for Field {
802 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
803 let variant_data = self.parent.variant_data(db);
804 let visibility = &variant_data.fields()[self.id].visibility;
805 let parent_id: hir_def::VariantId = self.parent.into();
806 visibility.resolve(db.upcast(), &parent_id.resolver(db.upcast()))
810 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
812 pub(crate) id: StructId,
816 pub fn module(self, db: &dyn HirDatabase) -> Module {
817 Module { id: self.id.lookup(db.upcast()).container }
820 pub fn name(self, db: &dyn HirDatabase) -> Name {
821 db.struct_data(self.id).name.clone()
824 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
825 db.struct_data(self.id)
829 .map(|(id, _)| Field { parent: self.into(), id })
833 pub fn ty(self, db: &dyn HirDatabase) -> Type {
834 Type::from_def(db, self.id.lookup(db.upcast()).container.krate(), self.id)
837 pub fn repr(self, db: &dyn HirDatabase) -> Option<ReprKind> {
838 db.struct_data(self.id).repr.clone()
841 pub fn kind(self, db: &dyn HirDatabase) -> StructKind {
842 self.variant_data(db).kind()
845 fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
846 db.struct_data(self.id).variant_data.clone()
850 impl HasVisibility for Struct {
851 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
852 db.struct_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
856 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
858 pub(crate) id: UnionId,
862 pub fn name(self, db: &dyn HirDatabase) -> Name {
863 db.union_data(self.id).name.clone()
866 pub fn module(self, db: &dyn HirDatabase) -> Module {
867 Module { id: self.id.lookup(db.upcast()).container }
870 pub fn ty(self, db: &dyn HirDatabase) -> Type {
871 Type::from_def(db, self.id.lookup(db.upcast()).container.krate(), self.id)
874 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
875 db.union_data(self.id)
879 .map(|(id, _)| Field { parent: self.into(), id })
883 fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
884 db.union_data(self.id).variant_data.clone()
888 impl HasVisibility for Union {
889 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
890 db.union_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
894 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
896 pub(crate) id: EnumId,
900 pub fn module(self, db: &dyn HirDatabase) -> Module {
901 Module { id: self.id.lookup(db.upcast()).container }
904 pub fn name(self, db: &dyn HirDatabase) -> Name {
905 db.enum_data(self.id).name.clone()
908 pub fn variants(self, db: &dyn HirDatabase) -> Vec<Variant> {
909 db.enum_data(self.id).variants.iter().map(|(id, _)| Variant { parent: self, id }).collect()
912 pub fn ty(self, db: &dyn HirDatabase) -> Type {
913 Type::from_def(db, self.id.lookup(db.upcast()).container.krate(), self.id)
917 impl HasVisibility for Enum {
918 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
919 db.enum_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
923 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
925 pub(crate) parent: Enum,
926 pub(crate) id: LocalEnumVariantId,
930 pub fn module(self, db: &dyn HirDatabase) -> Module {
931 self.parent.module(db)
934 pub fn parent_enum(self, _db: &dyn HirDatabase) -> Enum {
938 pub fn name(self, db: &dyn HirDatabase) -> Name {
939 db.enum_data(self.parent.id).variants[self.id].name.clone()
942 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
943 self.variant_data(db)
946 .map(|(id, _)| Field { parent: self.into(), id })
950 pub fn kind(self, db: &dyn HirDatabase) -> StructKind {
951 self.variant_data(db).kind()
954 pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
955 db.enum_data(self.parent.id).variants[self.id].variant_data.clone()
959 /// Variants inherit visibility from the parent enum.
960 impl HasVisibility for Variant {
961 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
962 self.parent_enum(db).visibility(db)
967 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
973 impl_from!(Struct, Union, Enum for Adt);
976 pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
977 let subst = db.generic_defaults(self.into());
978 subst.iter().any(|ty| ty.skip_binders().is_unknown())
981 /// Turns this ADT into a type. Any type parameters of the ADT will be
982 /// turned into unknown types, which is good for e.g. finding the most
983 /// general set of completions, but will not look very nice when printed.
984 pub fn ty(self, db: &dyn HirDatabase) -> Type {
985 let id = AdtId::from(self);
986 Type::from_def(db, id.module(db.upcast()).krate(), id)
989 pub fn module(self, db: &dyn HirDatabase) -> Module {
991 Adt::Struct(s) => s.module(db),
992 Adt::Union(s) => s.module(db),
993 Adt::Enum(e) => e.module(db),
997 pub fn name(self, db: &dyn HirDatabase) -> Name {
999 Adt::Struct(s) => s.name(db),
1000 Adt::Union(u) => u.name(db),
1001 Adt::Enum(e) => e.name(db),
1006 impl HasVisibility for Adt {
1007 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1009 Adt::Struct(it) => it.visibility(db),
1010 Adt::Union(it) => it.visibility(db),
1011 Adt::Enum(it) => it.visibility(db),
1016 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1017 pub enum VariantDef {
1022 impl_from!(Struct, Union, Variant for VariantDef);
1025 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
1027 VariantDef::Struct(it) => it.fields(db),
1028 VariantDef::Union(it) => it.fields(db),
1029 VariantDef::Variant(it) => it.fields(db),
1033 pub fn module(self, db: &dyn HirDatabase) -> Module {
1035 VariantDef::Struct(it) => it.module(db),
1036 VariantDef::Union(it) => it.module(db),
1037 VariantDef::Variant(it) => it.module(db),
1041 pub fn name(&self, db: &dyn HirDatabase) -> Name {
1043 VariantDef::Struct(s) => s.name(db),
1044 VariantDef::Union(u) => u.name(db),
1045 VariantDef::Variant(e) => e.name(db),
1049 pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
1051 VariantDef::Struct(it) => it.variant_data(db),
1052 VariantDef::Union(it) => it.variant_data(db),
1053 VariantDef::Variant(it) => it.variant_data(db),
1058 /// The defs which have a body.
1059 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1060 pub enum DefWithBody {
1065 impl_from!(Function, Const, Static for DefWithBody);
1068 pub fn module(self, db: &dyn HirDatabase) -> Module {
1070 DefWithBody::Const(c) => c.module(db),
1071 DefWithBody::Function(f) => f.module(db),
1072 DefWithBody::Static(s) => s.module(db),
1076 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1078 DefWithBody::Function(f) => Some(f.name(db)),
1079 DefWithBody::Static(s) => Some(s.name(db)),
1080 DefWithBody::Const(c) => c.name(db),
1084 /// Returns the type this def's body has to evaluate to.
1085 pub fn body_type(self, db: &dyn HirDatabase) -> Type {
1087 DefWithBody::Function(it) => it.ret_type(db),
1088 DefWithBody::Static(it) => it.ty(db),
1089 DefWithBody::Const(it) => it.ty(db),
1093 pub fn diagnostics(self, db: &dyn HirDatabase, acc: &mut Vec<AnyDiagnostic>) {
1094 let krate = self.module(db).id.krate();
1096 let (body, source_map) = db.body_with_source_map(self.into());
1098 for (_, def_map) in body.blocks(db.upcast()) {
1099 for diag in def_map.diagnostics() {
1100 emit_def_diagnostic(db, acc, diag);
1104 for diag in source_map.diagnostics() {
1106 BodyDiagnostic::InactiveCode { node, cfg, opts } => acc.push(
1107 InactiveCode { node: node.clone(), cfg: cfg.clone(), opts: opts.clone() }
1110 BodyDiagnostic::MacroError { node, message } => acc.push(
1112 node: node.clone().map(|it| it.into()),
1113 message: message.to_string(),
1117 BodyDiagnostic::UnresolvedProcMacro { node } => acc.push(
1118 UnresolvedProcMacro {
1119 node: node.clone().map(|it| it.into()),
1120 precise_location: None,
1125 BodyDiagnostic::UnresolvedMacroCall { node, path } => acc.push(
1126 UnresolvedMacroCall { macro_call: node.clone(), path: path.clone() }.into(),
1131 let infer = db.infer(self.into());
1132 let source_map = Lazy::new(|| db.body_with_source_map(self.into()).1);
1133 for d in &infer.diagnostics {
1135 hir_ty::InferenceDiagnostic::NoSuchField { expr } => {
1136 let field = source_map.field_syntax(*expr);
1137 acc.push(NoSuchField { field }.into())
1139 hir_ty::InferenceDiagnostic::BreakOutsideOfLoop { expr } => {
1140 let expr = source_map
1142 .expect("break outside of loop in synthetic syntax");
1143 acc.push(BreakOutsideOfLoop { expr }.into())
1148 for expr in hir_ty::diagnostics::missing_unsafe(db, self.into()) {
1149 match source_map.expr_syntax(expr) {
1150 Ok(expr) => acc.push(MissingUnsafe { expr }.into()),
1151 Err(SyntheticSyntax) => {
1152 // FIXME: Here and eslwhere in this file, the `expr` was
1153 // desugared, report or assert that this doesn't happen.
1158 for diagnostic in BodyValidationDiagnostic::collect(db, self.into()) {
1160 BodyValidationDiagnostic::RecordMissingFields {
1165 let variant_data = variant.variant_data(db.upcast());
1166 let missed_fields = missed_fields
1168 .map(|idx| variant_data.fields()[idx].name.clone())
1172 Either::Left(record_expr) => match source_map.expr_syntax(record_expr) {
1174 let root = source_ptr.file_syntax(db.upcast());
1175 if let ast::Expr::RecordExpr(record_expr) =
1176 &source_ptr.value.to_node(&root)
1178 if record_expr.record_expr_field_list().is_some() {
1181 file: source_ptr.file_id,
1182 field_list_parent: Either::Left(AstPtr::new(
1185 field_list_parent_path: record_expr
1187 .map(|path| AstPtr::new(&path)),
1195 Err(SyntheticSyntax) => (),
1197 Either::Right(record_pat) => match source_map.pat_syntax(record_pat) {
1199 if let Some(expr) = source_ptr.value.as_ref().left() {
1200 let root = source_ptr.file_syntax(db.upcast());
1201 if let ast::Pat::RecordPat(record_pat) = expr.to_node(&root) {
1202 if record_pat.record_pat_field_list().is_some() {
1205 file: source_ptr.file_id,
1206 field_list_parent: Either::Right(AstPtr::new(
1209 field_list_parent_path: record_pat
1211 .map(|path| AstPtr::new(&path)),
1220 Err(SyntheticSyntax) => (),
1224 BodyValidationDiagnostic::ReplaceFilterMapNextWithFindMap { method_call_expr } => {
1225 if let Ok(next_source_ptr) = source_map.expr_syntax(method_call_expr) {
1227 ReplaceFilterMapNextWithFindMap {
1228 file: next_source_ptr.file_id,
1229 next_expr: next_source_ptr.value,
1235 BodyValidationDiagnostic::MismatchedArgCount { call_expr, expected, found } => {
1236 match source_map.expr_syntax(call_expr) {
1237 Ok(source_ptr) => acc.push(
1238 MismatchedArgCount { call_expr: source_ptr, expected, found }.into(),
1240 Err(SyntheticSyntax) => (),
1243 BodyValidationDiagnostic::RemoveThisSemicolon { expr } => {
1244 match source_map.expr_syntax(expr) {
1245 Ok(expr) => acc.push(RemoveThisSemicolon { expr }.into()),
1246 Err(SyntheticSyntax) => (),
1249 BodyValidationDiagnostic::MissingOkOrSomeInTailExpr { expr, required } => {
1250 match source_map.expr_syntax(expr) {
1251 Ok(expr) => acc.push(
1252 MissingOkOrSomeInTailExpr {
1255 expected: self.body_type(db),
1259 Err(SyntheticSyntax) => (),
1262 BodyValidationDiagnostic::MissingMatchArms { match_expr } => {
1263 match source_map.expr_syntax(match_expr) {
1265 let root = source_ptr.file_syntax(db.upcast());
1266 if let ast::Expr::MatchExpr(match_expr) =
1267 &source_ptr.value.to_node(&root)
1269 if let (Some(match_expr), Some(arms)) =
1270 (match_expr.expr(), match_expr.match_arm_list())
1274 file: source_ptr.file_id,
1275 match_expr: AstPtr::new(&match_expr),
1276 arms: AstPtr::new(&arms),
1283 Err(SyntheticSyntax) => (),
1286 BodyValidationDiagnostic::AddReferenceHere { arg_expr, mutability } => {
1287 match source_map.expr_syntax(arg_expr) {
1288 Ok(expr) => acc.push(AddReferenceHere { expr, mutability }.into()),
1289 Err(SyntheticSyntax) => (),
1295 let def: ModuleDef = match self {
1296 DefWithBody::Function(it) => it.into(),
1297 DefWithBody::Static(it) => it.into(),
1298 DefWithBody::Const(it) => it.into(),
1300 for diag in hir_ty::diagnostics::incorrect_case(db, krate, def.into()) {
1301 acc.push(diag.into())
1306 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1307 pub struct Function {
1308 pub(crate) id: FunctionId,
1312 pub fn module(self, db: &dyn HirDatabase) -> Module {
1313 self.id.lookup(db.upcast()).module(db.upcast()).into()
1316 pub fn name(self, db: &dyn HirDatabase) -> Name {
1317 db.function_data(self.id).name.clone()
1320 /// Get this function's return type
1321 pub fn ret_type(self, db: &dyn HirDatabase) -> Type {
1322 let resolver = self.id.resolver(db.upcast());
1323 let krate = self.id.lookup(db.upcast()).container.module(db.upcast()).krate();
1324 let ret_type = &db.function_data(self.id).ret_type;
1325 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
1326 let ty = ctx.lower_ty(ret_type);
1327 Type::new_with_resolver_inner(db, krate, &resolver, ty)
1330 pub fn self_param(self, db: &dyn HirDatabase) -> Option<SelfParam> {
1331 if !db.function_data(self.id).has_self_param() {
1334 Some(SelfParam { func: self.id })
1337 pub fn assoc_fn_params(self, db: &dyn HirDatabase) -> Vec<Param> {
1338 let resolver = self.id.resolver(db.upcast());
1339 let krate = self.id.lookup(db.upcast()).container.module(db.upcast()).krate();
1340 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
1341 let environment = db.trait_environment(self.id.into());
1342 db.function_data(self.id)
1346 .map(|(idx, (_, type_ref))| {
1347 let ty = Type { krate, env: environment.clone(), ty: ctx.lower_ty(type_ref) };
1348 Param { func: self, ty, idx }
1353 pub fn method_params(self, db: &dyn HirDatabase) -> Option<Vec<Param>> {
1354 if self.self_param(db).is_none() {
1357 let mut res = self.assoc_fn_params(db);
1362 pub fn is_unsafe(self, db: &dyn HirDatabase) -> bool {
1363 db.function_data(self.id).is_unsafe()
1366 pub fn is_const(self, db: &dyn HirDatabase) -> bool {
1367 db.function_data(self.id).is_const()
1370 pub fn is_async(self, db: &dyn HirDatabase) -> bool {
1371 db.function_data(self.id).is_async()
1374 /// Whether this function declaration has a definition.
1376 /// This is false in the case of required (not provided) trait methods.
1377 pub fn has_body(self, db: &dyn HirDatabase) -> bool {
1378 db.function_data(self.id).has_body()
1381 /// A textual representation of the HIR of this function for debugging purposes.
1382 pub fn debug_hir(self, db: &dyn HirDatabase) -> String {
1383 let body = db.body(self.id.into());
1385 let mut result = String::new();
1386 format_to!(result, "HIR expressions in the body of `{}`:\n", self.name(db));
1387 for (id, expr) in body.exprs.iter() {
1388 format_to!(result, "{:?}: {:?}\n", id, expr);
1395 // Note: logically, this belongs to `hir_ty`, but we are not using it there yet.
1402 impl From<hir_ty::Mutability> for Access {
1403 fn from(mutability: hir_ty::Mutability) -> Access {
1405 hir_ty::Mutability::Not => Access::Shared,
1406 hir_ty::Mutability::Mut => Access::Exclusive,
1411 #[derive(Clone, Debug)]
1414 /// The index in parameter list, including self parameter.
1420 pub fn ty(&self) -> &Type {
1424 pub fn name(&self, db: &dyn HirDatabase) -> Option<Name> {
1425 db.function_data(self.func.id).params[self.idx].0.clone()
1428 pub fn as_local(&self, db: &dyn HirDatabase) -> Local {
1429 let parent = DefWithBodyId::FunctionId(self.func.into());
1430 let body = db.body(parent);
1431 Local { parent, pat_id: body.params[self.idx] }
1434 pub fn pattern_source(&self, db: &dyn HirDatabase) -> Option<ast::Pat> {
1435 self.source(db).and_then(|p| p.value.pat())
1438 pub fn source(&self, db: &dyn HirDatabase) -> Option<InFile<ast::Param>> {
1439 let InFile { file_id, value } = self.func.source(db)?;
1440 let params = value.param_list()?;
1441 if params.self_param().is_some() {
1442 params.params().nth(self.idx.checked_sub(1)?)
1444 params.params().nth(self.idx)
1446 .map(|value| InFile { file_id, value })
1450 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1451 pub struct SelfParam {
1456 pub fn access(self, db: &dyn HirDatabase) -> Access {
1457 let func_data = db.function_data(self.func);
1461 .map(|(_, param)| match &**param {
1462 TypeRef::Reference(.., mutability) => match mutability {
1463 hir_def::type_ref::Mutability::Shared => Access::Shared,
1464 hir_def::type_ref::Mutability::Mut => Access::Exclusive,
1468 .unwrap_or(Access::Owned)
1471 pub fn display(self, db: &dyn HirDatabase) -> &'static str {
1472 match self.access(db) {
1473 Access::Shared => "&self",
1474 Access::Exclusive => "&mut self",
1475 Access::Owned => "self",
1479 pub fn source(&self, db: &dyn HirDatabase) -> Option<InFile<ast::SelfParam>> {
1480 let InFile { file_id, value } = Function::from(self.func).source(db)?;
1483 .and_then(|params| params.self_param())
1484 .map(|value| InFile { file_id, value })
1487 pub fn ty(&self, db: &dyn HirDatabase) -> Type {
1488 let resolver = self.func.resolver(db.upcast());
1489 let krate = self.func.lookup(db.upcast()).container.module(db.upcast()).krate();
1490 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
1491 let environment = db.trait_environment(self.func.into());
1495 env: environment.clone(),
1496 ty: ctx.lower_ty(&db.function_data(self.func).params[0].1),
1501 impl HasVisibility for Function {
1502 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1503 let function_data = db.function_data(self.id);
1504 let visibility = &function_data.visibility;
1505 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1509 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1511 pub(crate) id: ConstId,
1515 pub fn module(self, db: &dyn HirDatabase) -> Module {
1516 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
1519 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1520 db.const_data(self.id).name.clone()
1523 pub fn value(self, db: &dyn HirDatabase) -> Option<ast::Expr> {
1524 self.source(db)?.value.body()
1527 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1528 let data = db.const_data(self.id);
1529 let resolver = self.id.resolver(db.upcast());
1530 let krate = self.id.lookup(db.upcast()).container.krate(db);
1531 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
1532 let ty = ctx.lower_ty(&data.type_ref);
1533 Type::new_with_resolver_inner(db, krate.id, &resolver, ty)
1536 pub fn eval(self, db: &dyn HirDatabase) -> Result<ComputedExpr, ConstEvalError> {
1537 let body = db.body(self.id.into());
1538 let root = &body.exprs[body.body_expr];
1539 let infer = db.infer_query(self.id.into());
1540 let infer = infer.as_ref();
1541 let result = eval_const(
1546 local_data: HashMap::default(),
1547 infer: &mut |x| infer[x].clone(),
1554 impl HasVisibility for Const {
1555 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1556 let function_data = db.const_data(self.id);
1557 let visibility = &function_data.visibility;
1558 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1562 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1564 pub(crate) id: StaticId,
1568 pub fn module(self, db: &dyn HirDatabase) -> Module {
1569 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
1572 pub fn name(self, db: &dyn HirDatabase) -> Name {
1573 db.static_data(self.id).name.clone()
1576 pub fn is_mut(self, db: &dyn HirDatabase) -> bool {
1577 db.static_data(self.id).mutable
1580 pub fn value(self, db: &dyn HirDatabase) -> Option<ast::Expr> {
1581 self.source(db)?.value.body()
1584 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1585 let data = db.static_data(self.id);
1586 let resolver = self.id.resolver(db.upcast());
1587 let krate = self.id.lookup(db.upcast()).container.module(db.upcast()).krate();
1588 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
1589 let ty = ctx.lower_ty(&data.type_ref);
1590 Type::new_with_resolver_inner(db, krate, &resolver, ty)
1594 impl HasVisibility for Static {
1595 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1596 db.static_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1600 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1602 pub(crate) id: TraitId,
1606 pub fn lang(db: &dyn HirDatabase, krate: Crate, name: &Name) -> Option<Trait> {
1607 db.lang_item(krate.into(), name.to_smol_str())
1608 .and_then(LangItemTarget::as_trait)
1612 pub fn module(self, db: &dyn HirDatabase) -> Module {
1613 Module { id: self.id.lookup(db.upcast()).container }
1616 pub fn name(self, db: &dyn HirDatabase) -> Name {
1617 db.trait_data(self.id).name.clone()
1620 pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
1621 db.trait_data(self.id).items.iter().map(|(_name, it)| (*it).into()).collect()
1624 pub fn is_auto(self, db: &dyn HirDatabase) -> bool {
1625 db.trait_data(self.id).is_auto
1628 pub fn is_unsafe(&self, db: &dyn HirDatabase) -> bool {
1629 db.trait_data(self.id).is_unsafe
1633 impl HasVisibility for Trait {
1634 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1635 db.trait_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1639 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1640 pub struct TypeAlias {
1641 pub(crate) id: TypeAliasId,
1645 pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
1646 let subst = db.generic_defaults(self.id.into());
1647 subst.iter().any(|ty| ty.skip_binders().is_unknown())
1650 pub fn module(self, db: &dyn HirDatabase) -> Module {
1651 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
1654 pub fn type_ref(self, db: &dyn HirDatabase) -> Option<TypeRef> {
1655 db.type_alias_data(self.id).type_ref.as_deref().cloned()
1658 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1659 Type::from_def(db, self.id.lookup(db.upcast()).module(db.upcast()).krate(), self.id)
1662 pub fn name(self, db: &dyn HirDatabase) -> Name {
1663 db.type_alias_data(self.id).name.clone()
1667 impl HasVisibility for TypeAlias {
1668 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1669 let function_data = db.type_alias_data(self.id);
1670 let visibility = &function_data.visibility;
1671 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1675 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1676 pub struct BuiltinType {
1677 pub(crate) inner: hir_def::builtin_type::BuiltinType,
1681 pub fn str() -> BuiltinType {
1682 BuiltinType { inner: hir_def::builtin_type::BuiltinType::Str }
1685 pub fn ty(self, db: &dyn HirDatabase, module: Module) -> Type {
1686 let resolver = module.id.resolver(db.upcast());
1687 Type::new_with_resolver(db, &resolver, TyBuilder::builtin(self.inner))
1688 .expect("crate not present in resolver")
1691 pub fn name(self) -> Name {
1692 self.inner.as_name()
1695 pub fn is_int(&self) -> bool {
1696 matches!(self.inner, hir_def::builtin_type::BuiltinType::Int(_))
1699 pub fn is_uint(&self) -> bool {
1700 matches!(self.inner, hir_def::builtin_type::BuiltinType::Uint(_))
1703 pub fn is_float(&self) -> bool {
1704 matches!(self.inner, hir_def::builtin_type::BuiltinType::Float(_))
1707 pub fn is_char(&self) -> bool {
1708 matches!(self.inner, hir_def::builtin_type::BuiltinType::Char)
1711 pub fn is_str(&self) -> bool {
1712 matches!(self.inner, hir_def::builtin_type::BuiltinType::Str)
1716 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1717 pub enum MacroKind {
1718 /// `macro_rules!` or Macros 2.0 macro.
1720 /// A built-in or custom derive.
1722 /// A built-in function-like macro.
1724 /// A procedural attribute macro.
1726 /// A function-like procedural macro.
1730 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1731 pub struct MacroDef {
1732 pub(crate) id: MacroDefId,
1736 /// FIXME: right now, this just returns the root module of the crate that
1737 /// defines this macro. The reasons for this is that macros are expanded
1738 /// early, in `hir_expand`, where modules simply do not exist yet.
1739 pub fn module(self, db: &dyn HirDatabase) -> Option<Module> {
1740 let krate = self.id.krate;
1741 let def_map = db.crate_def_map(krate);
1742 let module_id = def_map.root();
1743 Some(Module { id: def_map.module_id(module_id) })
1746 /// XXX: this parses the file
1747 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1748 match self.source(db)?.value {
1749 Either::Left(it) => it.name().map(|it| it.as_name()),
1750 Either::Right(_) => {
1751 let krate = self.id.krate;
1752 let def_map = db.crate_def_map(krate);
1753 let (_, name) = def_map.exported_proc_macros().find(|&(id, _)| id == self.id)?;
1759 pub fn kind(&self) -> MacroKind {
1760 match self.id.kind {
1761 MacroDefKind::Declarative(_) => MacroKind::Declarative,
1762 MacroDefKind::BuiltIn(_, _) | MacroDefKind::BuiltInEager(_, _) => MacroKind::BuiltIn,
1763 MacroDefKind::BuiltInDerive(_, _) => MacroKind::Derive,
1764 MacroDefKind::BuiltInAttr(_, _) => MacroKind::Attr,
1765 MacroDefKind::ProcMacro(_, base_db::ProcMacroKind::CustomDerive, _) => {
1768 MacroDefKind::ProcMacro(_, base_db::ProcMacroKind::Attr, _) => MacroKind::Attr,
1769 MacroDefKind::ProcMacro(_, base_db::ProcMacroKind::FuncLike, _) => MacroKind::ProcMacro,
1773 pub fn is_fn_like(&self) -> bool {
1775 MacroKind::Declarative | MacroKind::BuiltIn | MacroKind::ProcMacro => true,
1776 MacroKind::Attr | MacroKind::Derive => false,
1780 pub fn is_attr(&self) -> bool {
1781 matches!(self.kind(), MacroKind::Attr)
1785 #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
1792 impl From<MacroDef> for ItemInNs {
1793 fn from(it: MacroDef) -> Self {
1798 impl From<ModuleDef> for ItemInNs {
1799 fn from(module_def: ModuleDef) -> Self {
1801 ModuleDef::Static(_) | ModuleDef::Const(_) | ModuleDef::Function(_) => {
1802 ItemInNs::Values(module_def)
1804 _ => ItemInNs::Types(module_def),
1810 pub fn as_module_def(self) -> Option<ModuleDef> {
1812 ItemInNs::Types(id) | ItemInNs::Values(id) => Some(id),
1813 ItemInNs::Macros(_) => None,
1817 /// Returns the crate defining this item (or `None` if `self` is built-in).
1818 pub fn krate(&self, db: &dyn HirDatabase) -> Option<Crate> {
1820 ItemInNs::Types(did) | ItemInNs::Values(did) => did.module(db).map(|m| m.krate()),
1821 ItemInNs::Macros(id) => id.module(db).map(|m| m.krate()),
1825 pub fn attrs(&self, db: &dyn HirDatabase) -> Option<AttrsWithOwner> {
1827 ItemInNs::Types(it) | ItemInNs::Values(it) => it.attrs(db),
1828 ItemInNs::Macros(it) => Some(it.attrs(db)),
1833 /// Invariant: `inner.as_assoc_item(db).is_some()`
1834 /// We do not actively enforce this invariant.
1835 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1836 pub enum AssocItem {
1839 TypeAlias(TypeAlias),
1842 pub enum AssocItemContainer {
1846 pub trait AsAssocItem {
1847 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem>;
1850 impl AsAssocItem for Function {
1851 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1852 as_assoc_item(db, AssocItem::Function, self.id)
1855 impl AsAssocItem for Const {
1856 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1857 as_assoc_item(db, AssocItem::Const, self.id)
1860 impl AsAssocItem for TypeAlias {
1861 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1862 as_assoc_item(db, AssocItem::TypeAlias, self.id)
1865 impl AsAssocItem for ModuleDef {
1866 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1868 ModuleDef::Function(it) => it.as_assoc_item(db),
1869 ModuleDef::Const(it) => it.as_assoc_item(db),
1870 ModuleDef::TypeAlias(it) => it.as_assoc_item(db),
1875 fn as_assoc_item<ID, DEF, CTOR, AST>(db: &dyn HirDatabase, ctor: CTOR, id: ID) -> Option<AssocItem>
1877 ID: Lookup<Data = AssocItemLoc<AST>>,
1879 CTOR: FnOnce(DEF) -> AssocItem,
1882 match id.lookup(db.upcast()).container {
1883 ItemContainerId::TraitId(_) | ItemContainerId::ImplId(_) => Some(ctor(DEF::from(id))),
1884 ItemContainerId::ModuleId(_) | ItemContainerId::ExternBlockId(_) => None,
1889 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1891 AssocItem::Function(it) => Some(it.name(db)),
1892 AssocItem::Const(it) => it.name(db),
1893 AssocItem::TypeAlias(it) => Some(it.name(db)),
1896 pub fn module(self, db: &dyn HirDatabase) -> Module {
1898 AssocItem::Function(f) => f.module(db),
1899 AssocItem::Const(c) => c.module(db),
1900 AssocItem::TypeAlias(t) => t.module(db),
1903 pub fn container(self, db: &dyn HirDatabase) -> AssocItemContainer {
1904 let container = match self {
1905 AssocItem::Function(it) => it.id.lookup(db.upcast()).container,
1906 AssocItem::Const(it) => it.id.lookup(db.upcast()).container,
1907 AssocItem::TypeAlias(it) => it.id.lookup(db.upcast()).container,
1910 ItemContainerId::TraitId(id) => AssocItemContainer::Trait(id.into()),
1911 ItemContainerId::ImplId(id) => AssocItemContainer::Impl(id.into()),
1912 ItemContainerId::ModuleId(_) | ItemContainerId::ExternBlockId(_) => {
1913 panic!("invalid AssocItem")
1918 pub fn containing_trait(self, db: &dyn HirDatabase) -> Option<Trait> {
1919 match self.container(db) {
1920 AssocItemContainer::Trait(t) => Some(t),
1925 pub fn containing_trait_impl(self, db: &dyn HirDatabase) -> Option<Trait> {
1926 match self.container(db) {
1927 AssocItemContainer::Impl(i) => i.trait_(db),
1932 pub fn containing_trait_or_trait_impl(self, db: &dyn HirDatabase) -> Option<Trait> {
1933 match self.container(db) {
1934 AssocItemContainer::Trait(t) => Some(t),
1935 AssocItemContainer::Impl(i) => i.trait_(db),
1940 impl HasVisibility for AssocItem {
1941 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1943 AssocItem::Function(f) => f.visibility(db),
1944 AssocItem::Const(c) => c.visibility(db),
1945 AssocItem::TypeAlias(t) => t.visibility(db),
1950 impl From<AssocItem> for ModuleDef {
1951 fn from(assoc: AssocItem) -> Self {
1953 AssocItem::Function(it) => ModuleDef::Function(it),
1954 AssocItem::Const(it) => ModuleDef::Const(it),
1955 AssocItem::TypeAlias(it) => ModuleDef::TypeAlias(it),
1960 #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
1961 pub enum GenericDef {
1965 TypeAlias(TypeAlias),
1967 // enum variants cannot have generics themselves, but their parent enums
1968 // can, and this makes some code easier to write
1970 // consts can have type parameters from their parents (i.e. associated consts of traits)
1975 Adt(Struct, Enum, Union),
1985 pub fn params(self, db: &dyn HirDatabase) -> Vec<GenericParam> {
1986 let generics = db.generic_params(self.into());
1987 let ty_params = generics
1990 .map(|(local_id, _)| TypeParam { id: TypeParamId { parent: self.into(), local_id } })
1991 .map(GenericParam::TypeParam);
1992 let lt_params = generics
1995 .map(|(local_id, _)| LifetimeParam {
1996 id: LifetimeParamId { parent: self.into(), local_id },
1998 .map(GenericParam::LifetimeParam);
1999 let const_params = generics
2002 .map(|(local_id, _)| ConstParam { id: ConstParamId { parent: self.into(), local_id } })
2003 .map(GenericParam::ConstParam);
2004 ty_params.chain(lt_params).chain(const_params).collect()
2007 pub fn type_params(self, db: &dyn HirDatabase) -> Vec<TypeParam> {
2008 let generics = db.generic_params(self.into());
2012 .map(|(local_id, _)| TypeParam { id: TypeParamId { parent: self.into(), local_id } })
2017 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2019 pub(crate) parent: DefWithBodyId,
2020 pub(crate) pat_id: PatId,
2024 pub fn is_param(self, db: &dyn HirDatabase) -> bool {
2025 let src = self.source(db);
2027 Either::Left(bind_pat) => {
2028 bind_pat.syntax().ancestors().any(|it| ast::Param::can_cast(it.kind()))
2030 Either::Right(_self_param) => true,
2034 pub fn as_self_param(self, db: &dyn HirDatabase) -> Option<SelfParam> {
2036 DefWithBodyId::FunctionId(func) if self.is_self(db) => Some(SelfParam { func }),
2041 // FIXME: why is this an option? It shouldn't be?
2042 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
2043 let body = db.body(self.parent);
2044 match &body[self.pat_id] {
2045 Pat::Bind { name, .. } => Some(name.clone()),
2050 pub fn is_self(self, db: &dyn HirDatabase) -> bool {
2051 self.name(db) == Some(name![self])
2054 pub fn is_mut(self, db: &dyn HirDatabase) -> bool {
2055 let body = db.body(self.parent);
2056 matches!(&body[self.pat_id], Pat::Bind { mode: BindingAnnotation::Mutable, .. })
2059 pub fn is_ref(self, db: &dyn HirDatabase) -> bool {
2060 let body = db.body(self.parent);
2063 Pat::Bind { mode: BindingAnnotation::Ref | BindingAnnotation::RefMut, .. }
2067 pub fn parent(self, _db: &dyn HirDatabase) -> DefWithBody {
2071 pub fn module(self, db: &dyn HirDatabase) -> Module {
2072 self.parent(db).module(db)
2075 pub fn ty(self, db: &dyn HirDatabase) -> Type {
2076 let def = self.parent;
2077 let infer = db.infer(def);
2078 let ty = infer[self.pat_id].clone();
2079 let krate = def.module(db.upcast()).krate();
2080 Type::new(db, krate, def, ty)
2083 pub fn source(self, db: &dyn HirDatabase) -> InFile<Either<ast::IdentPat, ast::SelfParam>> {
2084 let (_body, source_map) = db.body_with_source_map(self.parent);
2085 let src = source_map.pat_syntax(self.pat_id).unwrap(); // Hmm...
2086 let root = src.file_syntax(db.upcast());
2088 ast.map_left(|it| it.cast().unwrap().to_node(&root)).map_right(|it| it.to_node(&root))
2093 // FIXME: Wrong name? This is could also be a registered attribute
2094 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2095 pub struct BuiltinAttr {
2096 krate: Option<CrateId>,
2101 // FIXME: consider crates\hir_def\src\nameres\attr_resolution.rs?
2102 pub(crate) fn by_name(db: &dyn HirDatabase, krate: Crate, name: &str) -> Option<Self> {
2103 if let builtin @ Some(_) = Self::builtin(name) {
2106 let idx = db.crate_def_map(krate.id).registered_attrs().iter().position(|it| it == name)?;
2107 Some(BuiltinAttr { krate: Some(krate.id), idx })
2110 pub(crate) fn builtin(name: &str) -> Option<Self> {
2111 hir_def::builtin_attr::INERT_ATTRIBUTES
2113 .position(|tool| tool.name == name)
2114 .map(|idx| BuiltinAttr { krate: None, idx })
2117 pub fn name(&self, db: &dyn HirDatabase) -> SmolStr {
2118 // FIXME: Return a `Name` here
2120 Some(krate) => db.crate_def_map(krate).registered_attrs()[self.idx].clone(),
2121 None => SmolStr::new(hir_def::builtin_attr::INERT_ATTRIBUTES[self.idx].name),
2125 pub fn template(&self, _: &dyn HirDatabase) -> Option<AttributeTemplate> {
2128 None => Some(hir_def::builtin_attr::INERT_ATTRIBUTES[self.idx].template),
2133 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2134 pub struct ToolModule {
2135 krate: Option<CrateId>,
2140 // FIXME: consider crates\hir_def\src\nameres\attr_resolution.rs?
2141 pub(crate) fn by_name(db: &dyn HirDatabase, krate: Crate, name: &str) -> Option<Self> {
2142 if let builtin @ Some(_) = Self::builtin(name) {
2145 let idx = db.crate_def_map(krate.id).registered_tools().iter().position(|it| it == name)?;
2146 Some(ToolModule { krate: Some(krate.id), idx })
2149 pub(crate) fn builtin(name: &str) -> Option<Self> {
2150 hir_def::builtin_attr::TOOL_MODULES
2152 .position(|&tool| tool == name)
2153 .map(|idx| ToolModule { krate: None, idx })
2156 pub fn name(&self, db: &dyn HirDatabase) -> SmolStr {
2157 // FIXME: Return a `Name` here
2159 Some(krate) => db.crate_def_map(krate).registered_tools()[self.idx].clone(),
2160 None => SmolStr::new(hir_def::builtin_attr::TOOL_MODULES[self.idx]),
2165 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2167 pub(crate) parent: DefWithBodyId,
2168 pub(crate) label_id: LabelId,
2172 pub fn module(self, db: &dyn HirDatabase) -> Module {
2173 self.parent(db).module(db)
2176 pub fn parent(self, _db: &dyn HirDatabase) -> DefWithBody {
2180 pub fn name(self, db: &dyn HirDatabase) -> Name {
2181 let body = db.body(self.parent);
2182 body[self.label_id].name.clone()
2185 pub fn source(self, db: &dyn HirDatabase) -> InFile<ast::Label> {
2186 let (_body, source_map) = db.body_with_source_map(self.parent);
2187 let src = source_map.label_syntax(self.label_id);
2188 let root = src.file_syntax(db.upcast());
2189 src.map(|ast| ast.to_node(&root))
2193 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2194 pub enum GenericParam {
2195 TypeParam(TypeParam),
2196 LifetimeParam(LifetimeParam),
2197 ConstParam(ConstParam),
2199 impl_from!(TypeParam, LifetimeParam, ConstParam for GenericParam);
2202 pub fn module(self, db: &dyn HirDatabase) -> Module {
2204 GenericParam::TypeParam(it) => it.module(db),
2205 GenericParam::LifetimeParam(it) => it.module(db),
2206 GenericParam::ConstParam(it) => it.module(db),
2210 pub fn name(self, db: &dyn HirDatabase) -> Name {
2212 GenericParam::TypeParam(it) => it.name(db),
2213 GenericParam::LifetimeParam(it) => it.name(db),
2214 GenericParam::ConstParam(it) => it.name(db),
2219 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2220 pub struct TypeParam {
2221 pub(crate) id: TypeParamId,
2225 pub fn name(self, db: &dyn HirDatabase) -> Name {
2226 let params = db.generic_params(self.id.parent);
2227 params.types[self.id.local_id].name.clone().unwrap_or_else(Name::missing)
2230 pub fn module(self, db: &dyn HirDatabase) -> Module {
2231 self.id.parent.module(db.upcast()).into()
2234 pub fn ty(self, db: &dyn HirDatabase) -> Type {
2235 let resolver = self.id.parent.resolver(db.upcast());
2236 let krate = self.id.parent.module(db.upcast()).krate();
2237 let ty = TyKind::Placeholder(hir_ty::to_placeholder_idx(db, self.id)).intern(Interner);
2238 Type::new_with_resolver_inner(db, krate, &resolver, ty)
2241 pub fn trait_bounds(self, db: &dyn HirDatabase) -> Vec<Trait> {
2242 db.generic_predicates_for_param(self.id, None)
2244 .filter_map(|pred| match &pred.skip_binders().skip_binders() {
2245 hir_ty::WhereClause::Implemented(trait_ref) => {
2246 Some(Trait::from(trait_ref.hir_trait_id()))
2253 pub fn default(self, db: &dyn HirDatabase) -> Option<Type> {
2254 let params = db.generic_defaults(self.id.parent);
2255 let local_idx = hir_ty::param_idx(db, self.id)?;
2256 let resolver = self.id.parent.resolver(db.upcast());
2257 let krate = self.id.parent.module(db.upcast()).krate();
2258 let ty = params.get(local_idx)?.clone();
2259 let subst = TyBuilder::type_params_subst(db, self.id.parent);
2260 let ty = ty.substitute(Interner, &subst_prefix(&subst, local_idx));
2261 Some(Type::new_with_resolver_inner(db, krate, &resolver, ty))
2265 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2266 pub struct LifetimeParam {
2267 pub(crate) id: LifetimeParamId,
2270 impl LifetimeParam {
2271 pub fn name(self, db: &dyn HirDatabase) -> Name {
2272 let params = db.generic_params(self.id.parent);
2273 params.lifetimes[self.id.local_id].name.clone()
2276 pub fn module(self, db: &dyn HirDatabase) -> Module {
2277 self.id.parent.module(db.upcast()).into()
2280 pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef {
2281 self.id.parent.into()
2285 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2286 pub struct ConstParam {
2287 pub(crate) id: ConstParamId,
2291 pub fn name(self, db: &dyn HirDatabase) -> Name {
2292 let params = db.generic_params(self.id.parent);
2293 params.consts[self.id.local_id].name.clone()
2296 pub fn module(self, db: &dyn HirDatabase) -> Module {
2297 self.id.parent.module(db.upcast()).into()
2300 pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef {
2301 self.id.parent.into()
2304 pub fn ty(self, db: &dyn HirDatabase) -> Type {
2305 let def = self.id.parent;
2306 let krate = def.module(db.upcast()).krate();
2307 Type::new(db, krate, def, db.const_param_ty(self.id))
2311 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2313 pub(crate) id: ImplId,
2317 pub fn all_in_crate(db: &dyn HirDatabase, krate: Crate) -> Vec<Impl> {
2318 let inherent = db.inherent_impls_in_crate(krate.id);
2319 let trait_ = db.trait_impls_in_crate(krate.id);
2321 inherent.all_impls().chain(trait_.all_impls()).map(Self::from).collect()
2324 pub fn all_for_type(db: &dyn HirDatabase, Type { krate, ty, .. }: Type) -> Vec<Impl> {
2325 let def_crates = match method_resolution::def_crates(db, &ty, krate) {
2326 Some(def_crates) => def_crates,
2327 None => return Vec::new(),
2330 let filter = |impl_def: &Impl| {
2331 let self_ty = impl_def.self_ty(db);
2332 let rref = self_ty.remove_ref();
2333 ty.equals_ctor(rref.as_ref().map_or(&self_ty.ty, |it| &it.ty))
2336 let fp = TyFingerprint::for_inherent_impl(&ty);
2339 None => return Vec::new(),
2342 let mut all = Vec::new();
2343 def_crates.iter().for_each(|&id| {
2345 db.inherent_impls_in_crate(id)
2353 for id in def_crates
2355 .flat_map(|&id| Crate { id }.transitive_reverse_dependencies(db))
2356 .map(|Crate { id }| id)
2357 .chain(def_crates.iter().copied())
2361 db.trait_impls_in_crate(id)
2362 .for_self_ty_without_blanket_impls(fp)
2370 pub fn all_for_trait(db: &dyn HirDatabase, trait_: Trait) -> Vec<Impl> {
2371 let krate = trait_.module(db).krate();
2372 let mut all = Vec::new();
2373 for Crate { id } in krate.transitive_reverse_dependencies(db).into_iter() {
2374 let impls = db.trait_impls_in_crate(id);
2375 all.extend(impls.for_trait(trait_.id).map(Self::from))
2380 // FIXME: the return type is wrong. This should be a hir version of
2381 // `TraitRef` (to account for parameters and qualifiers)
2382 pub fn trait_(self, db: &dyn HirDatabase) -> Option<Trait> {
2383 let trait_ref = db.impl_trait(self.id)?.skip_binders().clone();
2384 let id = hir_ty::from_chalk_trait_id(trait_ref.trait_id);
2388 pub fn self_ty(self, db: &dyn HirDatabase) -> Type {
2389 let impl_data = db.impl_data(self.id);
2390 let resolver = self.id.resolver(db.upcast());
2391 let krate = self.id.lookup(db.upcast()).container.krate();
2392 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
2393 let ty = ctx.lower_ty(&impl_data.self_ty);
2394 Type::new_with_resolver_inner(db, krate, &resolver, ty)
2397 pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
2398 db.impl_data(self.id).items.iter().map(|it| (*it).into()).collect()
2401 pub fn is_negative(self, db: &dyn HirDatabase) -> bool {
2402 db.impl_data(self.id).is_negative
2405 pub fn module(self, db: &dyn HirDatabase) -> Module {
2406 self.id.lookup(db.upcast()).container.into()
2409 pub fn is_builtin_derive(self, db: &dyn HirDatabase) -> Option<InFile<ast::Attr>> {
2410 let src = self.source(db)?;
2411 let item = src.file_id.is_builtin_derive(db.upcast())?;
2412 let hygenic = hir_expand::hygiene::Hygiene::new(db.upcast(), item.file_id);
2414 // FIXME: handle `cfg_attr`
2419 let path = ModPath::from_src(db.upcast(), it.path()?, &hygenic)?;
2420 if path.as_ident()?.to_smol_str() == "derive" {
2428 Some(item.with_value(attr))
2432 #[derive(Clone, PartialEq, Eq, Debug)]
2435 env: Arc<TraitEnvironment>,
2440 pub(crate) fn new_with_resolver(
2441 db: &dyn HirDatabase,
2442 resolver: &Resolver,
2445 let krate = resolver.krate()?;
2446 Some(Type::new_with_resolver_inner(db, krate, resolver, ty))
2448 pub(crate) fn new_with_resolver_inner(
2449 db: &dyn HirDatabase,
2451 resolver: &Resolver,
2454 let environment = resolver
2456 .map_or_else(|| Arc::new(TraitEnvironment::empty(krate)), |d| db.trait_environment(d));
2457 Type { krate, env: environment, ty }
2460 fn new(db: &dyn HirDatabase, krate: CrateId, lexical_env: impl HasResolver, ty: Ty) -> Type {
2461 let resolver = lexical_env.resolver(db.upcast());
2462 let environment = resolver
2464 .map_or_else(|| Arc::new(TraitEnvironment::empty(krate)), |d| db.trait_environment(d));
2465 Type { krate, env: environment, ty }
2469 db: &dyn HirDatabase,
2471 def: impl HasResolver + Into<TyDefId>,
2473 let ty = TyBuilder::def_ty(db, def.into()).fill_with_unknown().build();
2474 Type::new(db, krate, def, ty)
2477 pub fn new_slice(ty: Type) -> Type {
2478 Type { krate: ty.krate, env: ty.env, ty: TyBuilder::slice(ty.ty) }
2481 pub fn is_unit(&self) -> bool {
2482 matches!(self.ty.kind(Interner), TyKind::Tuple(0, ..))
2485 pub fn is_bool(&self) -> bool {
2486 matches!(self.ty.kind(Interner), TyKind::Scalar(Scalar::Bool))
2489 pub fn is_never(&self) -> bool {
2490 matches!(self.ty.kind(Interner), TyKind::Never)
2493 pub fn is_mutable_reference(&self) -> bool {
2494 matches!(self.ty.kind(Interner), TyKind::Ref(hir_ty::Mutability::Mut, ..))
2497 pub fn is_reference(&self) -> bool {
2498 matches!(self.ty.kind(Interner), TyKind::Ref(..))
2501 pub fn is_usize(&self) -> bool {
2502 matches!(self.ty.kind(Interner), TyKind::Scalar(Scalar::Uint(UintTy::Usize)))
2505 pub fn remove_ref(&self) -> Option<Type> {
2506 match &self.ty.kind(Interner) {
2507 TyKind::Ref(.., ty) => Some(self.derived(ty.clone())),
2512 pub fn strip_references(&self) -> Type {
2513 self.derived(self.ty.strip_references().clone())
2516 pub fn is_unknown(&self) -> bool {
2517 self.ty.is_unknown()
2520 /// Checks that particular type `ty` implements `std::future::Future`.
2521 /// This function is used in `.await` syntax completion.
2522 pub fn impls_future(&self, db: &dyn HirDatabase) -> bool {
2523 // No special case for the type of async block, since Chalk can figure it out.
2525 let krate = self.krate;
2527 let std_future_trait =
2528 db.lang_item(krate, SmolStr::new_inline("future_trait")).and_then(|it| it.as_trait());
2529 let std_future_trait = match std_future_trait {
2531 None => return false,
2535 Canonical { value: self.ty.clone(), binders: CanonicalVarKinds::empty(Interner) };
2536 method_resolution::implements_trait(
2545 /// Checks that particular type `ty` implements `std::ops::FnOnce`.
2547 /// This function can be used to check if a particular type is callable, since FnOnce is a
2548 /// supertrait of Fn and FnMut, so all callable types implements at least FnOnce.
2549 pub fn impls_fnonce(&self, db: &dyn HirDatabase) -> bool {
2550 let krate = self.krate;
2552 let fnonce_trait = match FnTrait::FnOnce.get_id(db, krate) {
2554 None => return false,
2558 Canonical { value: self.ty.clone(), binders: CanonicalVarKinds::empty(Interner) };
2559 method_resolution::implements_trait_unique(
2568 pub fn impls_trait(&self, db: &dyn HirDatabase, trait_: Trait, args: &[Type]) -> bool {
2569 let trait_ref = TyBuilder::trait_ref(db, trait_.id)
2570 .push(self.ty.clone())
2571 .fill(args.iter().map(|t| t.ty.clone()))
2574 let goal = Canonical {
2575 value: hir_ty::InEnvironment::new(&self.env.env, trait_ref.cast(Interner)),
2576 binders: CanonicalVarKinds::empty(Interner),
2579 db.trait_solve(self.krate, goal).is_some()
2582 pub fn normalize_trait_assoc_type(
2584 db: &dyn HirDatabase,
2588 let projection = TyBuilder::assoc_type_projection(db, alias.id)
2589 .push(self.ty.clone())
2590 .fill(args.iter().map(|t| t.ty.clone()))
2592 let goal = hir_ty::make_canonical(
2596 alias: AliasTy::Projection(projection),
2597 ty: TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0))
2602 [TyVariableKind::General].into_iter(),
2605 match db.trait_solve(self.krate, goal)? {
2606 Solution::Unique(s) => s
2611 .map(|ty| self.derived(ty.assert_ty_ref(Interner).clone())),
2612 Solution::Ambig(_) => None,
2616 pub fn is_copy(&self, db: &dyn HirDatabase) -> bool {
2617 let lang_item = db.lang_item(self.krate, SmolStr::new_inline("copy"));
2618 let copy_trait = match lang_item {
2619 Some(LangItemTarget::TraitId(it)) => it,
2622 self.impls_trait(db, copy_trait.into(), &[])
2625 pub fn as_callable(&self, db: &dyn HirDatabase) -> Option<Callable> {
2626 let def = self.ty.callable_def(db);
2628 let sig = self.ty.callable_sig(db)?;
2629 Some(Callable { ty: self.clone(), sig, def, is_bound_method: false })
2632 pub fn is_closure(&self) -> bool {
2633 matches!(&self.ty.kind(Interner), TyKind::Closure { .. })
2636 pub fn is_fn(&self) -> bool {
2637 matches!(&self.ty.kind(Interner), TyKind::FnDef(..) | TyKind::Function { .. })
2640 pub fn is_array(&self) -> bool {
2641 matches!(&self.ty.kind(Interner), TyKind::Array(..))
2644 pub fn is_packed(&self, db: &dyn HirDatabase) -> bool {
2645 let adt_id = match *self.ty.kind(Interner) {
2646 TyKind::Adt(hir_ty::AdtId(adt_id), ..) => adt_id,
2650 let adt = adt_id.into();
2652 Adt::Struct(s) => matches!(s.repr(db), Some(ReprKind::Packed)),
2657 pub fn is_raw_ptr(&self) -> bool {
2658 matches!(&self.ty.kind(Interner), TyKind::Raw(..))
2661 pub fn contains_unknown(&self) -> bool {
2662 return go(&self.ty);
2664 fn go(ty: &Ty) -> bool {
2665 match ty.kind(Interner) {
2666 TyKind::Error => true,
2668 TyKind::Adt(_, substs)
2669 | TyKind::AssociatedType(_, substs)
2670 | TyKind::Tuple(_, substs)
2671 | TyKind::OpaqueType(_, substs)
2672 | TyKind::FnDef(_, substs)
2673 | TyKind::Closure(_, substs) => {
2674 substs.iter(Interner).filter_map(|a| a.ty(Interner)).any(go)
2677 TyKind::Array(_ty, len) if len.is_unknown() => true,
2678 TyKind::Array(ty, _)
2680 | TyKind::Raw(_, ty)
2681 | TyKind::Ref(_, _, ty) => go(ty),
2686 | TyKind::Placeholder(_)
2687 | TyKind::BoundVar(_)
2688 | TyKind::InferenceVar(_, _)
2690 | TyKind::Function(_)
2692 | TyKind::Foreign(_)
2693 | TyKind::Generator(..)
2694 | TyKind::GeneratorWitness(..) => false,
2699 pub fn fields(&self, db: &dyn HirDatabase) -> Vec<(Field, Type)> {
2700 let (variant_id, substs) = match self.ty.kind(Interner) {
2701 TyKind::Adt(hir_ty::AdtId(AdtId::StructId(s)), substs) => ((*s).into(), substs),
2702 TyKind::Adt(hir_ty::AdtId(AdtId::UnionId(u)), substs) => ((*u).into(), substs),
2703 _ => return Vec::new(),
2706 db.field_types(variant_id)
2708 .map(|(local_id, ty)| {
2709 let def = Field { parent: variant_id.into(), id: local_id };
2710 let ty = ty.clone().substitute(Interner, substs);
2711 (def, self.derived(ty))
2716 pub fn tuple_fields(&self, _db: &dyn HirDatabase) -> Vec<Type> {
2717 if let TyKind::Tuple(_, substs) = &self.ty.kind(Interner) {
2720 .map(|ty| self.derived(ty.assert_ty_ref(Interner).clone()))
2727 pub fn autoderef<'a>(&'a self, db: &'a dyn HirDatabase) -> impl Iterator<Item = Type> + 'a {
2728 self.autoderef_(db).map(move |ty| self.derived(ty))
2731 pub fn autoderef_<'a>(&'a self, db: &'a dyn HirDatabase) -> impl Iterator<Item = Ty> + 'a {
2732 // There should be no inference vars in types passed here
2733 let canonical = hir_ty::replace_errors_with_variables(&self.ty);
2734 let environment = self.env.env.clone();
2735 let ty = InEnvironment { goal: canonical, environment };
2736 autoderef(db, Some(self.krate), ty).map(|canonical| canonical.value)
2739 // This would be nicer if it just returned an iterator, but that runs into
2740 // lifetime problems, because we need to borrow temp `CrateImplDefs`.
2741 pub fn iterate_assoc_items<T>(
2743 db: &dyn HirDatabase,
2745 mut callback: impl FnMut(AssocItem) -> Option<T>,
2747 let mut slot = None;
2748 self.iterate_assoc_items_dyn(db, krate, &mut |assoc_item_id| {
2749 slot = callback(assoc_item_id.into());
2755 fn iterate_assoc_items_dyn(
2757 db: &dyn HirDatabase,
2759 callback: &mut dyn FnMut(AssocItemId) -> bool,
2761 let def_crates = match method_resolution::def_crates(db, &self.ty, krate.id) {
2765 for krate in def_crates {
2766 let impls = db.inherent_impls_in_crate(krate);
2768 for impl_def in impls.for_self_ty(&self.ty) {
2769 for &item in db.impl_data(*impl_def).items.iter() {
2778 pub fn type_arguments(&self) -> impl Iterator<Item = Type> + '_ {
2783 .flat_map(|(_, substs)| substs.iter(Interner))
2784 .filter_map(|arg| arg.ty(Interner).cloned())
2785 .map(move |ty| self.derived(ty))
2788 pub fn iterate_method_candidates<T>(
2790 db: &dyn HirDatabase,
2792 traits_in_scope: &FxHashSet<TraitId>,
2793 name: Option<&Name>,
2794 mut callback: impl FnMut(Type, Function) -> Option<T>,
2796 let _p = profile::span("iterate_method_candidates");
2797 let mut slot = None;
2799 self.iterate_method_candidates_dyn(
2804 &mut |ty, assoc_item_id| {
2805 if let AssocItemId::FunctionId(func) = assoc_item_id {
2806 if let Some(res) = callback(self.derived(ty.clone()), func.into()) {
2808 return ControlFlow::Break(());
2811 ControlFlow::Continue(())
2817 fn iterate_method_candidates_dyn(
2819 db: &dyn HirDatabase,
2821 traits_in_scope: &FxHashSet<TraitId>,
2822 name: Option<&Name>,
2823 callback: &mut dyn FnMut(&Ty, AssocItemId) -> ControlFlow<()>,
2825 // There should be no inference vars in types passed here
2826 let canonical = hir_ty::replace_errors_with_variables(&self.ty);
2828 let env = self.env.clone();
2829 let krate = krate.id;
2831 method_resolution::iterate_method_candidates_dyn(
2839 method_resolution::LookupMode::MethodCall,
2840 &mut |ty, id| callback(&ty.value, id),
2844 pub fn iterate_path_candidates<T>(
2846 db: &dyn HirDatabase,
2848 traits_in_scope: &FxHashSet<TraitId>,
2849 name: Option<&Name>,
2850 mut callback: impl FnMut(Type, AssocItem) -> Option<T>,
2852 let _p = profile::span("iterate_path_candidates");
2853 let mut slot = None;
2854 self.iterate_path_candidates_dyn(
2859 &mut |ty, assoc_item_id| {
2860 if let Some(res) = callback(self.derived(ty.clone()), assoc_item_id.into()) {
2862 return ControlFlow::Break(());
2864 ControlFlow::Continue(())
2870 fn iterate_path_candidates_dyn(
2872 db: &dyn HirDatabase,
2874 traits_in_scope: &FxHashSet<TraitId>,
2875 name: Option<&Name>,
2876 callback: &mut dyn FnMut(&Ty, AssocItemId) -> ControlFlow<()>,
2878 let canonical = hir_ty::replace_errors_with_variables(&self.ty);
2880 let env = self.env.clone();
2881 let krate = krate.id;
2883 method_resolution::iterate_method_candidates_dyn(
2891 method_resolution::LookupMode::Path,
2892 &mut |ty, id| callback(&ty.value, id),
2896 pub fn as_adt(&self) -> Option<Adt> {
2897 let (adt, _subst) = self.ty.as_adt()?;
2901 pub fn as_builtin(&self) -> Option<BuiltinType> {
2902 self.ty.as_builtin().map(|inner| BuiltinType { inner })
2905 pub fn as_dyn_trait(&self) -> Option<Trait> {
2906 self.ty.dyn_trait().map(Into::into)
2909 /// If a type can be represented as `dyn Trait`, returns all traits accessible via this type,
2910 /// or an empty iterator otherwise.
2911 pub fn applicable_inherent_traits<'a>(
2913 db: &'a dyn HirDatabase,
2914 ) -> impl Iterator<Item = Trait> + 'a {
2915 let _p = profile::span("applicable_inherent_traits");
2917 .filter_map(|ty| ty.dyn_trait())
2918 .flat_map(move |dyn_trait_id| hir_ty::all_super_traits(db.upcast(), dyn_trait_id))
2922 pub fn env_traits<'a>(&'a self, db: &'a dyn HirDatabase) -> impl Iterator<Item = Trait> + 'a {
2923 let _p = profile::span("env_traits");
2925 .filter(|ty| matches!(ty.kind(Interner), TyKind::Placeholder(_)))
2928 .traits_in_scope_from_clauses(ty)
2929 .flat_map(|t| hir_ty::all_super_traits(db.upcast(), t))
2934 pub fn as_impl_traits(&self, db: &dyn HirDatabase) -> Option<impl Iterator<Item = Trait>> {
2935 self.ty.impl_trait_bounds(db).map(|it| {
2936 it.into_iter().filter_map(|pred| match pred.skip_binders() {
2937 hir_ty::WhereClause::Implemented(trait_ref) => {
2938 Some(Trait::from(trait_ref.hir_trait_id()))
2945 pub fn as_associated_type_parent_trait(&self, db: &dyn HirDatabase) -> Option<Trait> {
2946 self.ty.associated_type_parent_trait(db).map(Into::into)
2949 fn derived(&self, ty: Ty) -> Type {
2950 Type { krate: self.krate, env: self.env.clone(), ty }
2953 pub fn walk(&self, db: &dyn HirDatabase, mut cb: impl FnMut(Type)) {
2954 // TypeWalk::walk for a Ty at first visits parameters and only after that the Ty itself.
2955 // We need a different order here.
2958 db: &dyn HirDatabase,
2960 substs: &Substitution,
2961 cb: &mut impl FnMut(Type),
2963 for ty in substs.iter(Interner).filter_map(|a| a.ty(Interner)) {
2964 walk_type(db, &type_.derived(ty.clone()), cb);
2969 db: &dyn HirDatabase,
2971 bounds: &[QuantifiedWhereClause],
2972 cb: &mut impl FnMut(Type),
2974 for pred in bounds {
2975 if let WhereClause::Implemented(trait_ref) = pred.skip_binders() {
2977 // skip the self type. it's likely the type we just got the bounds from
2979 trait_ref.substitution.iter(Interner).skip(1).filter_map(|a| a.ty(Interner))
2981 walk_type(db, &type_.derived(ty.clone()), cb);
2987 fn walk_type(db: &dyn HirDatabase, type_: &Type, cb: &mut impl FnMut(Type)) {
2988 let ty = type_.ty.strip_references();
2989 match ty.kind(Interner) {
2990 TyKind::Adt(_, substs) => {
2991 cb(type_.derived(ty.clone()));
2992 walk_substs(db, type_, substs, cb);
2994 TyKind::AssociatedType(_, substs) => {
2995 if ty.associated_type_parent_trait(db).is_some() {
2996 cb(type_.derived(ty.clone()));
2998 walk_substs(db, type_, substs, cb);
3000 TyKind::OpaqueType(_, subst) => {
3001 if let Some(bounds) = ty.impl_trait_bounds(db) {
3002 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
3005 walk_substs(db, type_, subst, cb);
3007 TyKind::Alias(AliasTy::Opaque(opaque_ty)) => {
3008 if let Some(bounds) = ty.impl_trait_bounds(db) {
3009 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
3012 walk_substs(db, type_, &opaque_ty.substitution, cb);
3014 TyKind::Placeholder(_) => {
3015 if let Some(bounds) = ty.impl_trait_bounds(db) {
3016 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
3019 TyKind::Dyn(bounds) => {
3022 &type_.derived(ty.clone()),
3023 bounds.bounds.skip_binders().interned(),
3028 TyKind::Ref(_, _, ty)
3029 | TyKind::Raw(_, ty)
3030 | TyKind::Array(ty, _)
3031 | TyKind::Slice(ty) => {
3032 walk_type(db, &type_.derived(ty.clone()), cb);
3035 TyKind::FnDef(_, substs)
3036 | TyKind::Tuple(_, substs)
3037 | TyKind::Closure(.., substs) => {
3038 walk_substs(db, type_, substs, cb);
3040 TyKind::Function(hir_ty::FnPointer { substitution, .. }) => {
3041 walk_substs(db, type_, &substitution.0, cb);
3048 walk_type(db, self, &mut cb);
3051 pub fn could_unify_with(&self, db: &dyn HirDatabase, other: &Type) -> bool {
3052 let tys = hir_ty::replace_errors_with_variables(&(self.ty.clone(), other.ty.clone()));
3053 could_unify(db, self.env.clone(), &tys)
3059 pub struct Callable {
3062 def: Option<CallableDefId>,
3063 pub(crate) is_bound_method: bool,
3066 pub enum CallableKind {
3068 TupleStruct(Struct),
3069 TupleEnumVariant(Variant),
3074 pub fn kind(&self) -> CallableKind {
3076 Some(CallableDefId::FunctionId(it)) => CallableKind::Function(it.into()),
3077 Some(CallableDefId::StructId(it)) => CallableKind::TupleStruct(it.into()),
3078 Some(CallableDefId::EnumVariantId(it)) => CallableKind::TupleEnumVariant(it.into()),
3079 None => CallableKind::Closure,
3082 pub fn receiver_param(&self, db: &dyn HirDatabase) -> Option<ast::SelfParam> {
3083 let func = match self.def {
3084 Some(CallableDefId::FunctionId(it)) if self.is_bound_method => it,
3087 let src = func.lookup(db.upcast()).source(db.upcast());
3088 let param_list = src.value.param_list()?;
3089 param_list.self_param()
3091 pub fn n_params(&self) -> usize {
3092 self.sig.params().len() - if self.is_bound_method { 1 } else { 0 }
3096 db: &dyn HirDatabase,
3097 ) -> Vec<(Option<Either<ast::SelfParam, ast::Pat>>, Type)> {
3102 .skip(if self.is_bound_method { 1 } else { 0 })
3103 .map(|ty| self.ty.derived(ty.clone()));
3104 let patterns = match self.def {
3105 Some(CallableDefId::FunctionId(func)) => {
3106 let src = func.lookup(db.upcast()).source(db.upcast());
3107 src.value.param_list().map(|param_list| {
3110 .map(|it| Some(Either::Left(it)))
3111 .filter(|_| !self.is_bound_method)
3113 .chain(param_list.params().map(|it| it.pat().map(Either::Right)))
3118 patterns.into_iter().flatten().chain(iter::repeat(None)).zip(types).collect()
3120 pub fn return_type(&self) -> Type {
3121 self.ty.derived(self.sig.ret().clone())
3126 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
3128 ModuleDef(ModuleDef),
3130 GenericParam(GenericParam),
3139 pub fn all_items(def: PerNs) -> ArrayVec<Self, 3> {
3140 let mut items = ArrayVec::new();
3142 match (def.take_types(), def.take_values()) {
3143 (Some(m1), None) => items.push(ScopeDef::ModuleDef(m1.into())),
3144 (None, Some(m2)) => items.push(ScopeDef::ModuleDef(m2.into())),
3145 (Some(m1), Some(m2)) => {
3146 // Some items, like unit structs and enum variants, are
3147 // returned as both a type and a value. Here we want
3148 // to de-duplicate them.
3150 items.push(ScopeDef::ModuleDef(m1.into()));
3151 items.push(ScopeDef::ModuleDef(m2.into()));
3153 items.push(ScopeDef::ModuleDef(m1.into()));
3159 if let Some(macro_def_id) = def.take_macros() {
3160 items.push(ScopeDef::MacroDef(macro_def_id.into()));
3163 if items.is_empty() {
3164 items.push(ScopeDef::Unknown);
3170 pub fn attrs(&self, db: &dyn HirDatabase) -> Option<AttrsWithOwner> {
3172 ScopeDef::ModuleDef(it) => it.attrs(db),
3173 ScopeDef::MacroDef(it) => Some(it.attrs(db)),
3174 ScopeDef::GenericParam(it) => Some(it.attrs(db)),
3175 ScopeDef::ImplSelfType(_)
3176 | ScopeDef::AdtSelfType(_)
3177 | ScopeDef::Local(_)
3178 | ScopeDef::Label(_)
3179 | ScopeDef::Unknown => None,
3183 pub fn krate(&self, db: &dyn HirDatabase) -> Option<Crate> {
3185 ScopeDef::ModuleDef(it) => it.module(db).map(|m| m.krate()),
3186 ScopeDef::MacroDef(it) => it.module(db).map(|m| m.krate()),
3187 ScopeDef::GenericParam(it) => Some(it.module(db).krate()),
3188 ScopeDef::ImplSelfType(_) => None,
3189 ScopeDef::AdtSelfType(it) => Some(it.module(db).krate()),
3190 ScopeDef::Local(it) => Some(it.module(db).krate()),
3191 ScopeDef::Label(it) => Some(it.module(db).krate()),
3192 ScopeDef::Unknown => None,
3197 impl From<ItemInNs> for ScopeDef {
3198 fn from(item: ItemInNs) -> Self {
3200 ItemInNs::Types(id) => ScopeDef::ModuleDef(id),
3201 ItemInNs::Values(id) => ScopeDef::ModuleDef(id),
3202 ItemInNs::Macros(id) => ScopeDef::MacroDef(id),
3207 pub trait HasVisibility {
3208 fn visibility(&self, db: &dyn HirDatabase) -> Visibility;
3209 fn is_visible_from(&self, db: &dyn HirDatabase, module: Module) -> bool {
3210 let vis = self.visibility(db);
3211 vis.is_visible_from(db.upcast(), module.id)
3215 /// Trait for obtaining the defining crate of an item.
3216 pub trait HasCrate {
3217 fn krate(&self, db: &dyn HirDatabase) -> Crate;
3220 impl<T: hir_def::HasModule> HasCrate for T {
3221 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3222 self.module(db.upcast()).krate().into()
3226 impl HasCrate for AssocItem {
3227 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3228 self.module(db).krate()
3232 impl HasCrate for Field {
3233 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3234 self.parent_def(db).module(db).krate()
3238 impl HasCrate for Function {
3239 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3240 self.module(db).krate()
3244 impl HasCrate for Const {
3245 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3246 self.module(db).krate()
3250 impl HasCrate for TypeAlias {
3251 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3252 self.module(db).krate()
3256 impl HasCrate for Type {
3257 fn krate(&self, _db: &dyn HirDatabase) -> Crate {