]> git.proxmox.com Git - rustc.git/blob - src/tools/rust-analyzer/crates/hir/src/lib.rs
New upstream version 1.69.0+dfsg1
[rustc.git] / src / tools / rust-analyzer / crates / hir / src / lib.rs
1 //! HIR (previously known as descriptors) provides a high-level object oriented
2 //! access to Rust code.
3 //!
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.
7 //!
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".
11 //!
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.
15 //!
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>.
19
20 #![warn(rust_2018_idioms, unused_lifetimes, semicolon_in_expressions_from_macros)]
21 #![recursion_limit = "512"]
22
23 mod semantics;
24 mod source_analyzer;
25
26 mod from_id;
27 mod attrs;
28 mod has_source;
29
30 pub mod diagnostics;
31 pub mod db;
32 pub mod symbols;
33
34 mod display;
35
36 use std::{iter, ops::ControlFlow, sync::Arc};
37
38 use arrayvec::ArrayVec;
39 use base_db::{CrateDisplayName, CrateId, CrateOrigin, Edition, FileId, ProcMacroKind};
40 use either::Either;
41 use hir_def::{
42 adt::VariantData,
43 body::{BodyDiagnostic, SyntheticSyntax},
44 expr::{BindingAnnotation, ExprOrPatId, LabelId, Pat, PatId},
45 generics::{TypeOrConstParamData, TypeParamProvenance},
46 item_tree::ItemTreeNode,
47 lang_item::{LangItem, LangItemTarget},
48 layout::{Layout, LayoutError, ReprOptions},
49 nameres::{self, diagnostics::DefDiagnostic},
50 per_ns::PerNs,
51 resolver::{HasResolver, Resolver},
52 src::HasSource as _,
53 type_ref::ConstScalar,
54 AdtId, AssocItemId, AssocItemLoc, AttrDefId, ConstId, ConstParamId, DefWithBodyId, EnumId,
55 EnumVariantId, FunctionId, GenericDefId, HasModule, ImplId, ItemContainerId, LifetimeParamId,
56 LocalEnumVariantId, LocalFieldId, Lookup, MacroExpander, MacroId, ModuleId, StaticId, StructId,
57 TraitId, TypeAliasId, TypeOrConstParamId, TypeParamId, UnionId,
58 };
59 use hir_expand::{name::name, MacroCallKind};
60 use hir_ty::{
61 all_super_traits, autoderef,
62 consteval::{unknown_const_as_generic, ComputedExpr, ConstEvalError, ConstExt},
63 diagnostics::BodyValidationDiagnostic,
64 layout::layout_of_ty,
65 method_resolution::{self, TyFingerprint},
66 primitive::UintTy,
67 traits::FnTrait,
68 AliasTy, CallableDefId, CallableSig, Canonical, CanonicalVarKinds, Cast, ClosureId,
69 ConcreteConst, ConstValue, GenericArgData, Interner, ParamKind, QuantifiedWhereClause, Scalar,
70 Substitution, TraitEnvironment, TraitRefExt, Ty, TyBuilder, TyDefId, TyExt, TyKind,
71 WhereClause,
72 };
73 use itertools::Itertools;
74 use nameres::diagnostics::DefDiagnosticKind;
75 use once_cell::unsync::Lazy;
76 use rustc_hash::FxHashSet;
77 use stdx::{impl_from, never};
78 use syntax::{
79 ast::{self, HasAttrs as _, HasDocComments, HasName},
80 AstNode, AstPtr, SmolStr, SyntaxNodePtr, TextRange, T,
81 };
82
83 use crate::db::{DefDatabase, HirDatabase};
84
85 pub use crate::{
86 attrs::{HasAttrs, Namespace},
87 diagnostics::{
88 AnyDiagnostic, BreakOutsideOfLoop, InactiveCode, IncorrectCase, InvalidDeriveTarget,
89 MacroError, MalformedDerive, MismatchedArgCount, MissingFields, MissingMatchArms,
90 MissingUnsafe, NoSuchField, PrivateAssocItem, PrivateField,
91 ReplaceFilterMapNextWithFindMap, TypeMismatch, UnimplementedBuiltinMacro,
92 UnresolvedExternCrate, UnresolvedImport, UnresolvedMacroCall, UnresolvedModule,
93 UnresolvedProcMacro,
94 },
95 has_source::HasSource,
96 semantics::{PathResolution, Semantics, SemanticsScope, TypeInfo, VisibleTraits},
97 };
98
99 // Be careful with these re-exports.
100 //
101 // `hir` is the boundary between the compiler and the IDE. It should try hard to
102 // isolate the compiler from the ide, to allow the two to be refactored
103 // independently. Re-exporting something from the compiler is the sure way to
104 // breach the boundary.
105 //
106 // Generally, a refactoring which *removes* a name from this list is a good
107 // idea!
108 pub use {
109 cfg::{CfgAtom, CfgExpr, CfgOptions},
110 hir_def::{
111 adt::StructKind,
112 attr::{Attrs, AttrsWithOwner, Documentation},
113 builtin_attr::AttributeTemplate,
114 find_path::PrefixKind,
115 import_map,
116 nameres::ModuleSource,
117 path::{ModPath, PathKind},
118 type_ref::{Mutability, TypeRef},
119 visibility::Visibility,
120 // FIXME: This is here since it is input of a method in `HirWrite`
121 // and things outside of hir need to implement that trait. We probably
122 // should move whole `hir_ty::display` to this crate so we will become
123 // able to use `ModuleDef` or `Definition` instead of `ModuleDefId`.
124 ModuleDefId,
125 },
126 hir_expand::{
127 attrs::Attr,
128 name::{known, Name},
129 ExpandResult, HirFileId, InFile, MacroFile, Origin,
130 },
131 hir_ty::{
132 display::{HirDisplay, HirDisplayError, HirWrite},
133 PointerCast, Safety,
134 },
135 };
136
137 // These are negative re-exports: pub using these names is forbidden, they
138 // should remain private to hir internals.
139 #[allow(unused)]
140 use {
141 hir_def::path::Path,
142 hir_expand::{hygiene::Hygiene, name::AsName},
143 };
144
145 /// hir::Crate describes a single crate. It's the main interface with which
146 /// a crate's dependencies interact. Mostly, it should be just a proxy for the
147 /// root module.
148 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
149 pub struct Crate {
150 pub(crate) id: CrateId,
151 }
152
153 #[derive(Debug)]
154 pub struct CrateDependency {
155 pub krate: Crate,
156 pub name: Name,
157 }
158
159 impl Crate {
160 pub fn origin(self, db: &dyn HirDatabase) -> CrateOrigin {
161 db.crate_graph()[self.id].origin.clone()
162 }
163
164 pub fn is_builtin(self, db: &dyn HirDatabase) -> bool {
165 matches!(self.origin(db), CrateOrigin::Lang(_))
166 }
167
168 pub fn dependencies(self, db: &dyn HirDatabase) -> Vec<CrateDependency> {
169 db.crate_graph()[self.id]
170 .dependencies
171 .iter()
172 .map(|dep| {
173 let krate = Crate { id: dep.crate_id };
174 let name = dep.as_name();
175 CrateDependency { krate, name }
176 })
177 .collect()
178 }
179
180 pub fn reverse_dependencies(self, db: &dyn HirDatabase) -> Vec<Crate> {
181 let crate_graph = db.crate_graph();
182 crate_graph
183 .iter()
184 .filter(|&krate| {
185 crate_graph[krate].dependencies.iter().any(|it| it.crate_id == self.id)
186 })
187 .map(|id| Crate { id })
188 .collect()
189 }
190
191 pub fn transitive_reverse_dependencies(
192 self,
193 db: &dyn HirDatabase,
194 ) -> impl Iterator<Item = Crate> {
195 db.crate_graph().transitive_rev_deps(self.id).map(|id| Crate { id })
196 }
197
198 pub fn root_module(self, db: &dyn HirDatabase) -> Module {
199 let def_map = db.crate_def_map(self.id);
200 Module { id: def_map.module_id(def_map.root()) }
201 }
202
203 pub fn modules(self, db: &dyn HirDatabase) -> Vec<Module> {
204 let def_map = db.crate_def_map(self.id);
205 def_map.modules().map(|(id, _)| def_map.module_id(id).into()).collect()
206 }
207
208 pub fn root_file(self, db: &dyn HirDatabase) -> FileId {
209 db.crate_graph()[self.id].root_file_id
210 }
211
212 pub fn edition(self, db: &dyn HirDatabase) -> Edition {
213 db.crate_graph()[self.id].edition
214 }
215
216 pub fn version(self, db: &dyn HirDatabase) -> Option<String> {
217 db.crate_graph()[self.id].version.clone()
218 }
219
220 pub fn display_name(self, db: &dyn HirDatabase) -> Option<CrateDisplayName> {
221 db.crate_graph()[self.id].display_name.clone()
222 }
223
224 pub fn query_external_importables(
225 self,
226 db: &dyn DefDatabase,
227 query: import_map::Query,
228 ) -> impl Iterator<Item = Either<ModuleDef, Macro>> {
229 let _p = profile::span("query_external_importables");
230 import_map::search_dependencies(db, self.into(), query).into_iter().map(|item| {
231 match ItemInNs::from(item) {
232 ItemInNs::Types(mod_id) | ItemInNs::Values(mod_id) => Either::Left(mod_id),
233 ItemInNs::Macros(mac_id) => Either::Right(mac_id),
234 }
235 })
236 }
237
238 pub fn all(db: &dyn HirDatabase) -> Vec<Crate> {
239 db.crate_graph().iter().map(|id| Crate { id }).collect()
240 }
241
242 /// Try to get the root URL of the documentation of a crate.
243 pub fn get_html_root_url(self: &Crate, db: &dyn HirDatabase) -> Option<String> {
244 // Look for #![doc(html_root_url = "...")]
245 let attrs = db.attrs(AttrDefId::ModuleId(self.root_module(db).into()));
246 let doc_url = attrs.by_key("doc").find_string_value_in_tt("html_root_url");
247 doc_url.map(|s| s.trim_matches('"').trim_end_matches('/').to_owned() + "/")
248 }
249
250 pub fn cfg(&self, db: &dyn HirDatabase) -> CfgOptions {
251 db.crate_graph()[self.id].cfg_options.clone()
252 }
253
254 pub fn potential_cfg(&self, db: &dyn HirDatabase) -> CfgOptions {
255 db.crate_graph()[self.id].potential_cfg_options.clone()
256 }
257 }
258
259 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
260 pub struct Module {
261 pub(crate) id: ModuleId,
262 }
263
264 /// The defs which can be visible in the module.
265 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
266 pub enum ModuleDef {
267 Module(Module),
268 Function(Function),
269 Adt(Adt),
270 // Can't be directly declared, but can be imported.
271 Variant(Variant),
272 Const(Const),
273 Static(Static),
274 Trait(Trait),
275 TypeAlias(TypeAlias),
276 BuiltinType(BuiltinType),
277 Macro(Macro),
278 }
279 impl_from!(
280 Module,
281 Function,
282 Adt(Struct, Enum, Union),
283 Variant,
284 Const,
285 Static,
286 Trait,
287 TypeAlias,
288 BuiltinType,
289 Macro
290 for ModuleDef
291 );
292
293 impl From<VariantDef> for ModuleDef {
294 fn from(var: VariantDef) -> Self {
295 match var {
296 VariantDef::Struct(t) => Adt::from(t).into(),
297 VariantDef::Union(t) => Adt::from(t).into(),
298 VariantDef::Variant(t) => t.into(),
299 }
300 }
301 }
302
303 impl ModuleDef {
304 pub fn module(self, db: &dyn HirDatabase) -> Option<Module> {
305 match self {
306 ModuleDef::Module(it) => it.parent(db),
307 ModuleDef::Function(it) => Some(it.module(db)),
308 ModuleDef::Adt(it) => Some(it.module(db)),
309 ModuleDef::Variant(it) => Some(it.module(db)),
310 ModuleDef::Const(it) => Some(it.module(db)),
311 ModuleDef::Static(it) => Some(it.module(db)),
312 ModuleDef::Trait(it) => Some(it.module(db)),
313 ModuleDef::TypeAlias(it) => Some(it.module(db)),
314 ModuleDef::Macro(it) => Some(it.module(db)),
315 ModuleDef::BuiltinType(_) => None,
316 }
317 }
318
319 pub fn canonical_path(&self, db: &dyn HirDatabase) -> Option<String> {
320 let mut segments = vec![self.name(db)?];
321 for m in self.module(db)?.path_to_root(db) {
322 segments.extend(m.name(db))
323 }
324 segments.reverse();
325 Some(segments.into_iter().join("::"))
326 }
327
328 pub fn canonical_module_path(
329 &self,
330 db: &dyn HirDatabase,
331 ) -> Option<impl Iterator<Item = Module>> {
332 self.module(db).map(|it| it.path_to_root(db).into_iter().rev())
333 }
334
335 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
336 let name = match self {
337 ModuleDef::Module(it) => it.name(db)?,
338 ModuleDef::Const(it) => it.name(db)?,
339 ModuleDef::Adt(it) => it.name(db),
340 ModuleDef::Trait(it) => it.name(db),
341 ModuleDef::Function(it) => it.name(db),
342 ModuleDef::Variant(it) => it.name(db),
343 ModuleDef::TypeAlias(it) => it.name(db),
344 ModuleDef::Static(it) => it.name(db),
345 ModuleDef::Macro(it) => it.name(db),
346 ModuleDef::BuiltinType(it) => it.name(),
347 };
348 Some(name)
349 }
350
351 pub fn diagnostics(self, db: &dyn HirDatabase) -> Vec<AnyDiagnostic> {
352 let id = match self {
353 ModuleDef::Adt(it) => match it {
354 Adt::Struct(it) => it.id.into(),
355 Adt::Enum(it) => it.id.into(),
356 Adt::Union(it) => it.id.into(),
357 },
358 ModuleDef::Trait(it) => it.id.into(),
359 ModuleDef::Function(it) => it.id.into(),
360 ModuleDef::TypeAlias(it) => it.id.into(),
361 ModuleDef::Module(it) => it.id.into(),
362 ModuleDef::Const(it) => it.id.into(),
363 ModuleDef::Static(it) => it.id.into(),
364 ModuleDef::Variant(it) => {
365 EnumVariantId { parent: it.parent.into(), local_id: it.id }.into()
366 }
367 ModuleDef::BuiltinType(_) | ModuleDef::Macro(_) => return Vec::new(),
368 };
369
370 let module = match self.module(db) {
371 Some(it) => it,
372 None => return Vec::new(),
373 };
374
375 let mut acc = Vec::new();
376
377 match self.as_def_with_body() {
378 Some(def) => {
379 def.diagnostics(db, &mut acc);
380 }
381 None => {
382 for diag in hir_ty::diagnostics::incorrect_case(db, module.id.krate(), id) {
383 acc.push(diag.into())
384 }
385 }
386 }
387
388 acc
389 }
390
391 pub fn as_def_with_body(self) -> Option<DefWithBody> {
392 match self {
393 ModuleDef::Function(it) => Some(it.into()),
394 ModuleDef::Const(it) => Some(it.into()),
395 ModuleDef::Static(it) => Some(it.into()),
396 ModuleDef::Variant(it) => Some(it.into()),
397
398 ModuleDef::Module(_)
399 | ModuleDef::Adt(_)
400 | ModuleDef::Trait(_)
401 | ModuleDef::TypeAlias(_)
402 | ModuleDef::Macro(_)
403 | ModuleDef::BuiltinType(_) => None,
404 }
405 }
406
407 pub fn attrs(&self, db: &dyn HirDatabase) -> Option<AttrsWithOwner> {
408 Some(match self {
409 ModuleDef::Module(it) => it.attrs(db),
410 ModuleDef::Function(it) => it.attrs(db),
411 ModuleDef::Adt(it) => it.attrs(db),
412 ModuleDef::Variant(it) => it.attrs(db),
413 ModuleDef::Const(it) => it.attrs(db),
414 ModuleDef::Static(it) => it.attrs(db),
415 ModuleDef::Trait(it) => it.attrs(db),
416 ModuleDef::TypeAlias(it) => it.attrs(db),
417 ModuleDef::Macro(it) => it.attrs(db),
418 ModuleDef::BuiltinType(_) => return None,
419 })
420 }
421 }
422
423 impl HasVisibility for ModuleDef {
424 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
425 match *self {
426 ModuleDef::Module(it) => it.visibility(db),
427 ModuleDef::Function(it) => it.visibility(db),
428 ModuleDef::Adt(it) => it.visibility(db),
429 ModuleDef::Const(it) => it.visibility(db),
430 ModuleDef::Static(it) => it.visibility(db),
431 ModuleDef::Trait(it) => it.visibility(db),
432 ModuleDef::TypeAlias(it) => it.visibility(db),
433 ModuleDef::Variant(it) => it.visibility(db),
434 ModuleDef::Macro(it) => it.visibility(db),
435 ModuleDef::BuiltinType(_) => Visibility::Public,
436 }
437 }
438 }
439
440 impl Module {
441 /// Name of this module.
442 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
443 let def_map = self.id.def_map(db.upcast());
444 let parent = def_map[self.id.local_id].parent?;
445 def_map[parent].children.iter().find_map(|(name, module_id)| {
446 if *module_id == self.id.local_id {
447 Some(name.clone())
448 } else {
449 None
450 }
451 })
452 }
453
454 /// Returns the crate this module is part of.
455 pub fn krate(self) -> Crate {
456 Crate { id: self.id.krate() }
457 }
458
459 /// Topmost parent of this module. Every module has a `crate_root`, but some
460 /// might be missing `krate`. This can happen if a module's file is not included
461 /// in the module tree of any target in `Cargo.toml`.
462 pub fn crate_root(self, db: &dyn HirDatabase) -> Module {
463 let def_map = db.crate_def_map(self.id.krate());
464 Module { id: def_map.module_id(def_map.root()) }
465 }
466
467 pub fn is_crate_root(self, db: &dyn HirDatabase) -> bool {
468 let def_map = db.crate_def_map(self.id.krate());
469 def_map.root() == self.id.local_id
470 }
471
472 /// Iterates over all child modules.
473 pub fn children(self, db: &dyn HirDatabase) -> impl Iterator<Item = Module> {
474 let def_map = self.id.def_map(db.upcast());
475 let children = def_map[self.id.local_id]
476 .children
477 .values()
478 .map(|module_id| Module { id: def_map.module_id(*module_id) })
479 .collect::<Vec<_>>();
480 children.into_iter()
481 }
482
483 /// Finds a parent module.
484 pub fn parent(self, db: &dyn HirDatabase) -> Option<Module> {
485 // FIXME: handle block expressions as modules (their parent is in a different DefMap)
486 let def_map = self.id.def_map(db.upcast());
487 let parent_id = def_map[self.id.local_id].parent?;
488 Some(Module { id: def_map.module_id(parent_id) })
489 }
490
491 pub fn path_to_root(self, db: &dyn HirDatabase) -> Vec<Module> {
492 let mut res = vec![self];
493 let mut curr = self;
494 while let Some(next) = curr.parent(db) {
495 res.push(next);
496 curr = next
497 }
498 res
499 }
500
501 /// Returns a `ModuleScope`: a set of items, visible in this module.
502 pub fn scope(
503 self,
504 db: &dyn HirDatabase,
505 visible_from: Option<Module>,
506 ) -> Vec<(Name, ScopeDef)> {
507 self.id.def_map(db.upcast())[self.id.local_id]
508 .scope
509 .entries()
510 .filter_map(|(name, def)| {
511 if let Some(m) = visible_from {
512 let filtered =
513 def.filter_visibility(|vis| vis.is_visible_from(db.upcast(), m.id));
514 if filtered.is_none() && !def.is_none() {
515 None
516 } else {
517 Some((name, filtered))
518 }
519 } else {
520 Some((name, def))
521 }
522 })
523 .flat_map(|(name, def)| {
524 ScopeDef::all_items(def).into_iter().map(move |item| (name.clone(), item))
525 })
526 .collect()
527 }
528
529 /// Fills `acc` with the module's diagnostics.
530 pub fn diagnostics(self, db: &dyn HirDatabase, acc: &mut Vec<AnyDiagnostic>) {
531 let _p = profile::span("Module::diagnostics").detail(|| {
532 format!("{:?}", self.name(db).map_or("<unknown>".into(), |name| name.to_string()))
533 });
534 let def_map = self.id.def_map(db.upcast());
535 for diag in def_map.diagnostics() {
536 if diag.in_module != self.id.local_id {
537 // FIXME: This is accidentally quadratic.
538 continue;
539 }
540 emit_def_diagnostic(db, acc, diag);
541 }
542 for decl in self.declarations(db) {
543 match decl {
544 ModuleDef::Module(m) => {
545 // Only add diagnostics from inline modules
546 if def_map[m.id.local_id].origin.is_inline() {
547 m.diagnostics(db, acc)
548 }
549 }
550 ModuleDef::Trait(t) => {
551 for diag in db.trait_data_with_diagnostics(t.id).1.iter() {
552 emit_def_diagnostic(db, acc, diag);
553 }
554 acc.extend(decl.diagnostics(db))
555 }
556 ModuleDef::Adt(adt) => {
557 match adt {
558 Adt::Struct(s) => {
559 for diag in db.struct_data_with_diagnostics(s.id).1.iter() {
560 emit_def_diagnostic(db, acc, diag);
561 }
562 }
563 Adt::Union(u) => {
564 for diag in db.union_data_with_diagnostics(u.id).1.iter() {
565 emit_def_diagnostic(db, acc, diag);
566 }
567 }
568 Adt::Enum(e) => {
569 for v in e.variants(db) {
570 acc.extend(ModuleDef::Variant(v).diagnostics(db));
571 }
572
573 for diag in db.enum_data_with_diagnostics(e.id).1.iter() {
574 emit_def_diagnostic(db, acc, diag);
575 }
576 }
577 }
578 acc.extend(decl.diagnostics(db))
579 }
580 _ => acc.extend(decl.diagnostics(db)),
581 }
582 }
583
584 for impl_def in self.impl_defs(db) {
585 for diag in db.impl_data_with_diagnostics(impl_def.id).1.iter() {
586 emit_def_diagnostic(db, acc, diag);
587 }
588
589 for item in impl_def.items(db) {
590 let def: DefWithBody = match item {
591 AssocItem::Function(it) => it.into(),
592 AssocItem::Const(it) => it.into(),
593 AssocItem::TypeAlias(_) => continue,
594 };
595
596 def.diagnostics(db, acc);
597 }
598 }
599 }
600
601 pub fn declarations(self, db: &dyn HirDatabase) -> Vec<ModuleDef> {
602 let def_map = self.id.def_map(db.upcast());
603 let scope = &def_map[self.id.local_id].scope;
604 scope
605 .declarations()
606 .map(ModuleDef::from)
607 .chain(scope.unnamed_consts().map(|id| ModuleDef::Const(Const::from(id))))
608 .collect()
609 }
610
611 pub fn legacy_macros(self, db: &dyn HirDatabase) -> Vec<Macro> {
612 let def_map = self.id.def_map(db.upcast());
613 let scope = &def_map[self.id.local_id].scope;
614 scope.legacy_macros().flat_map(|(_, it)| it).map(|&it| it.into()).collect()
615 }
616
617 pub fn impl_defs(self, db: &dyn HirDatabase) -> Vec<Impl> {
618 let def_map = self.id.def_map(db.upcast());
619 def_map[self.id.local_id].scope.impls().map(Impl::from).collect()
620 }
621
622 /// Finds a path that can be used to refer to the given item from within
623 /// this module, if possible.
624 pub fn find_use_path(
625 self,
626 db: &dyn DefDatabase,
627 item: impl Into<ItemInNs>,
628 prefer_no_std: bool,
629 ) -> Option<ModPath> {
630 hir_def::find_path::find_path(db, item.into().into(), self.into(), prefer_no_std)
631 }
632
633 /// Finds a path that can be used to refer to the given item from within
634 /// this module, if possible. This is used for returning import paths for use-statements.
635 pub fn find_use_path_prefixed(
636 self,
637 db: &dyn DefDatabase,
638 item: impl Into<ItemInNs>,
639 prefix_kind: PrefixKind,
640 prefer_no_std: bool,
641 ) -> Option<ModPath> {
642 hir_def::find_path::find_path_prefixed(
643 db,
644 item.into().into(),
645 self.into(),
646 prefix_kind,
647 prefer_no_std,
648 )
649 }
650 }
651
652 fn emit_def_diagnostic(db: &dyn HirDatabase, acc: &mut Vec<AnyDiagnostic>, diag: &DefDiagnostic) {
653 match &diag.kind {
654 DefDiagnosticKind::UnresolvedModule { ast: declaration, candidates } => {
655 let decl = declaration.to_node(db.upcast());
656 acc.push(
657 UnresolvedModule {
658 decl: InFile::new(declaration.file_id, AstPtr::new(&decl)),
659 candidates: candidates.clone(),
660 }
661 .into(),
662 )
663 }
664 DefDiagnosticKind::UnresolvedExternCrate { ast } => {
665 let item = ast.to_node(db.upcast());
666 acc.push(
667 UnresolvedExternCrate { decl: InFile::new(ast.file_id, AstPtr::new(&item)) }.into(),
668 );
669 }
670
671 DefDiagnosticKind::UnresolvedImport { id, index } => {
672 let file_id = id.file_id();
673 let item_tree = id.item_tree(db.upcast());
674 let import = &item_tree[id.value];
675
676 let use_tree = import.use_tree_to_ast(db.upcast(), file_id, *index);
677 acc.push(
678 UnresolvedImport { decl: InFile::new(file_id, AstPtr::new(&use_tree)) }.into(),
679 );
680 }
681
682 DefDiagnosticKind::UnconfiguredCode { ast, cfg, opts } => {
683 let item = ast.to_node(db.upcast());
684 acc.push(
685 InactiveCode {
686 node: ast.with_value(AstPtr::new(&item).into()),
687 cfg: cfg.clone(),
688 opts: opts.clone(),
689 }
690 .into(),
691 );
692 }
693
694 DefDiagnosticKind::UnresolvedProcMacro { ast, krate } => {
695 let (node, precise_location, macro_name, kind) = precise_macro_call_location(ast, db);
696 acc.push(
697 UnresolvedProcMacro { node, precise_location, macro_name, kind, krate: *krate }
698 .into(),
699 );
700 }
701
702 DefDiagnosticKind::UnresolvedMacroCall { ast, path } => {
703 let (node, precise_location, _, _) = precise_macro_call_location(ast, db);
704 acc.push(
705 UnresolvedMacroCall {
706 macro_call: node,
707 precise_location,
708 path: path.clone(),
709 is_bang: matches!(ast, MacroCallKind::FnLike { .. }),
710 }
711 .into(),
712 );
713 }
714
715 DefDiagnosticKind::MacroError { ast, message } => {
716 let (node, precise_location, _, _) = precise_macro_call_location(ast, db);
717 acc.push(MacroError { node, precise_location, message: message.clone() }.into());
718 }
719
720 DefDiagnosticKind::UnimplementedBuiltinMacro { ast } => {
721 let node = ast.to_node(db.upcast());
722 // Must have a name, otherwise we wouldn't emit it.
723 let name = node.name().expect("unimplemented builtin macro with no name");
724 acc.push(
725 UnimplementedBuiltinMacro {
726 node: ast.with_value(SyntaxNodePtr::from(AstPtr::new(&name))),
727 }
728 .into(),
729 );
730 }
731 DefDiagnosticKind::InvalidDeriveTarget { ast, id } => {
732 let node = ast.to_node(db.upcast());
733 let derive = node.attrs().nth(*id as usize);
734 match derive {
735 Some(derive) => {
736 acc.push(
737 InvalidDeriveTarget {
738 node: ast.with_value(SyntaxNodePtr::from(AstPtr::new(&derive))),
739 }
740 .into(),
741 );
742 }
743 None => stdx::never!("derive diagnostic on item without derive attribute"),
744 }
745 }
746 DefDiagnosticKind::MalformedDerive { ast, id } => {
747 let node = ast.to_node(db.upcast());
748 let derive = node.attrs().nth(*id as usize);
749 match derive {
750 Some(derive) => {
751 acc.push(
752 MalformedDerive {
753 node: ast.with_value(SyntaxNodePtr::from(AstPtr::new(&derive))),
754 }
755 .into(),
756 );
757 }
758 None => stdx::never!("derive diagnostic on item without derive attribute"),
759 }
760 }
761 }
762 }
763
764 fn precise_macro_call_location(
765 ast: &MacroCallKind,
766 db: &dyn HirDatabase,
767 ) -> (InFile<SyntaxNodePtr>, Option<TextRange>, Option<String>, MacroKind) {
768 // FIXME: maaybe we actually want slightly different ranges for the different macro diagnostics
769 // - e.g. the full attribute for macro errors, but only the name for name resolution
770 match ast {
771 MacroCallKind::FnLike { ast_id, .. } => {
772 let node = ast_id.to_node(db.upcast());
773 (
774 ast_id.with_value(SyntaxNodePtr::from(AstPtr::new(&node))),
775 node.path()
776 .and_then(|it| it.segment())
777 .and_then(|it| it.name_ref())
778 .map(|it| it.syntax().text_range()),
779 node.path().and_then(|it| it.segment()).map(|it| it.to_string()),
780 MacroKind::ProcMacro,
781 )
782 }
783 MacroCallKind::Derive { ast_id, derive_attr_index, derive_index } => {
784 let node = ast_id.to_node(db.upcast());
785 // Compute the precise location of the macro name's token in the derive
786 // list.
787 let token = (|| {
788 let derive_attr = node
789 .doc_comments_and_attrs()
790 .nth(derive_attr_index.ast_index())
791 .and_then(Either::left)?;
792 let token_tree = derive_attr.meta()?.token_tree()?;
793 let group_by = token_tree
794 .syntax()
795 .children_with_tokens()
796 .filter_map(|elem| match elem {
797 syntax::NodeOrToken::Token(tok) => Some(tok),
798 _ => None,
799 })
800 .group_by(|t| t.kind() == T![,]);
801 let (_, mut group) = group_by
802 .into_iter()
803 .filter(|&(comma, _)| !comma)
804 .nth(*derive_index as usize)?;
805 group.find(|t| t.kind() == T![ident])
806 })();
807 (
808 ast_id.with_value(SyntaxNodePtr::from(AstPtr::new(&node))),
809 token.as_ref().map(|tok| tok.text_range()),
810 token.as_ref().map(ToString::to_string),
811 MacroKind::Derive,
812 )
813 }
814 MacroCallKind::Attr { ast_id, invoc_attr_index, .. } => {
815 let node = ast_id.to_node(db.upcast());
816 let attr = node
817 .doc_comments_and_attrs()
818 .nth(invoc_attr_index.ast_index())
819 .and_then(Either::left)
820 .unwrap_or_else(|| {
821 panic!("cannot find attribute #{}", invoc_attr_index.ast_index())
822 });
823
824 (
825 ast_id.with_value(SyntaxNodePtr::from(AstPtr::new(&attr))),
826 Some(attr.syntax().text_range()),
827 attr.path()
828 .and_then(|path| path.segment())
829 .and_then(|seg| seg.name_ref())
830 .as_ref()
831 .map(ToString::to_string),
832 MacroKind::Attr,
833 )
834 }
835 }
836 }
837
838 impl HasVisibility for Module {
839 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
840 let def_map = self.id.def_map(db.upcast());
841 let module_data = &def_map[self.id.local_id];
842 module_data.visibility
843 }
844 }
845
846 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
847 pub struct Field {
848 pub(crate) parent: VariantDef,
849 pub(crate) id: LocalFieldId,
850 }
851
852 #[derive(Debug, PartialEq, Eq)]
853 pub enum FieldSource {
854 Named(ast::RecordField),
855 Pos(ast::TupleField),
856 }
857
858 impl Field {
859 pub fn name(&self, db: &dyn HirDatabase) -> Name {
860 self.parent.variant_data(db).fields()[self.id].name.clone()
861 }
862
863 pub fn index(&self) -> usize {
864 u32::from(self.id.into_raw()) as usize
865 }
866
867 /// Returns the type as in the signature of the struct (i.e., with
868 /// placeholder types for type parameters). Only use this in the context of
869 /// the field definition.
870 pub fn ty(&self, db: &dyn HirDatabase) -> Type {
871 let var_id = self.parent.into();
872 let generic_def_id: GenericDefId = match self.parent {
873 VariantDef::Struct(it) => it.id.into(),
874 VariantDef::Union(it) => it.id.into(),
875 VariantDef::Variant(it) => it.parent.id.into(),
876 };
877 let substs = TyBuilder::placeholder_subst(db, generic_def_id);
878 let ty = db.field_types(var_id)[self.id].clone().substitute(Interner, &substs);
879 Type::new(db, var_id, ty)
880 }
881
882 pub fn layout(&self, db: &dyn HirDatabase) -> Result<Layout, LayoutError> {
883 layout_of_ty(db, &self.ty(db).ty, self.parent.module(db).krate().into())
884 }
885
886 pub fn parent_def(&self, _db: &dyn HirDatabase) -> VariantDef {
887 self.parent
888 }
889 }
890
891 impl HasVisibility for Field {
892 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
893 let variant_data = self.parent.variant_data(db);
894 let visibility = &variant_data.fields()[self.id].visibility;
895 let parent_id: hir_def::VariantId = self.parent.into();
896 visibility.resolve(db.upcast(), &parent_id.resolver(db.upcast()))
897 }
898 }
899
900 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
901 pub struct Struct {
902 pub(crate) id: StructId,
903 }
904
905 impl Struct {
906 pub fn module(self, db: &dyn HirDatabase) -> Module {
907 Module { id: self.id.lookup(db.upcast()).container }
908 }
909
910 pub fn name(self, db: &dyn HirDatabase) -> Name {
911 db.struct_data(self.id).name.clone()
912 }
913
914 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
915 db.struct_data(self.id)
916 .variant_data
917 .fields()
918 .iter()
919 .map(|(id, _)| Field { parent: self.into(), id })
920 .collect()
921 }
922
923 pub fn ty(self, db: &dyn HirDatabase) -> Type {
924 Type::from_def(db, self.id)
925 }
926
927 pub fn repr(self, db: &dyn HirDatabase) -> Option<ReprOptions> {
928 db.struct_data(self.id).repr
929 }
930
931 pub fn kind(self, db: &dyn HirDatabase) -> StructKind {
932 self.variant_data(db).kind()
933 }
934
935 fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
936 db.struct_data(self.id).variant_data.clone()
937 }
938 }
939
940 impl HasVisibility for Struct {
941 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
942 db.struct_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
943 }
944 }
945
946 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
947 pub struct Union {
948 pub(crate) id: UnionId,
949 }
950
951 impl Union {
952 pub fn name(self, db: &dyn HirDatabase) -> Name {
953 db.union_data(self.id).name.clone()
954 }
955
956 pub fn module(self, db: &dyn HirDatabase) -> Module {
957 Module { id: self.id.lookup(db.upcast()).container }
958 }
959
960 pub fn ty(self, db: &dyn HirDatabase) -> Type {
961 Type::from_def(db, self.id)
962 }
963
964 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
965 db.union_data(self.id)
966 .variant_data
967 .fields()
968 .iter()
969 .map(|(id, _)| Field { parent: self.into(), id })
970 .collect()
971 }
972
973 fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
974 db.union_data(self.id).variant_data.clone()
975 }
976 }
977
978 impl HasVisibility for Union {
979 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
980 db.union_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
981 }
982 }
983
984 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
985 pub struct Enum {
986 pub(crate) id: EnumId,
987 }
988
989 impl Enum {
990 pub fn module(self, db: &dyn HirDatabase) -> Module {
991 Module { id: self.id.lookup(db.upcast()).container }
992 }
993
994 pub fn name(self, db: &dyn HirDatabase) -> Name {
995 db.enum_data(self.id).name.clone()
996 }
997
998 pub fn variants(self, db: &dyn HirDatabase) -> Vec<Variant> {
999 db.enum_data(self.id).variants.iter().map(|(id, _)| Variant { parent: self, id }).collect()
1000 }
1001
1002 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1003 Type::from_def(db, self.id)
1004 }
1005
1006 /// The type of the enum variant bodies.
1007 pub fn variant_body_ty(self, db: &dyn HirDatabase) -> Type {
1008 Type::new_for_crate(
1009 self.id.lookup(db.upcast()).container.krate(),
1010 TyBuilder::builtin(match db.enum_data(self.id).variant_body_type() {
1011 hir_def::layout::IntegerType::Pointer(sign) => match sign {
1012 true => hir_def::builtin_type::BuiltinType::Int(
1013 hir_def::builtin_type::BuiltinInt::Isize,
1014 ),
1015 false => hir_def::builtin_type::BuiltinType::Uint(
1016 hir_def::builtin_type::BuiltinUint::Usize,
1017 ),
1018 },
1019 hir_def::layout::IntegerType::Fixed(i, sign) => match sign {
1020 true => hir_def::builtin_type::BuiltinType::Int(match i {
1021 hir_def::layout::Integer::I8 => hir_def::builtin_type::BuiltinInt::I8,
1022 hir_def::layout::Integer::I16 => hir_def::builtin_type::BuiltinInt::I16,
1023 hir_def::layout::Integer::I32 => hir_def::builtin_type::BuiltinInt::I32,
1024 hir_def::layout::Integer::I64 => hir_def::builtin_type::BuiltinInt::I64,
1025 hir_def::layout::Integer::I128 => hir_def::builtin_type::BuiltinInt::I128,
1026 }),
1027 false => hir_def::builtin_type::BuiltinType::Uint(match i {
1028 hir_def::layout::Integer::I8 => hir_def::builtin_type::BuiltinUint::U8,
1029 hir_def::layout::Integer::I16 => hir_def::builtin_type::BuiltinUint::U16,
1030 hir_def::layout::Integer::I32 => hir_def::builtin_type::BuiltinUint::U32,
1031 hir_def::layout::Integer::I64 => hir_def::builtin_type::BuiltinUint::U64,
1032 hir_def::layout::Integer::I128 => hir_def::builtin_type::BuiltinUint::U128,
1033 }),
1034 },
1035 }),
1036 )
1037 }
1038
1039 pub fn is_data_carrying(self, db: &dyn HirDatabase) -> bool {
1040 self.variants(db).iter().any(|v| !matches!(v.kind(db), StructKind::Unit))
1041 }
1042 }
1043
1044 impl HasVisibility for Enum {
1045 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1046 db.enum_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1047 }
1048 }
1049
1050 impl From<&Variant> for DefWithBodyId {
1051 fn from(&v: &Variant) -> Self {
1052 DefWithBodyId::VariantId(v.into())
1053 }
1054 }
1055
1056 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1057 pub struct Variant {
1058 pub(crate) parent: Enum,
1059 pub(crate) id: LocalEnumVariantId,
1060 }
1061
1062 impl Variant {
1063 pub fn module(self, db: &dyn HirDatabase) -> Module {
1064 self.parent.module(db)
1065 }
1066
1067 pub fn parent_enum(self, _db: &dyn HirDatabase) -> Enum {
1068 self.parent
1069 }
1070
1071 pub fn name(self, db: &dyn HirDatabase) -> Name {
1072 db.enum_data(self.parent.id).variants[self.id].name.clone()
1073 }
1074
1075 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
1076 self.variant_data(db)
1077 .fields()
1078 .iter()
1079 .map(|(id, _)| Field { parent: self.into(), id })
1080 .collect()
1081 }
1082
1083 pub fn kind(self, db: &dyn HirDatabase) -> StructKind {
1084 self.variant_data(db).kind()
1085 }
1086
1087 pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
1088 db.enum_data(self.parent.id).variants[self.id].variant_data.clone()
1089 }
1090
1091 pub fn value(self, db: &dyn HirDatabase) -> Option<ast::Expr> {
1092 self.source(db)?.value.expr()
1093 }
1094
1095 pub fn eval(self, db: &dyn HirDatabase) -> Result<ComputedExpr, ConstEvalError> {
1096 db.const_eval_variant(self.into())
1097 }
1098 }
1099
1100 /// Variants inherit visibility from the parent enum.
1101 impl HasVisibility for Variant {
1102 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1103 self.parent_enum(db).visibility(db)
1104 }
1105 }
1106
1107 /// A Data Type
1108 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1109 pub enum Adt {
1110 Struct(Struct),
1111 Union(Union),
1112 Enum(Enum),
1113 }
1114 impl_from!(Struct, Union, Enum for Adt);
1115
1116 impl Adt {
1117 pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
1118 let subst = db.generic_defaults(self.into());
1119 subst.iter().any(|ty| match ty.skip_binders().data(Interner) {
1120 GenericArgData::Ty(x) => x.is_unknown(),
1121 _ => false,
1122 })
1123 }
1124
1125 pub fn layout(self, db: &dyn HirDatabase) -> Result<Layout, LayoutError> {
1126 if db.generic_params(self.into()).iter().count() != 0 {
1127 return Err(LayoutError::HasPlaceholder);
1128 }
1129 db.layout_of_adt(self.into(), Substitution::empty(Interner))
1130 }
1131
1132 /// Turns this ADT into a type. Any type parameters of the ADT will be
1133 /// turned into unknown types, which is good for e.g. finding the most
1134 /// general set of completions, but will not look very nice when printed.
1135 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1136 let id = AdtId::from(self);
1137 Type::from_def(db, id)
1138 }
1139
1140 /// Turns this ADT into a type with the given type parameters. This isn't
1141 /// the greatest API, FIXME find a better one.
1142 pub fn ty_with_args(self, db: &dyn HirDatabase, args: &[Type]) -> Type {
1143 let id = AdtId::from(self);
1144 let mut it = args.iter().map(|t| t.ty.clone());
1145 let ty = TyBuilder::def_ty(db, id.into(), None)
1146 .fill(|x| {
1147 let r = it.next().unwrap_or_else(|| TyKind::Error.intern(Interner));
1148 match x {
1149 ParamKind::Type => GenericArgData::Ty(r).intern(Interner),
1150 ParamKind::Const(ty) => unknown_const_as_generic(ty.clone()),
1151 }
1152 })
1153 .build();
1154 Type::new(db, id, ty)
1155 }
1156
1157 pub fn module(self, db: &dyn HirDatabase) -> Module {
1158 match self {
1159 Adt::Struct(s) => s.module(db),
1160 Adt::Union(s) => s.module(db),
1161 Adt::Enum(e) => e.module(db),
1162 }
1163 }
1164
1165 pub fn name(self, db: &dyn HirDatabase) -> Name {
1166 match self {
1167 Adt::Struct(s) => s.name(db),
1168 Adt::Union(u) => u.name(db),
1169 Adt::Enum(e) => e.name(db),
1170 }
1171 }
1172
1173 pub fn as_enum(&self) -> Option<Enum> {
1174 if let Self::Enum(v) = self {
1175 Some(*v)
1176 } else {
1177 None
1178 }
1179 }
1180 }
1181
1182 impl HasVisibility for Adt {
1183 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1184 match self {
1185 Adt::Struct(it) => it.visibility(db),
1186 Adt::Union(it) => it.visibility(db),
1187 Adt::Enum(it) => it.visibility(db),
1188 }
1189 }
1190 }
1191
1192 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1193 pub enum VariantDef {
1194 Struct(Struct),
1195 Union(Union),
1196 Variant(Variant),
1197 }
1198 impl_from!(Struct, Union, Variant for VariantDef);
1199
1200 impl VariantDef {
1201 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
1202 match self {
1203 VariantDef::Struct(it) => it.fields(db),
1204 VariantDef::Union(it) => it.fields(db),
1205 VariantDef::Variant(it) => it.fields(db),
1206 }
1207 }
1208
1209 pub fn module(self, db: &dyn HirDatabase) -> Module {
1210 match self {
1211 VariantDef::Struct(it) => it.module(db),
1212 VariantDef::Union(it) => it.module(db),
1213 VariantDef::Variant(it) => it.module(db),
1214 }
1215 }
1216
1217 pub fn name(&self, db: &dyn HirDatabase) -> Name {
1218 match self {
1219 VariantDef::Struct(s) => s.name(db),
1220 VariantDef::Union(u) => u.name(db),
1221 VariantDef::Variant(e) => e.name(db),
1222 }
1223 }
1224
1225 pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
1226 match self {
1227 VariantDef::Struct(it) => it.variant_data(db),
1228 VariantDef::Union(it) => it.variant_data(db),
1229 VariantDef::Variant(it) => it.variant_data(db),
1230 }
1231 }
1232 }
1233
1234 /// The defs which have a body.
1235 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1236 pub enum DefWithBody {
1237 Function(Function),
1238 Static(Static),
1239 Const(Const),
1240 Variant(Variant),
1241 }
1242 impl_from!(Function, Const, Static, Variant for DefWithBody);
1243
1244 impl DefWithBody {
1245 pub fn module(self, db: &dyn HirDatabase) -> Module {
1246 match self {
1247 DefWithBody::Const(c) => c.module(db),
1248 DefWithBody::Function(f) => f.module(db),
1249 DefWithBody::Static(s) => s.module(db),
1250 DefWithBody::Variant(v) => v.module(db),
1251 }
1252 }
1253
1254 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1255 match self {
1256 DefWithBody::Function(f) => Some(f.name(db)),
1257 DefWithBody::Static(s) => Some(s.name(db)),
1258 DefWithBody::Const(c) => c.name(db),
1259 DefWithBody::Variant(v) => Some(v.name(db)),
1260 }
1261 }
1262
1263 /// Returns the type this def's body has to evaluate to.
1264 pub fn body_type(self, db: &dyn HirDatabase) -> Type {
1265 match self {
1266 DefWithBody::Function(it) => it.ret_type(db),
1267 DefWithBody::Static(it) => it.ty(db),
1268 DefWithBody::Const(it) => it.ty(db),
1269 DefWithBody::Variant(it) => it.parent.variant_body_ty(db),
1270 }
1271 }
1272
1273 fn id(&self) -> DefWithBodyId {
1274 match self {
1275 DefWithBody::Function(it) => it.id.into(),
1276 DefWithBody::Static(it) => it.id.into(),
1277 DefWithBody::Const(it) => it.id.into(),
1278 DefWithBody::Variant(it) => it.into(),
1279 }
1280 }
1281
1282 /// A textual representation of the HIR of this def's body for debugging purposes.
1283 pub fn debug_hir(self, db: &dyn HirDatabase) -> String {
1284 let body = db.body(self.id());
1285 body.pretty_print(db.upcast(), self.id())
1286 }
1287
1288 pub fn diagnostics(self, db: &dyn HirDatabase, acc: &mut Vec<AnyDiagnostic>) {
1289 let krate = self.module(db).id.krate();
1290
1291 let (body, source_map) = db.body_with_source_map(self.into());
1292
1293 for (_, def_map) in body.blocks(db.upcast()) {
1294 for diag in def_map.diagnostics() {
1295 emit_def_diagnostic(db, acc, diag);
1296 }
1297 }
1298
1299 for diag in source_map.diagnostics() {
1300 match diag {
1301 BodyDiagnostic::InactiveCode { node, cfg, opts } => acc.push(
1302 InactiveCode { node: node.clone(), cfg: cfg.clone(), opts: opts.clone() }
1303 .into(),
1304 ),
1305 BodyDiagnostic::MacroError { node, message } => acc.push(
1306 MacroError {
1307 node: node.clone().map(|it| it.into()),
1308 precise_location: None,
1309 message: message.to_string(),
1310 }
1311 .into(),
1312 ),
1313 BodyDiagnostic::UnresolvedProcMacro { node, krate } => acc.push(
1314 UnresolvedProcMacro {
1315 node: node.clone().map(|it| it.into()),
1316 precise_location: None,
1317 macro_name: None,
1318 kind: MacroKind::ProcMacro,
1319 krate: *krate,
1320 }
1321 .into(),
1322 ),
1323 BodyDiagnostic::UnresolvedMacroCall { node, path } => acc.push(
1324 UnresolvedMacroCall {
1325 macro_call: node.clone().map(|ast_ptr| ast_ptr.into()),
1326 precise_location: None,
1327 path: path.clone(),
1328 is_bang: true,
1329 }
1330 .into(),
1331 ),
1332 }
1333 }
1334
1335 let infer = db.infer(self.into());
1336 let source_map = Lazy::new(|| db.body_with_source_map(self.into()).1);
1337 for d in &infer.diagnostics {
1338 match d {
1339 hir_ty::InferenceDiagnostic::NoSuchField { expr } => {
1340 let field = source_map.field_syntax(*expr);
1341 acc.push(NoSuchField { field }.into())
1342 }
1343 &hir_ty::InferenceDiagnostic::BreakOutsideOfLoop { expr, is_break } => {
1344 let expr = source_map
1345 .expr_syntax(expr)
1346 .expect("break outside of loop in synthetic syntax");
1347 acc.push(BreakOutsideOfLoop { expr, is_break }.into())
1348 }
1349 hir_ty::InferenceDiagnostic::MismatchedArgCount { call_expr, expected, found } => {
1350 match source_map.expr_syntax(*call_expr) {
1351 Ok(source_ptr) => acc.push(
1352 MismatchedArgCount {
1353 call_expr: source_ptr,
1354 expected: *expected,
1355 found: *found,
1356 }
1357 .into(),
1358 ),
1359 Err(SyntheticSyntax) => (),
1360 }
1361 }
1362 &hir_ty::InferenceDiagnostic::PrivateField { expr, field } => {
1363 let expr = source_map.expr_syntax(expr).expect("unexpected synthetic");
1364 let field = field.into();
1365 acc.push(PrivateField { expr, field }.into())
1366 }
1367 &hir_ty::InferenceDiagnostic::PrivateAssocItem { id, item } => {
1368 let expr_or_pat = match id {
1369 ExprOrPatId::ExprId(expr) => source_map
1370 .expr_syntax(expr)
1371 .expect("unexpected synthetic")
1372 .map(Either::Left),
1373 ExprOrPatId::PatId(pat) => source_map
1374 .pat_syntax(pat)
1375 .expect("unexpected synthetic")
1376 .map(Either::Right),
1377 };
1378 let item = item.into();
1379 acc.push(PrivateAssocItem { expr_or_pat, item }.into())
1380 }
1381 }
1382 }
1383 for (expr, mismatch) in infer.expr_type_mismatches() {
1384 let expr = match source_map.expr_syntax(expr) {
1385 Ok(expr) => expr,
1386 Err(SyntheticSyntax) => continue,
1387 };
1388 acc.push(
1389 TypeMismatch {
1390 expr,
1391 expected: Type::new(db, DefWithBodyId::from(self), mismatch.expected.clone()),
1392 actual: Type::new(db, DefWithBodyId::from(self), mismatch.actual.clone()),
1393 }
1394 .into(),
1395 );
1396 }
1397
1398 for expr in hir_ty::diagnostics::missing_unsafe(db, self.into()) {
1399 match source_map.expr_syntax(expr) {
1400 Ok(expr) => acc.push(MissingUnsafe { expr }.into()),
1401 Err(SyntheticSyntax) => {
1402 // FIXME: Here and eslwhere in this file, the `expr` was
1403 // desugared, report or assert that this doesn't happen.
1404 }
1405 }
1406 }
1407
1408 for diagnostic in BodyValidationDiagnostic::collect(db, self.into()) {
1409 match diagnostic {
1410 BodyValidationDiagnostic::RecordMissingFields {
1411 record,
1412 variant,
1413 missed_fields,
1414 } => {
1415 let variant_data = variant.variant_data(db.upcast());
1416 let missed_fields = missed_fields
1417 .into_iter()
1418 .map(|idx| variant_data.fields()[idx].name.clone())
1419 .collect();
1420
1421 match record {
1422 Either::Left(record_expr) => match source_map.expr_syntax(record_expr) {
1423 Ok(source_ptr) => {
1424 let root = source_ptr.file_syntax(db.upcast());
1425 if let ast::Expr::RecordExpr(record_expr) =
1426 &source_ptr.value.to_node(&root)
1427 {
1428 if record_expr.record_expr_field_list().is_some() {
1429 acc.push(
1430 MissingFields {
1431 file: source_ptr.file_id,
1432 field_list_parent: Either::Left(AstPtr::new(
1433 record_expr,
1434 )),
1435 field_list_parent_path: record_expr
1436 .path()
1437 .map(|path| AstPtr::new(&path)),
1438 missed_fields,
1439 }
1440 .into(),
1441 )
1442 }
1443 }
1444 }
1445 Err(SyntheticSyntax) => (),
1446 },
1447 Either::Right(record_pat) => match source_map.pat_syntax(record_pat) {
1448 Ok(source_ptr) => {
1449 if let Some(expr) = source_ptr.value.as_ref().left() {
1450 let root = source_ptr.file_syntax(db.upcast());
1451 if let ast::Pat::RecordPat(record_pat) = expr.to_node(&root) {
1452 if record_pat.record_pat_field_list().is_some() {
1453 acc.push(
1454 MissingFields {
1455 file: source_ptr.file_id,
1456 field_list_parent: Either::Right(AstPtr::new(
1457 &record_pat,
1458 )),
1459 field_list_parent_path: record_pat
1460 .path()
1461 .map(|path| AstPtr::new(&path)),
1462 missed_fields,
1463 }
1464 .into(),
1465 )
1466 }
1467 }
1468 }
1469 }
1470 Err(SyntheticSyntax) => (),
1471 },
1472 }
1473 }
1474 BodyValidationDiagnostic::ReplaceFilterMapNextWithFindMap { method_call_expr } => {
1475 if let Ok(next_source_ptr) = source_map.expr_syntax(method_call_expr) {
1476 acc.push(
1477 ReplaceFilterMapNextWithFindMap {
1478 file: next_source_ptr.file_id,
1479 next_expr: next_source_ptr.value,
1480 }
1481 .into(),
1482 );
1483 }
1484 }
1485 BodyValidationDiagnostic::MissingMatchArms { match_expr, uncovered_patterns } => {
1486 match source_map.expr_syntax(match_expr) {
1487 Ok(source_ptr) => {
1488 let root = source_ptr.file_syntax(db.upcast());
1489 if let ast::Expr::MatchExpr(match_expr) =
1490 &source_ptr.value.to_node(&root)
1491 {
1492 if let Some(match_expr) = match_expr.expr() {
1493 acc.push(
1494 MissingMatchArms {
1495 file: source_ptr.file_id,
1496 match_expr: AstPtr::new(&match_expr),
1497 uncovered_patterns,
1498 }
1499 .into(),
1500 );
1501 }
1502 }
1503 }
1504 Err(SyntheticSyntax) => (),
1505 }
1506 }
1507 }
1508 }
1509
1510 let def: ModuleDef = match self {
1511 DefWithBody::Function(it) => it.into(),
1512 DefWithBody::Static(it) => it.into(),
1513 DefWithBody::Const(it) => it.into(),
1514 DefWithBody::Variant(it) => it.into(),
1515 };
1516 for diag in hir_ty::diagnostics::incorrect_case(db, krate, def.into()) {
1517 acc.push(diag.into())
1518 }
1519 }
1520 }
1521
1522 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1523 pub struct Function {
1524 pub(crate) id: FunctionId,
1525 }
1526
1527 impl Function {
1528 pub fn module(self, db: &dyn HirDatabase) -> Module {
1529 self.id.lookup(db.upcast()).module(db.upcast()).into()
1530 }
1531
1532 pub fn name(self, db: &dyn HirDatabase) -> Name {
1533 db.function_data(self.id).name.clone()
1534 }
1535
1536 /// Get this function's return type
1537 pub fn ret_type(self, db: &dyn HirDatabase) -> Type {
1538 let resolver = self.id.resolver(db.upcast());
1539 let substs = TyBuilder::placeholder_subst(db, self.id);
1540 let callable_sig = db.callable_item_signature(self.id.into()).substitute(Interner, &substs);
1541 let ty = callable_sig.ret().clone();
1542 Type::new_with_resolver_inner(db, &resolver, ty)
1543 }
1544
1545 pub fn async_ret_type(self, db: &dyn HirDatabase) -> Option<Type> {
1546 if !self.is_async(db) {
1547 return None;
1548 }
1549 let resolver = self.id.resolver(db.upcast());
1550 let substs = TyBuilder::placeholder_subst(db, self.id);
1551 let callable_sig = db.callable_item_signature(self.id.into()).substitute(Interner, &substs);
1552 let ret_ty = callable_sig.ret().clone();
1553 for pred in ret_ty.impl_trait_bounds(db).into_iter().flatten() {
1554 if let WhereClause::AliasEq(output_eq) = pred.into_value_and_skipped_binders().0 {
1555 return Type::new_with_resolver_inner(db, &resolver, output_eq.ty).into();
1556 }
1557 }
1558 never!("Async fn ret_type should be impl Future");
1559 None
1560 }
1561
1562 pub fn has_self_param(self, db: &dyn HirDatabase) -> bool {
1563 db.function_data(self.id).has_self_param()
1564 }
1565
1566 pub fn self_param(self, db: &dyn HirDatabase) -> Option<SelfParam> {
1567 self.has_self_param(db).then_some(SelfParam { func: self.id })
1568 }
1569
1570 pub fn assoc_fn_params(self, db: &dyn HirDatabase) -> Vec<Param> {
1571 let environment = db.trait_environment(self.id.into());
1572 let substs = TyBuilder::placeholder_subst(db, self.id);
1573 let callable_sig = db.callable_item_signature(self.id.into()).substitute(Interner, &substs);
1574 callable_sig
1575 .params()
1576 .iter()
1577 .enumerate()
1578 .map(|(idx, ty)| {
1579 let ty = Type { env: environment.clone(), ty: ty.clone() };
1580 Param { func: self, ty, idx }
1581 })
1582 .collect()
1583 }
1584
1585 pub fn method_params(self, db: &dyn HirDatabase) -> Option<Vec<Param>> {
1586 if self.self_param(db).is_none() {
1587 return None;
1588 }
1589 Some(self.params_without_self(db))
1590 }
1591
1592 pub fn params_without_self(self, db: &dyn HirDatabase) -> Vec<Param> {
1593 let environment = db.trait_environment(self.id.into());
1594 let substs = TyBuilder::placeholder_subst(db, self.id);
1595 let callable_sig = db.callable_item_signature(self.id.into()).substitute(Interner, &substs);
1596 let skip = if db.function_data(self.id).has_self_param() { 1 } else { 0 };
1597 callable_sig
1598 .params()
1599 .iter()
1600 .enumerate()
1601 .skip(skip)
1602 .map(|(idx, ty)| {
1603 let ty = Type { env: environment.clone(), ty: ty.clone() };
1604 Param { func: self, ty, idx }
1605 })
1606 .collect()
1607 }
1608
1609 pub fn is_const(self, db: &dyn HirDatabase) -> bool {
1610 db.function_data(self.id).has_const_kw()
1611 }
1612
1613 pub fn is_async(self, db: &dyn HirDatabase) -> bool {
1614 db.function_data(self.id).has_async_kw()
1615 }
1616
1617 pub fn is_unsafe_to_call(self, db: &dyn HirDatabase) -> bool {
1618 hir_ty::is_fn_unsafe_to_call(db, self.id)
1619 }
1620
1621 /// Whether this function declaration has a definition.
1622 ///
1623 /// This is false in the case of required (not provided) trait methods.
1624 pub fn has_body(self, db: &dyn HirDatabase) -> bool {
1625 db.function_data(self.id).has_body()
1626 }
1627
1628 pub fn as_proc_macro(self, db: &dyn HirDatabase) -> Option<Macro> {
1629 let function_data = db.function_data(self.id);
1630 let attrs = &function_data.attrs;
1631 // FIXME: Store this in FunctionData flags?
1632 if !(attrs.is_proc_macro()
1633 || attrs.is_proc_macro_attribute()
1634 || attrs.is_proc_macro_derive())
1635 {
1636 return None;
1637 }
1638 let loc = self.id.lookup(db.upcast());
1639 let def_map = db.crate_def_map(loc.krate(db).into());
1640 def_map.fn_as_proc_macro(self.id).map(|id| Macro { id: id.into() })
1641 }
1642 }
1643
1644 // Note: logically, this belongs to `hir_ty`, but we are not using it there yet.
1645 #[derive(Clone, Copy, PartialEq, Eq)]
1646 pub enum Access {
1647 Shared,
1648 Exclusive,
1649 Owned,
1650 }
1651
1652 impl From<hir_ty::Mutability> for Access {
1653 fn from(mutability: hir_ty::Mutability) -> Access {
1654 match mutability {
1655 hir_ty::Mutability::Not => Access::Shared,
1656 hir_ty::Mutability::Mut => Access::Exclusive,
1657 }
1658 }
1659 }
1660
1661 #[derive(Clone, Debug)]
1662 pub struct Param {
1663 func: Function,
1664 /// The index in parameter list, including self parameter.
1665 idx: usize,
1666 ty: Type,
1667 }
1668
1669 impl Param {
1670 pub fn ty(&self) -> &Type {
1671 &self.ty
1672 }
1673
1674 pub fn name(&self, db: &dyn HirDatabase) -> Option<Name> {
1675 db.function_data(self.func.id).params[self.idx].0.clone()
1676 }
1677
1678 pub fn as_local(&self, db: &dyn HirDatabase) -> Option<Local> {
1679 let parent = DefWithBodyId::FunctionId(self.func.into());
1680 let body = db.body(parent);
1681 let pat_id = body.params[self.idx];
1682 if let Pat::Bind { .. } = &body[pat_id] {
1683 Some(Local { parent, pat_id: body.params[self.idx] })
1684 } else {
1685 None
1686 }
1687 }
1688
1689 pub fn pattern_source(&self, db: &dyn HirDatabase) -> Option<ast::Pat> {
1690 self.source(db).and_then(|p| p.value.pat())
1691 }
1692
1693 pub fn source(&self, db: &dyn HirDatabase) -> Option<InFile<ast::Param>> {
1694 let InFile { file_id, value } = self.func.source(db)?;
1695 let params = value.param_list()?;
1696 if params.self_param().is_some() {
1697 params.params().nth(self.idx.checked_sub(1)?)
1698 } else {
1699 params.params().nth(self.idx)
1700 }
1701 .map(|value| InFile { file_id, value })
1702 }
1703 }
1704
1705 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1706 pub struct SelfParam {
1707 func: FunctionId,
1708 }
1709
1710 impl SelfParam {
1711 pub fn access(self, db: &dyn HirDatabase) -> Access {
1712 let func_data = db.function_data(self.func);
1713 func_data
1714 .params
1715 .first()
1716 .map(|(_, param)| match &**param {
1717 TypeRef::Reference(.., mutability) => match mutability {
1718 hir_def::type_ref::Mutability::Shared => Access::Shared,
1719 hir_def::type_ref::Mutability::Mut => Access::Exclusive,
1720 },
1721 _ => Access::Owned,
1722 })
1723 .unwrap_or(Access::Owned)
1724 }
1725
1726 pub fn display(self, db: &dyn HirDatabase) -> &'static str {
1727 match self.access(db) {
1728 Access::Shared => "&self",
1729 Access::Exclusive => "&mut self",
1730 Access::Owned => "self",
1731 }
1732 }
1733
1734 pub fn source(&self, db: &dyn HirDatabase) -> Option<InFile<ast::SelfParam>> {
1735 let InFile { file_id, value } = Function::from(self.func).source(db)?;
1736 value
1737 .param_list()
1738 .and_then(|params| params.self_param())
1739 .map(|value| InFile { file_id, value })
1740 }
1741
1742 pub fn ty(&self, db: &dyn HirDatabase) -> Type {
1743 let substs = TyBuilder::placeholder_subst(db, self.func);
1744 let callable_sig =
1745 db.callable_item_signature(self.func.into()).substitute(Interner, &substs);
1746 let environment = db.trait_environment(self.func.into());
1747 let ty = callable_sig.params()[0].clone();
1748 Type { env: environment, ty }
1749 }
1750 }
1751
1752 impl HasVisibility for Function {
1753 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1754 db.function_visibility(self.id)
1755 }
1756 }
1757
1758 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1759 pub struct Const {
1760 pub(crate) id: ConstId,
1761 }
1762
1763 impl Const {
1764 pub fn module(self, db: &dyn HirDatabase) -> Module {
1765 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
1766 }
1767
1768 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1769 db.const_data(self.id).name.clone()
1770 }
1771
1772 pub fn value(self, db: &dyn HirDatabase) -> Option<ast::Expr> {
1773 self.source(db)?.value.body()
1774 }
1775
1776 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1777 let data = db.const_data(self.id);
1778 let resolver = self.id.resolver(db.upcast());
1779 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
1780 let ty = ctx.lower_ty(&data.type_ref);
1781 Type::new_with_resolver_inner(db, &resolver, ty)
1782 }
1783
1784 pub fn eval(self, db: &dyn HirDatabase) -> Result<ComputedExpr, ConstEvalError> {
1785 db.const_eval(self.id)
1786 }
1787 }
1788
1789 impl HasVisibility for Const {
1790 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1791 db.const_visibility(self.id)
1792 }
1793 }
1794
1795 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1796 pub struct Static {
1797 pub(crate) id: StaticId,
1798 }
1799
1800 impl Static {
1801 pub fn module(self, db: &dyn HirDatabase) -> Module {
1802 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
1803 }
1804
1805 pub fn name(self, db: &dyn HirDatabase) -> Name {
1806 db.static_data(self.id).name.clone()
1807 }
1808
1809 pub fn is_mut(self, db: &dyn HirDatabase) -> bool {
1810 db.static_data(self.id).mutable
1811 }
1812
1813 pub fn value(self, db: &dyn HirDatabase) -> Option<ast::Expr> {
1814 self.source(db)?.value.body()
1815 }
1816
1817 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1818 let data = db.static_data(self.id);
1819 let resolver = self.id.resolver(db.upcast());
1820 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
1821 let ty = ctx.lower_ty(&data.type_ref);
1822 Type::new_with_resolver_inner(db, &resolver, ty)
1823 }
1824 }
1825
1826 impl HasVisibility for Static {
1827 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1828 db.static_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1829 }
1830 }
1831
1832 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1833 pub struct Trait {
1834 pub(crate) id: TraitId,
1835 }
1836
1837 impl Trait {
1838 pub fn lang(db: &dyn HirDatabase, krate: Crate, name: &Name) -> Option<Trait> {
1839 db.lang_item(krate.into(), LangItem::from_name(name)?)
1840 .and_then(LangItemTarget::as_trait)
1841 .map(Into::into)
1842 }
1843
1844 pub fn module(self, db: &dyn HirDatabase) -> Module {
1845 Module { id: self.id.lookup(db.upcast()).container }
1846 }
1847
1848 pub fn name(self, db: &dyn HirDatabase) -> Name {
1849 db.trait_data(self.id).name.clone()
1850 }
1851
1852 pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
1853 db.trait_data(self.id).items.iter().map(|(_name, it)| (*it).into()).collect()
1854 }
1855
1856 pub fn items_with_supertraits(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
1857 let traits = all_super_traits(db.upcast(), self.into());
1858 traits.iter().flat_map(|tr| Trait::from(*tr).items(db)).collect()
1859 }
1860
1861 pub fn is_auto(self, db: &dyn HirDatabase) -> bool {
1862 db.trait_data(self.id).is_auto
1863 }
1864
1865 pub fn is_unsafe(&self, db: &dyn HirDatabase) -> bool {
1866 db.trait_data(self.id).is_unsafe
1867 }
1868
1869 pub fn type_or_const_param_count(
1870 &self,
1871 db: &dyn HirDatabase,
1872 count_required_only: bool,
1873 ) -> usize {
1874 db.generic_params(GenericDefId::from(self.id))
1875 .type_or_consts
1876 .iter()
1877 .filter(|(_, ty)| match ty {
1878 TypeOrConstParamData::TypeParamData(ty)
1879 if ty.provenance != TypeParamProvenance::TypeParamList =>
1880 {
1881 false
1882 }
1883 _ => true,
1884 })
1885 .filter(|(_, ty)| !count_required_only || !ty.has_default())
1886 .count()
1887 }
1888 }
1889
1890 impl HasVisibility for Trait {
1891 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1892 db.trait_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1893 }
1894 }
1895
1896 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1897 pub struct TypeAlias {
1898 pub(crate) id: TypeAliasId,
1899 }
1900
1901 impl TypeAlias {
1902 pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
1903 let subst = db.generic_defaults(self.id.into());
1904 subst.iter().any(|ty| match ty.skip_binders().data(Interner) {
1905 GenericArgData::Ty(x) => x.is_unknown(),
1906 _ => false,
1907 })
1908 }
1909
1910 pub fn module(self, db: &dyn HirDatabase) -> Module {
1911 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
1912 }
1913
1914 pub fn type_ref(self, db: &dyn HirDatabase) -> Option<TypeRef> {
1915 db.type_alias_data(self.id).type_ref.as_deref().cloned()
1916 }
1917
1918 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1919 Type::from_def(db, self.id)
1920 }
1921
1922 pub fn name(self, db: &dyn HirDatabase) -> Name {
1923 db.type_alias_data(self.id).name.clone()
1924 }
1925 }
1926
1927 impl HasVisibility for TypeAlias {
1928 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1929 let function_data = db.type_alias_data(self.id);
1930 let visibility = &function_data.visibility;
1931 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1932 }
1933 }
1934
1935 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1936 pub struct BuiltinType {
1937 pub(crate) inner: hir_def::builtin_type::BuiltinType,
1938 }
1939
1940 impl BuiltinType {
1941 pub fn str() -> BuiltinType {
1942 BuiltinType { inner: hir_def::builtin_type::BuiltinType::Str }
1943 }
1944
1945 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1946 Type::new_for_crate(db.crate_graph().iter().next().unwrap(), TyBuilder::builtin(self.inner))
1947 }
1948
1949 pub fn name(self) -> Name {
1950 self.inner.as_name()
1951 }
1952
1953 pub fn is_int(&self) -> bool {
1954 matches!(self.inner, hir_def::builtin_type::BuiltinType::Int(_))
1955 }
1956
1957 pub fn is_uint(&self) -> bool {
1958 matches!(self.inner, hir_def::builtin_type::BuiltinType::Uint(_))
1959 }
1960
1961 pub fn is_float(&self) -> bool {
1962 matches!(self.inner, hir_def::builtin_type::BuiltinType::Float(_))
1963 }
1964
1965 pub fn is_char(&self) -> bool {
1966 matches!(self.inner, hir_def::builtin_type::BuiltinType::Char)
1967 }
1968
1969 pub fn is_bool(&self) -> bool {
1970 matches!(self.inner, hir_def::builtin_type::BuiltinType::Bool)
1971 }
1972
1973 pub fn is_str(&self) -> bool {
1974 matches!(self.inner, hir_def::builtin_type::BuiltinType::Str)
1975 }
1976 }
1977
1978 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1979 pub enum MacroKind {
1980 /// `macro_rules!` or Macros 2.0 macro.
1981 Declarative,
1982 /// A built-in or custom derive.
1983 Derive,
1984 /// A built-in function-like macro.
1985 BuiltIn,
1986 /// A procedural attribute macro.
1987 Attr,
1988 /// A function-like procedural macro.
1989 ProcMacro,
1990 }
1991
1992 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1993 pub struct Macro {
1994 pub(crate) id: MacroId,
1995 }
1996
1997 impl Macro {
1998 pub fn module(self, db: &dyn HirDatabase) -> Module {
1999 Module { id: self.id.module(db.upcast()) }
2000 }
2001
2002 pub fn name(self, db: &dyn HirDatabase) -> Name {
2003 match self.id {
2004 MacroId::Macro2Id(id) => db.macro2_data(id).name.clone(),
2005 MacroId::MacroRulesId(id) => db.macro_rules_data(id).name.clone(),
2006 MacroId::ProcMacroId(id) => db.proc_macro_data(id).name.clone(),
2007 }
2008 }
2009
2010 pub fn is_macro_export(self, db: &dyn HirDatabase) -> bool {
2011 matches!(self.id, MacroId::MacroRulesId(id) if db.macro_rules_data(id).macro_export)
2012 }
2013
2014 pub fn kind(&self, db: &dyn HirDatabase) -> MacroKind {
2015 match self.id {
2016 MacroId::Macro2Id(it) => match it.lookup(db.upcast()).expander {
2017 MacroExpander::Declarative => MacroKind::Declarative,
2018 MacroExpander::BuiltIn(_) | MacroExpander::BuiltInEager(_) => MacroKind::BuiltIn,
2019 MacroExpander::BuiltInAttr(_) => MacroKind::Attr,
2020 MacroExpander::BuiltInDerive(_) => MacroKind::Derive,
2021 },
2022 MacroId::MacroRulesId(it) => match it.lookup(db.upcast()).expander {
2023 MacroExpander::Declarative => MacroKind::Declarative,
2024 MacroExpander::BuiltIn(_) | MacroExpander::BuiltInEager(_) => MacroKind::BuiltIn,
2025 MacroExpander::BuiltInAttr(_) => MacroKind::Attr,
2026 MacroExpander::BuiltInDerive(_) => MacroKind::Derive,
2027 },
2028 MacroId::ProcMacroId(it) => match it.lookup(db.upcast()).kind {
2029 ProcMacroKind::CustomDerive => MacroKind::Derive,
2030 ProcMacroKind::FuncLike => MacroKind::ProcMacro,
2031 ProcMacroKind::Attr => MacroKind::Attr,
2032 },
2033 }
2034 }
2035
2036 pub fn is_fn_like(&self, db: &dyn HirDatabase) -> bool {
2037 match self.kind(db) {
2038 MacroKind::Declarative | MacroKind::BuiltIn | MacroKind::ProcMacro => true,
2039 MacroKind::Attr | MacroKind::Derive => false,
2040 }
2041 }
2042
2043 pub fn is_builtin_derive(&self, db: &dyn HirDatabase) -> bool {
2044 match self.id {
2045 MacroId::Macro2Id(it) => {
2046 matches!(it.lookup(db.upcast()).expander, MacroExpander::BuiltInDerive(_))
2047 }
2048 MacroId::MacroRulesId(it) => {
2049 matches!(it.lookup(db.upcast()).expander, MacroExpander::BuiltInDerive(_))
2050 }
2051 MacroId::ProcMacroId(_) => false,
2052 }
2053 }
2054
2055 pub fn is_attr(&self, db: &dyn HirDatabase) -> bool {
2056 matches!(self.kind(db), MacroKind::Attr)
2057 }
2058
2059 pub fn is_derive(&self, db: &dyn HirDatabase) -> bool {
2060 matches!(self.kind(db), MacroKind::Derive)
2061 }
2062 }
2063
2064 impl HasVisibility for Macro {
2065 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
2066 match self.id {
2067 MacroId::Macro2Id(id) => {
2068 let data = db.macro2_data(id);
2069 let visibility = &data.visibility;
2070 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
2071 }
2072 MacroId::MacroRulesId(_) => Visibility::Public,
2073 MacroId::ProcMacroId(_) => Visibility::Public,
2074 }
2075 }
2076 }
2077
2078 #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
2079 pub enum ItemInNs {
2080 Types(ModuleDef),
2081 Values(ModuleDef),
2082 Macros(Macro),
2083 }
2084
2085 impl From<Macro> for ItemInNs {
2086 fn from(it: Macro) -> Self {
2087 Self::Macros(it)
2088 }
2089 }
2090
2091 impl From<ModuleDef> for ItemInNs {
2092 fn from(module_def: ModuleDef) -> Self {
2093 match module_def {
2094 ModuleDef::Static(_) | ModuleDef::Const(_) | ModuleDef::Function(_) => {
2095 ItemInNs::Values(module_def)
2096 }
2097 _ => ItemInNs::Types(module_def),
2098 }
2099 }
2100 }
2101
2102 impl ItemInNs {
2103 pub fn as_module_def(self) -> Option<ModuleDef> {
2104 match self {
2105 ItemInNs::Types(id) | ItemInNs::Values(id) => Some(id),
2106 ItemInNs::Macros(_) => None,
2107 }
2108 }
2109
2110 /// Returns the crate defining this item (or `None` if `self` is built-in).
2111 pub fn krate(&self, db: &dyn HirDatabase) -> Option<Crate> {
2112 match self {
2113 ItemInNs::Types(did) | ItemInNs::Values(did) => did.module(db).map(|m| m.krate()),
2114 ItemInNs::Macros(id) => Some(id.module(db).krate()),
2115 }
2116 }
2117
2118 pub fn attrs(&self, db: &dyn HirDatabase) -> Option<AttrsWithOwner> {
2119 match self {
2120 ItemInNs::Types(it) | ItemInNs::Values(it) => it.attrs(db),
2121 ItemInNs::Macros(it) => Some(it.attrs(db)),
2122 }
2123 }
2124 }
2125
2126 /// Invariant: `inner.as_assoc_item(db).is_some()`
2127 /// We do not actively enforce this invariant.
2128 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2129 pub enum AssocItem {
2130 Function(Function),
2131 Const(Const),
2132 TypeAlias(TypeAlias),
2133 }
2134 #[derive(Debug, Clone)]
2135 pub enum AssocItemContainer {
2136 Trait(Trait),
2137 Impl(Impl),
2138 }
2139 pub trait AsAssocItem {
2140 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem>;
2141 }
2142
2143 impl AsAssocItem for Function {
2144 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
2145 as_assoc_item(db, AssocItem::Function, self.id)
2146 }
2147 }
2148 impl AsAssocItem for Const {
2149 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
2150 as_assoc_item(db, AssocItem::Const, self.id)
2151 }
2152 }
2153 impl AsAssocItem for TypeAlias {
2154 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
2155 as_assoc_item(db, AssocItem::TypeAlias, self.id)
2156 }
2157 }
2158 impl AsAssocItem for ModuleDef {
2159 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
2160 match self {
2161 ModuleDef::Function(it) => it.as_assoc_item(db),
2162 ModuleDef::Const(it) => it.as_assoc_item(db),
2163 ModuleDef::TypeAlias(it) => it.as_assoc_item(db),
2164 _ => None,
2165 }
2166 }
2167 }
2168 impl AsAssocItem for DefWithBody {
2169 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
2170 match self {
2171 DefWithBody::Function(it) => it.as_assoc_item(db),
2172 DefWithBody::Const(it) => it.as_assoc_item(db),
2173 DefWithBody::Static(_) | DefWithBody::Variant(_) => None,
2174 }
2175 }
2176 }
2177
2178 fn as_assoc_item<ID, DEF, CTOR, AST>(db: &dyn HirDatabase, ctor: CTOR, id: ID) -> Option<AssocItem>
2179 where
2180 ID: Lookup<Data = AssocItemLoc<AST>>,
2181 DEF: From<ID>,
2182 CTOR: FnOnce(DEF) -> AssocItem,
2183 AST: ItemTreeNode,
2184 {
2185 match id.lookup(db.upcast()).container {
2186 ItemContainerId::TraitId(_) | ItemContainerId::ImplId(_) => Some(ctor(DEF::from(id))),
2187 ItemContainerId::ModuleId(_) | ItemContainerId::ExternBlockId(_) => None,
2188 }
2189 }
2190
2191 impl AssocItem {
2192 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
2193 match self {
2194 AssocItem::Function(it) => Some(it.name(db)),
2195 AssocItem::Const(it) => it.name(db),
2196 AssocItem::TypeAlias(it) => Some(it.name(db)),
2197 }
2198 }
2199 pub fn module(self, db: &dyn HirDatabase) -> Module {
2200 match self {
2201 AssocItem::Function(f) => f.module(db),
2202 AssocItem::Const(c) => c.module(db),
2203 AssocItem::TypeAlias(t) => t.module(db),
2204 }
2205 }
2206 pub fn container(self, db: &dyn HirDatabase) -> AssocItemContainer {
2207 let container = match self {
2208 AssocItem::Function(it) => it.id.lookup(db.upcast()).container,
2209 AssocItem::Const(it) => it.id.lookup(db.upcast()).container,
2210 AssocItem::TypeAlias(it) => it.id.lookup(db.upcast()).container,
2211 };
2212 match container {
2213 ItemContainerId::TraitId(id) => AssocItemContainer::Trait(id.into()),
2214 ItemContainerId::ImplId(id) => AssocItemContainer::Impl(id.into()),
2215 ItemContainerId::ModuleId(_) | ItemContainerId::ExternBlockId(_) => {
2216 panic!("invalid AssocItem")
2217 }
2218 }
2219 }
2220
2221 pub fn containing_trait(self, db: &dyn HirDatabase) -> Option<Trait> {
2222 match self.container(db) {
2223 AssocItemContainer::Trait(t) => Some(t),
2224 _ => None,
2225 }
2226 }
2227
2228 pub fn containing_trait_impl(self, db: &dyn HirDatabase) -> Option<Trait> {
2229 match self.container(db) {
2230 AssocItemContainer::Impl(i) => i.trait_(db),
2231 _ => None,
2232 }
2233 }
2234
2235 pub fn containing_trait_or_trait_impl(self, db: &dyn HirDatabase) -> Option<Trait> {
2236 match self.container(db) {
2237 AssocItemContainer::Trait(t) => Some(t),
2238 AssocItemContainer::Impl(i) => i.trait_(db),
2239 }
2240 }
2241 }
2242
2243 impl HasVisibility for AssocItem {
2244 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
2245 match self {
2246 AssocItem::Function(f) => f.visibility(db),
2247 AssocItem::Const(c) => c.visibility(db),
2248 AssocItem::TypeAlias(t) => t.visibility(db),
2249 }
2250 }
2251 }
2252
2253 impl From<AssocItem> for ModuleDef {
2254 fn from(assoc: AssocItem) -> Self {
2255 match assoc {
2256 AssocItem::Function(it) => ModuleDef::Function(it),
2257 AssocItem::Const(it) => ModuleDef::Const(it),
2258 AssocItem::TypeAlias(it) => ModuleDef::TypeAlias(it),
2259 }
2260 }
2261 }
2262
2263 #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
2264 pub enum GenericDef {
2265 Function(Function),
2266 Adt(Adt),
2267 Trait(Trait),
2268 TypeAlias(TypeAlias),
2269 Impl(Impl),
2270 // enum variants cannot have generics themselves, but their parent enums
2271 // can, and this makes some code easier to write
2272 Variant(Variant),
2273 // consts can have type parameters from their parents (i.e. associated consts of traits)
2274 Const(Const),
2275 }
2276 impl_from!(
2277 Function,
2278 Adt(Struct, Enum, Union),
2279 Trait,
2280 TypeAlias,
2281 Impl,
2282 Variant,
2283 Const
2284 for GenericDef
2285 );
2286
2287 impl GenericDef {
2288 pub fn params(self, db: &dyn HirDatabase) -> Vec<GenericParam> {
2289 let generics = db.generic_params(self.into());
2290 let ty_params = generics.type_or_consts.iter().map(|(local_id, _)| {
2291 let toc = TypeOrConstParam { id: TypeOrConstParamId { parent: self.into(), local_id } };
2292 match toc.split(db) {
2293 Either::Left(x) => GenericParam::ConstParam(x),
2294 Either::Right(x) => GenericParam::TypeParam(x),
2295 }
2296 });
2297 let lt_params = generics
2298 .lifetimes
2299 .iter()
2300 .map(|(local_id, _)| LifetimeParam {
2301 id: LifetimeParamId { parent: self.into(), local_id },
2302 })
2303 .map(GenericParam::LifetimeParam);
2304 lt_params.chain(ty_params).collect()
2305 }
2306
2307 pub fn type_params(self, db: &dyn HirDatabase) -> Vec<TypeOrConstParam> {
2308 let generics = db.generic_params(self.into());
2309 generics
2310 .type_or_consts
2311 .iter()
2312 .map(|(local_id, _)| TypeOrConstParam {
2313 id: TypeOrConstParamId { parent: self.into(), local_id },
2314 })
2315 .collect()
2316 }
2317 }
2318
2319 /// A single local definition.
2320 ///
2321 /// If the definition of this is part of a "MultiLocal", that is a local that has multiple declarations due to or-patterns
2322 /// then this only references a single one of those.
2323 /// To retrieve the other locals you should use [`Local::associated_locals`]
2324 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2325 pub struct Local {
2326 pub(crate) parent: DefWithBodyId,
2327 pub(crate) pat_id: PatId,
2328 }
2329
2330 impl Local {
2331 pub fn is_param(self, db: &dyn HirDatabase) -> bool {
2332 let src = self.source(db);
2333 match src.value {
2334 Either::Left(pat) => pat
2335 .syntax()
2336 .ancestors()
2337 .map(|it| it.kind())
2338 .take_while(|&kind| ast::Pat::can_cast(kind) || ast::Param::can_cast(kind))
2339 .any(ast::Param::can_cast),
2340 Either::Right(_) => true,
2341 }
2342 }
2343
2344 pub fn as_self_param(self, db: &dyn HirDatabase) -> Option<SelfParam> {
2345 match self.parent {
2346 DefWithBodyId::FunctionId(func) if self.is_self(db) => Some(SelfParam { func }),
2347 _ => None,
2348 }
2349 }
2350
2351 pub fn name(self, db: &dyn HirDatabase) -> Name {
2352 let body = db.body(self.parent);
2353 match &body[self.pat_id] {
2354 Pat::Bind { name, .. } => name.clone(),
2355 _ => {
2356 stdx::never!("hir::Local is missing a name!");
2357 Name::missing()
2358 }
2359 }
2360 }
2361
2362 pub fn is_self(self, db: &dyn HirDatabase) -> bool {
2363 self.name(db) == name![self]
2364 }
2365
2366 pub fn is_mut(self, db: &dyn HirDatabase) -> bool {
2367 let body = db.body(self.parent);
2368 matches!(&body[self.pat_id], Pat::Bind { mode: BindingAnnotation::Mutable, .. })
2369 }
2370
2371 pub fn is_ref(self, db: &dyn HirDatabase) -> bool {
2372 let body = db.body(self.parent);
2373 matches!(
2374 &body[self.pat_id],
2375 Pat::Bind { mode: BindingAnnotation::Ref | BindingAnnotation::RefMut, .. }
2376 )
2377 }
2378
2379 pub fn parent(self, _db: &dyn HirDatabase) -> DefWithBody {
2380 self.parent.into()
2381 }
2382
2383 pub fn module(self, db: &dyn HirDatabase) -> Module {
2384 self.parent(db).module(db)
2385 }
2386
2387 pub fn ty(self, db: &dyn HirDatabase) -> Type {
2388 let def = self.parent;
2389 let infer = db.infer(def);
2390 let ty = infer[self.pat_id].clone();
2391 Type::new(db, def, ty)
2392 }
2393
2394 pub fn associated_locals(self, db: &dyn HirDatabase) -> Box<[Local]> {
2395 let body = db.body(self.parent);
2396 body.ident_patterns_for(&self.pat_id)
2397 .iter()
2398 .map(|&pat_id| Local { parent: self.parent, pat_id })
2399 .collect()
2400 }
2401
2402 /// If this local is part of a multi-local, retrieve the representative local.
2403 /// That is the local that references are being resolved to.
2404 pub fn representative(self, db: &dyn HirDatabase) -> Local {
2405 let body = db.body(self.parent);
2406 Local { pat_id: body.pattern_representative(self.pat_id), ..self }
2407 }
2408
2409 pub fn source(self, db: &dyn HirDatabase) -> InFile<Either<ast::IdentPat, ast::SelfParam>> {
2410 let (_body, source_map) = db.body_with_source_map(self.parent);
2411 let src = source_map.pat_syntax(self.pat_id).unwrap(); // Hmm...
2412 let root = src.file_syntax(db.upcast());
2413 src.map(|ast| match ast {
2414 // Suspicious unwrap
2415 Either::Left(it) => Either::Left(it.cast().unwrap().to_node(&root)),
2416 Either::Right(it) => Either::Right(it.to_node(&root)),
2417 })
2418 }
2419 }
2420
2421 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2422 pub struct DeriveHelper {
2423 pub(crate) derive: MacroId,
2424 pub(crate) idx: u32,
2425 }
2426
2427 impl DeriveHelper {
2428 pub fn derive(&self) -> Macro {
2429 Macro { id: self.derive }
2430 }
2431
2432 pub fn name(&self, db: &dyn HirDatabase) -> Name {
2433 match self.derive {
2434 MacroId::Macro2Id(it) => db
2435 .macro2_data(it)
2436 .helpers
2437 .as_deref()
2438 .and_then(|it| it.get(self.idx as usize))
2439 .cloned(),
2440 MacroId::MacroRulesId(_) => None,
2441 MacroId::ProcMacroId(proc_macro) => db
2442 .proc_macro_data(proc_macro)
2443 .helpers
2444 .as_deref()
2445 .and_then(|it| it.get(self.idx as usize))
2446 .cloned(),
2447 }
2448 .unwrap_or_else(|| Name::missing())
2449 }
2450 }
2451
2452 // FIXME: Wrong name? This is could also be a registered attribute
2453 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2454 pub struct BuiltinAttr {
2455 krate: Option<CrateId>,
2456 idx: u32,
2457 }
2458
2459 impl BuiltinAttr {
2460 // FIXME: consider crates\hir_def\src\nameres\attr_resolution.rs?
2461 pub(crate) fn by_name(db: &dyn HirDatabase, krate: Crate, name: &str) -> Option<Self> {
2462 if let builtin @ Some(_) = Self::builtin(name) {
2463 return builtin;
2464 }
2465 let idx =
2466 db.crate_def_map(krate.id).registered_attrs().iter().position(|it| it == name)? as u32;
2467 Some(BuiltinAttr { krate: Some(krate.id), idx })
2468 }
2469
2470 fn builtin(name: &str) -> Option<Self> {
2471 hir_def::builtin_attr::INERT_ATTRIBUTES
2472 .iter()
2473 .position(|tool| tool.name == name)
2474 .map(|idx| BuiltinAttr { krate: None, idx: idx as u32 })
2475 }
2476
2477 pub fn name(&self, db: &dyn HirDatabase) -> SmolStr {
2478 // FIXME: Return a `Name` here
2479 match self.krate {
2480 Some(krate) => db.crate_def_map(krate).registered_attrs()[self.idx as usize].clone(),
2481 None => SmolStr::new(hir_def::builtin_attr::INERT_ATTRIBUTES[self.idx as usize].name),
2482 }
2483 }
2484
2485 pub fn template(&self, _: &dyn HirDatabase) -> Option<AttributeTemplate> {
2486 match self.krate {
2487 Some(_) => None,
2488 None => Some(hir_def::builtin_attr::INERT_ATTRIBUTES[self.idx as usize].template),
2489 }
2490 }
2491 }
2492
2493 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2494 pub struct ToolModule {
2495 krate: Option<CrateId>,
2496 idx: u32,
2497 }
2498
2499 impl ToolModule {
2500 // FIXME: consider crates\hir_def\src\nameres\attr_resolution.rs?
2501 pub(crate) fn by_name(db: &dyn HirDatabase, krate: Crate, name: &str) -> Option<Self> {
2502 if let builtin @ Some(_) = Self::builtin(name) {
2503 return builtin;
2504 }
2505 let idx =
2506 db.crate_def_map(krate.id).registered_tools().iter().position(|it| it == name)? as u32;
2507 Some(ToolModule { krate: Some(krate.id), idx })
2508 }
2509
2510 fn builtin(name: &str) -> Option<Self> {
2511 hir_def::builtin_attr::TOOL_MODULES
2512 .iter()
2513 .position(|&tool| tool == name)
2514 .map(|idx| ToolModule { krate: None, idx: idx as u32 })
2515 }
2516
2517 pub fn name(&self, db: &dyn HirDatabase) -> SmolStr {
2518 // FIXME: Return a `Name` here
2519 match self.krate {
2520 Some(krate) => db.crate_def_map(krate).registered_tools()[self.idx as usize].clone(),
2521 None => SmolStr::new(hir_def::builtin_attr::TOOL_MODULES[self.idx as usize]),
2522 }
2523 }
2524 }
2525
2526 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2527 pub struct Label {
2528 pub(crate) parent: DefWithBodyId,
2529 pub(crate) label_id: LabelId,
2530 }
2531
2532 impl Label {
2533 pub fn module(self, db: &dyn HirDatabase) -> Module {
2534 self.parent(db).module(db)
2535 }
2536
2537 pub fn parent(self, _db: &dyn HirDatabase) -> DefWithBody {
2538 self.parent.into()
2539 }
2540
2541 pub fn name(self, db: &dyn HirDatabase) -> Name {
2542 let body = db.body(self.parent);
2543 body[self.label_id].name.clone()
2544 }
2545
2546 pub fn source(self, db: &dyn HirDatabase) -> InFile<ast::Label> {
2547 let (_body, source_map) = db.body_with_source_map(self.parent);
2548 let src = source_map.label_syntax(self.label_id);
2549 let root = src.file_syntax(db.upcast());
2550 src.map(|ast| ast.to_node(&root))
2551 }
2552 }
2553
2554 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2555 pub enum GenericParam {
2556 TypeParam(TypeParam),
2557 ConstParam(ConstParam),
2558 LifetimeParam(LifetimeParam),
2559 }
2560 impl_from!(TypeParam, ConstParam, LifetimeParam for GenericParam);
2561
2562 impl GenericParam {
2563 pub fn module(self, db: &dyn HirDatabase) -> Module {
2564 match self {
2565 GenericParam::TypeParam(it) => it.module(db),
2566 GenericParam::ConstParam(it) => it.module(db),
2567 GenericParam::LifetimeParam(it) => it.module(db),
2568 }
2569 }
2570
2571 pub fn name(self, db: &dyn HirDatabase) -> Name {
2572 match self {
2573 GenericParam::TypeParam(it) => it.name(db),
2574 GenericParam::ConstParam(it) => it.name(db),
2575 GenericParam::LifetimeParam(it) => it.name(db),
2576 }
2577 }
2578
2579 pub fn parent(self) -> GenericDef {
2580 match self {
2581 GenericParam::TypeParam(it) => it.id.parent().into(),
2582 GenericParam::ConstParam(it) => it.id.parent().into(),
2583 GenericParam::LifetimeParam(it) => it.id.parent.into(),
2584 }
2585 }
2586 }
2587
2588 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2589 pub struct TypeParam {
2590 pub(crate) id: TypeParamId,
2591 }
2592
2593 impl TypeParam {
2594 pub fn merge(self) -> TypeOrConstParam {
2595 TypeOrConstParam { id: self.id.into() }
2596 }
2597
2598 pub fn name(self, db: &dyn HirDatabase) -> Name {
2599 self.merge().name(db)
2600 }
2601
2602 pub fn module(self, db: &dyn HirDatabase) -> Module {
2603 self.id.parent().module(db.upcast()).into()
2604 }
2605
2606 /// Is this type parameter implicitly introduced (eg. `Self` in a trait or an `impl Trait`
2607 /// argument)?
2608 pub fn is_implicit(self, db: &dyn HirDatabase) -> bool {
2609 let params = db.generic_params(self.id.parent());
2610 let data = &params.type_or_consts[self.id.local_id()];
2611 match data.type_param().unwrap().provenance {
2612 hir_def::generics::TypeParamProvenance::TypeParamList => false,
2613 hir_def::generics::TypeParamProvenance::TraitSelf
2614 | hir_def::generics::TypeParamProvenance::ArgumentImplTrait => true,
2615 }
2616 }
2617
2618 pub fn ty(self, db: &dyn HirDatabase) -> Type {
2619 let resolver = self.id.parent().resolver(db.upcast());
2620 let ty =
2621 TyKind::Placeholder(hir_ty::to_placeholder_idx(db, self.id.into())).intern(Interner);
2622 Type::new_with_resolver_inner(db, &resolver, ty)
2623 }
2624
2625 /// FIXME: this only lists trait bounds from the item defining the type
2626 /// parameter, not additional bounds that might be added e.g. by a method if
2627 /// the parameter comes from an impl!
2628 pub fn trait_bounds(self, db: &dyn HirDatabase) -> Vec<Trait> {
2629 db.generic_predicates_for_param(self.id.parent(), self.id.into(), None)
2630 .iter()
2631 .filter_map(|pred| match &pred.skip_binders().skip_binders() {
2632 hir_ty::WhereClause::Implemented(trait_ref) => {
2633 Some(Trait::from(trait_ref.hir_trait_id()))
2634 }
2635 _ => None,
2636 })
2637 .collect()
2638 }
2639
2640 pub fn default(self, db: &dyn HirDatabase) -> Option<Type> {
2641 let params = db.generic_defaults(self.id.parent());
2642 let local_idx = hir_ty::param_idx(db, self.id.into())?;
2643 let resolver = self.id.parent().resolver(db.upcast());
2644 let ty = params.get(local_idx)?.clone();
2645 let subst = TyBuilder::placeholder_subst(db, self.id.parent());
2646 let ty = ty.substitute(Interner, &subst);
2647 match ty.data(Interner) {
2648 GenericArgData::Ty(x) => Some(Type::new_with_resolver_inner(db, &resolver, x.clone())),
2649 _ => None,
2650 }
2651 }
2652 }
2653
2654 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2655 pub struct LifetimeParam {
2656 pub(crate) id: LifetimeParamId,
2657 }
2658
2659 impl LifetimeParam {
2660 pub fn name(self, db: &dyn HirDatabase) -> Name {
2661 let params = db.generic_params(self.id.parent);
2662 params.lifetimes[self.id.local_id].name.clone()
2663 }
2664
2665 pub fn module(self, db: &dyn HirDatabase) -> Module {
2666 self.id.parent.module(db.upcast()).into()
2667 }
2668
2669 pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef {
2670 self.id.parent.into()
2671 }
2672 }
2673
2674 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2675 pub struct ConstParam {
2676 pub(crate) id: ConstParamId,
2677 }
2678
2679 impl ConstParam {
2680 pub fn merge(self) -> TypeOrConstParam {
2681 TypeOrConstParam { id: self.id.into() }
2682 }
2683
2684 pub fn name(self, db: &dyn HirDatabase) -> Name {
2685 let params = db.generic_params(self.id.parent());
2686 match params.type_or_consts[self.id.local_id()].name() {
2687 Some(x) => x.clone(),
2688 None => {
2689 never!();
2690 Name::missing()
2691 }
2692 }
2693 }
2694
2695 pub fn module(self, db: &dyn HirDatabase) -> Module {
2696 self.id.parent().module(db.upcast()).into()
2697 }
2698
2699 pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef {
2700 self.id.parent().into()
2701 }
2702
2703 pub fn ty(self, db: &dyn HirDatabase) -> Type {
2704 Type::new(db, self.id.parent(), db.const_param_ty(self.id))
2705 }
2706 }
2707
2708 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2709 pub struct TypeOrConstParam {
2710 pub(crate) id: TypeOrConstParamId,
2711 }
2712
2713 impl TypeOrConstParam {
2714 pub fn name(self, db: &dyn HirDatabase) -> Name {
2715 let params = db.generic_params(self.id.parent);
2716 match params.type_or_consts[self.id.local_id].name() {
2717 Some(n) => n.clone(),
2718 _ => Name::missing(),
2719 }
2720 }
2721
2722 pub fn module(self, db: &dyn HirDatabase) -> Module {
2723 self.id.parent.module(db.upcast()).into()
2724 }
2725
2726 pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef {
2727 self.id.parent.into()
2728 }
2729
2730 pub fn split(self, db: &dyn HirDatabase) -> Either<ConstParam, TypeParam> {
2731 let params = db.generic_params(self.id.parent);
2732 match &params.type_or_consts[self.id.local_id] {
2733 hir_def::generics::TypeOrConstParamData::TypeParamData(_) => {
2734 Either::Right(TypeParam { id: TypeParamId::from_unchecked(self.id) })
2735 }
2736 hir_def::generics::TypeOrConstParamData::ConstParamData(_) => {
2737 Either::Left(ConstParam { id: ConstParamId::from_unchecked(self.id) })
2738 }
2739 }
2740 }
2741
2742 pub fn ty(self, db: &dyn HirDatabase) -> Type {
2743 match self.split(db) {
2744 Either::Left(x) => x.ty(db),
2745 Either::Right(x) => x.ty(db),
2746 }
2747 }
2748 }
2749
2750 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2751 pub struct Impl {
2752 pub(crate) id: ImplId,
2753 }
2754
2755 impl Impl {
2756 pub fn all_in_crate(db: &dyn HirDatabase, krate: Crate) -> Vec<Impl> {
2757 let inherent = db.inherent_impls_in_crate(krate.id);
2758 let trait_ = db.trait_impls_in_crate(krate.id);
2759
2760 inherent.all_impls().chain(trait_.all_impls()).map(Self::from).collect()
2761 }
2762
2763 pub fn all_for_type(db: &dyn HirDatabase, Type { ty, env }: Type) -> Vec<Impl> {
2764 let def_crates = match method_resolution::def_crates(db, &ty, env.krate) {
2765 Some(def_crates) => def_crates,
2766 None => return Vec::new(),
2767 };
2768
2769 let filter = |impl_def: &Impl| {
2770 let self_ty = impl_def.self_ty(db);
2771 let rref = self_ty.remove_ref();
2772 ty.equals_ctor(rref.as_ref().map_or(&self_ty.ty, |it| &it.ty))
2773 };
2774
2775 let fp = TyFingerprint::for_inherent_impl(&ty);
2776 let fp = match fp {
2777 Some(fp) => fp,
2778 None => return Vec::new(),
2779 };
2780
2781 let mut all = Vec::new();
2782 def_crates.iter().for_each(|&id| {
2783 all.extend(
2784 db.inherent_impls_in_crate(id)
2785 .for_self_ty(&ty)
2786 .iter()
2787 .cloned()
2788 .map(Self::from)
2789 .filter(filter),
2790 )
2791 });
2792 for id in def_crates
2793 .iter()
2794 .flat_map(|&id| Crate { id }.transitive_reverse_dependencies(db))
2795 .map(|Crate { id }| id)
2796 .chain(def_crates.iter().copied())
2797 .unique()
2798 {
2799 all.extend(
2800 db.trait_impls_in_crate(id)
2801 .for_self_ty_without_blanket_impls(fp)
2802 .map(Self::from)
2803 .filter(filter),
2804 );
2805 }
2806 all
2807 }
2808
2809 pub fn all_for_trait(db: &dyn HirDatabase, trait_: Trait) -> Vec<Impl> {
2810 let krate = trait_.module(db).krate();
2811 let mut all = Vec::new();
2812 for Crate { id } in krate.transitive_reverse_dependencies(db) {
2813 let impls = db.trait_impls_in_crate(id);
2814 all.extend(impls.for_trait(trait_.id).map(Self::from))
2815 }
2816 all
2817 }
2818
2819 pub fn trait_(self, db: &dyn HirDatabase) -> Option<Trait> {
2820 let trait_ref = db.impl_trait(self.id)?;
2821 let id = trait_ref.skip_binders().hir_trait_id();
2822 Some(Trait { id })
2823 }
2824
2825 pub fn trait_ref(self, db: &dyn HirDatabase) -> Option<TraitRef> {
2826 let substs = TyBuilder::placeholder_subst(db, self.id);
2827 let trait_ref = db.impl_trait(self.id)?.substitute(Interner, &substs);
2828 let resolver = self.id.resolver(db.upcast());
2829 Some(TraitRef::new_with_resolver(db, &resolver, trait_ref))
2830 }
2831
2832 pub fn self_ty(self, db: &dyn HirDatabase) -> Type {
2833 let resolver = self.id.resolver(db.upcast());
2834 let substs = TyBuilder::placeholder_subst(db, self.id);
2835 let ty = db.impl_self_ty(self.id).substitute(Interner, &substs);
2836 Type::new_with_resolver_inner(db, &resolver, ty)
2837 }
2838
2839 pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
2840 db.impl_data(self.id).items.iter().map(|it| (*it).into()).collect()
2841 }
2842
2843 pub fn is_negative(self, db: &dyn HirDatabase) -> bool {
2844 db.impl_data(self.id).is_negative
2845 }
2846
2847 pub fn module(self, db: &dyn HirDatabase) -> Module {
2848 self.id.lookup(db.upcast()).container.into()
2849 }
2850
2851 pub fn is_builtin_derive(self, db: &dyn HirDatabase) -> Option<InFile<ast::Attr>> {
2852 let src = self.source(db)?;
2853 src.file_id.is_builtin_derive(db.upcast())
2854 }
2855 }
2856
2857 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
2858 pub struct TraitRef {
2859 env: Arc<TraitEnvironment>,
2860 trait_ref: hir_ty::TraitRef,
2861 }
2862
2863 impl TraitRef {
2864 pub(crate) fn new_with_resolver(
2865 db: &dyn HirDatabase,
2866 resolver: &Resolver,
2867 trait_ref: hir_ty::TraitRef,
2868 ) -> TraitRef {
2869 let env = resolver.generic_def().map_or_else(
2870 || Arc::new(TraitEnvironment::empty(resolver.krate())),
2871 |d| db.trait_environment(d),
2872 );
2873 TraitRef { env, trait_ref }
2874 }
2875
2876 pub fn trait_(&self) -> Trait {
2877 let id = self.trait_ref.hir_trait_id();
2878 Trait { id }
2879 }
2880
2881 pub fn self_ty(&self) -> Type {
2882 let ty = self.trait_ref.self_type_parameter(Interner);
2883 Type { env: self.env.clone(), ty }
2884 }
2885
2886 /// Returns `idx`-th argument of this trait reference if it is a type argument. Note that the
2887 /// first argument is the `Self` type.
2888 pub fn get_type_argument(&self, idx: usize) -> Option<Type> {
2889 self.trait_ref
2890 .substitution
2891 .as_slice(Interner)
2892 .get(idx)
2893 .and_then(|arg| arg.ty(Interner))
2894 .cloned()
2895 .map(|ty| Type { env: self.env.clone(), ty })
2896 }
2897 }
2898
2899 #[derive(Clone, PartialEq, Eq, Debug)]
2900 pub struct Type {
2901 env: Arc<TraitEnvironment>,
2902 ty: Ty,
2903 }
2904
2905 impl Type {
2906 pub(crate) fn new_with_resolver(db: &dyn HirDatabase, resolver: &Resolver, ty: Ty) -> Type {
2907 Type::new_with_resolver_inner(db, resolver, ty)
2908 }
2909
2910 pub(crate) fn new_with_resolver_inner(
2911 db: &dyn HirDatabase,
2912 resolver: &Resolver,
2913 ty: Ty,
2914 ) -> Type {
2915 let environment = resolver.generic_def().map_or_else(
2916 || Arc::new(TraitEnvironment::empty(resolver.krate())),
2917 |d| db.trait_environment(d),
2918 );
2919 Type { env: environment, ty }
2920 }
2921
2922 pub(crate) fn new_for_crate(krate: CrateId, ty: Ty) -> Type {
2923 Type { env: Arc::new(TraitEnvironment::empty(krate)), ty }
2924 }
2925
2926 pub fn reference(inner: &Type, m: Mutability) -> Type {
2927 inner.derived(
2928 TyKind::Ref(
2929 if m.is_mut() { hir_ty::Mutability::Mut } else { hir_ty::Mutability::Not },
2930 hir_ty::static_lifetime(),
2931 inner.ty.clone(),
2932 )
2933 .intern(Interner),
2934 )
2935 }
2936
2937 fn new(db: &dyn HirDatabase, lexical_env: impl HasResolver, ty: Ty) -> Type {
2938 let resolver = lexical_env.resolver(db.upcast());
2939 let environment = resolver.generic_def().map_or_else(
2940 || Arc::new(TraitEnvironment::empty(resolver.krate())),
2941 |d| db.trait_environment(d),
2942 );
2943 Type { env: environment, ty }
2944 }
2945
2946 fn from_def(db: &dyn HirDatabase, def: impl HasResolver + Into<TyDefId>) -> Type {
2947 let ty_def = def.into();
2948 let parent_subst = match ty_def {
2949 TyDefId::TypeAliasId(id) => match id.lookup(db.upcast()).container {
2950 ItemContainerId::TraitId(id) => {
2951 let subst = TyBuilder::subst_for_def(db, id, None).fill_with_unknown().build();
2952 Some(subst)
2953 }
2954 ItemContainerId::ImplId(id) => {
2955 let subst = TyBuilder::subst_for_def(db, id, None).fill_with_unknown().build();
2956 Some(subst)
2957 }
2958 _ => None,
2959 },
2960 _ => None,
2961 };
2962 let ty = TyBuilder::def_ty(db, ty_def, parent_subst).fill_with_unknown().build();
2963 Type::new(db, def, ty)
2964 }
2965
2966 pub fn new_slice(ty: Type) -> Type {
2967 Type { env: ty.env, ty: TyBuilder::slice(ty.ty) }
2968 }
2969
2970 pub fn is_unit(&self) -> bool {
2971 matches!(self.ty.kind(Interner), TyKind::Tuple(0, ..))
2972 }
2973
2974 pub fn is_bool(&self) -> bool {
2975 matches!(self.ty.kind(Interner), TyKind::Scalar(Scalar::Bool))
2976 }
2977
2978 pub fn is_never(&self) -> bool {
2979 matches!(self.ty.kind(Interner), TyKind::Never)
2980 }
2981
2982 pub fn is_mutable_reference(&self) -> bool {
2983 matches!(self.ty.kind(Interner), TyKind::Ref(hir_ty::Mutability::Mut, ..))
2984 }
2985
2986 pub fn is_reference(&self) -> bool {
2987 matches!(self.ty.kind(Interner), TyKind::Ref(..))
2988 }
2989
2990 pub fn as_reference(&self) -> Option<(Type, Mutability)> {
2991 let (ty, _lt, m) = self.ty.as_reference()?;
2992 let m = Mutability::from_mutable(matches!(m, hir_ty::Mutability::Mut));
2993 Some((self.derived(ty.clone()), m))
2994 }
2995
2996 pub fn is_slice(&self) -> bool {
2997 matches!(self.ty.kind(Interner), TyKind::Slice(..))
2998 }
2999
3000 pub fn is_usize(&self) -> bool {
3001 matches!(self.ty.kind(Interner), TyKind::Scalar(Scalar::Uint(UintTy::Usize)))
3002 }
3003
3004 pub fn is_int_or_uint(&self) -> bool {
3005 match self.ty.kind(Interner) {
3006 TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_)) => true,
3007 _ => false,
3008 }
3009 }
3010
3011 pub fn remove_ref(&self) -> Option<Type> {
3012 match &self.ty.kind(Interner) {
3013 TyKind::Ref(.., ty) => Some(self.derived(ty.clone())),
3014 _ => None,
3015 }
3016 }
3017
3018 pub fn strip_references(&self) -> Type {
3019 self.derived(self.ty.strip_references().clone())
3020 }
3021
3022 pub fn strip_reference(&self) -> Type {
3023 self.derived(self.ty.strip_reference().clone())
3024 }
3025
3026 pub fn is_unknown(&self) -> bool {
3027 self.ty.is_unknown()
3028 }
3029
3030 /// Checks that particular type `ty` implements `std::future::IntoFuture` or
3031 /// `std::future::Future`.
3032 /// This function is used in `.await` syntax completion.
3033 pub fn impls_into_future(&self, db: &dyn HirDatabase) -> bool {
3034 let trait_ = db
3035 .lang_item(self.env.krate, LangItem::IntoFutureIntoFuture)
3036 .and_then(|it| {
3037 let into_future_fn = it.as_function()?;
3038 let assoc_item = as_assoc_item(db, AssocItem::Function, into_future_fn)?;
3039 let into_future_trait = assoc_item.containing_trait_or_trait_impl(db)?;
3040 Some(into_future_trait.id)
3041 })
3042 .or_else(|| {
3043 let future_trait = db.lang_item(self.env.krate, LangItem::Future)?;
3044 future_trait.as_trait()
3045 });
3046
3047 let trait_ = match trait_ {
3048 Some(it) => it,
3049 None => return false,
3050 };
3051
3052 let canonical_ty =
3053 Canonical { value: self.ty.clone(), binders: CanonicalVarKinds::empty(Interner) };
3054 method_resolution::implements_trait(&canonical_ty, db, self.env.clone(), trait_)
3055 }
3056
3057 /// Checks that particular type `ty` implements `std::ops::FnOnce`.
3058 ///
3059 /// This function can be used to check if a particular type is callable, since FnOnce is a
3060 /// supertrait of Fn and FnMut, so all callable types implements at least FnOnce.
3061 pub fn impls_fnonce(&self, db: &dyn HirDatabase) -> bool {
3062 let fnonce_trait = match FnTrait::FnOnce.get_id(db, self.env.krate) {
3063 Some(it) => it,
3064 None => return false,
3065 };
3066
3067 let canonical_ty =
3068 Canonical { value: self.ty.clone(), binders: CanonicalVarKinds::empty(Interner) };
3069 method_resolution::implements_trait_unique(
3070 &canonical_ty,
3071 db,
3072 self.env.clone(),
3073 fnonce_trait,
3074 )
3075 }
3076
3077 pub fn impls_trait(&self, db: &dyn HirDatabase, trait_: Trait, args: &[Type]) -> bool {
3078 let mut it = args.iter().map(|t| t.ty.clone());
3079 let trait_ref = TyBuilder::trait_ref(db, trait_.id)
3080 .push(self.ty.clone())
3081 .fill(|x| {
3082 let r = it.next().unwrap();
3083 match x {
3084 ParamKind::Type => GenericArgData::Ty(r).intern(Interner),
3085 ParamKind::Const(ty) => {
3086 // FIXME: this code is not covered in tests.
3087 unknown_const_as_generic(ty.clone())
3088 }
3089 }
3090 })
3091 .build();
3092
3093 let goal = Canonical {
3094 value: hir_ty::InEnvironment::new(&self.env.env, trait_ref.cast(Interner)),
3095 binders: CanonicalVarKinds::empty(Interner),
3096 };
3097
3098 db.trait_solve(self.env.krate, goal).is_some()
3099 }
3100
3101 pub fn normalize_trait_assoc_type(
3102 &self,
3103 db: &dyn HirDatabase,
3104 args: &[Type],
3105 alias: TypeAlias,
3106 ) -> Option<Type> {
3107 let mut args = args.iter();
3108 let trait_id = match alias.id.lookup(db.upcast()).container {
3109 ItemContainerId::TraitId(id) => id,
3110 _ => unreachable!("non assoc type alias reached in normalize_trait_assoc_type()"),
3111 };
3112 let parent_subst = TyBuilder::subst_for_def(db, trait_id, None)
3113 .push(self.ty.clone())
3114 .fill(|x| {
3115 // FIXME: this code is not covered in tests.
3116 match x {
3117 ParamKind::Type => {
3118 GenericArgData::Ty(args.next().unwrap().ty.clone()).intern(Interner)
3119 }
3120 ParamKind::Const(ty) => unknown_const_as_generic(ty.clone()),
3121 }
3122 })
3123 .build();
3124 // FIXME: We don't handle GATs yet.
3125 let projection = TyBuilder::assoc_type_projection(db, alias.id, Some(parent_subst)).build();
3126
3127 let ty = db.normalize_projection(projection, self.env.clone());
3128 if ty.is_unknown() {
3129 None
3130 } else {
3131 Some(self.derived(ty))
3132 }
3133 }
3134
3135 pub fn is_copy(&self, db: &dyn HirDatabase) -> bool {
3136 let lang_item = db.lang_item(self.env.krate, LangItem::Copy);
3137 let copy_trait = match lang_item {
3138 Some(LangItemTarget::Trait(it)) => it,
3139 _ => return false,
3140 };
3141 self.impls_trait(db, copy_trait.into(), &[])
3142 }
3143
3144 pub fn as_callable(&self, db: &dyn HirDatabase) -> Option<Callable> {
3145 let callee = match self.ty.kind(Interner) {
3146 TyKind::Closure(id, _) => Callee::Closure(*id),
3147 TyKind::Function(_) => Callee::FnPtr,
3148 TyKind::FnDef(..) => Callee::Def(self.ty.callable_def(db)?),
3149 _ => {
3150 let sig = hir_ty::callable_sig_from_fnonce(&self.ty, self.env.clone(), db)?;
3151 return Some(Callable {
3152 ty: self.clone(),
3153 sig,
3154 callee: Callee::Other,
3155 is_bound_method: false,
3156 });
3157 }
3158 };
3159
3160 let sig = self.ty.callable_sig(db)?;
3161 Some(Callable { ty: self.clone(), sig, callee, is_bound_method: false })
3162 }
3163
3164 pub fn is_closure(&self) -> bool {
3165 matches!(self.ty.kind(Interner), TyKind::Closure { .. })
3166 }
3167
3168 pub fn is_fn(&self) -> bool {
3169 matches!(self.ty.kind(Interner), TyKind::FnDef(..) | TyKind::Function { .. })
3170 }
3171
3172 pub fn is_array(&self) -> bool {
3173 matches!(self.ty.kind(Interner), TyKind::Array(..))
3174 }
3175
3176 pub fn is_packed(&self, db: &dyn HirDatabase) -> bool {
3177 let adt_id = match *self.ty.kind(Interner) {
3178 TyKind::Adt(hir_ty::AdtId(adt_id), ..) => adt_id,
3179 _ => return false,
3180 };
3181
3182 let adt = adt_id.into();
3183 match adt {
3184 Adt::Struct(s) => s.repr(db).unwrap_or_default().pack.is_some(),
3185 _ => false,
3186 }
3187 }
3188
3189 pub fn is_raw_ptr(&self) -> bool {
3190 matches!(self.ty.kind(Interner), TyKind::Raw(..))
3191 }
3192
3193 pub fn contains_unknown(&self) -> bool {
3194 // FIXME: When we get rid of `ConstScalar::Unknown`, we can just look at precomputed
3195 // `TypeFlags` in `TyData`.
3196 return go(&self.ty);
3197
3198 fn go(ty: &Ty) -> bool {
3199 match ty.kind(Interner) {
3200 TyKind::Error => true,
3201
3202 TyKind::Adt(_, substs)
3203 | TyKind::AssociatedType(_, substs)
3204 | TyKind::Tuple(_, substs)
3205 | TyKind::OpaqueType(_, substs)
3206 | TyKind::FnDef(_, substs)
3207 | TyKind::Closure(_, substs) => {
3208 substs.iter(Interner).filter_map(|a| a.ty(Interner)).any(go)
3209 }
3210
3211 TyKind::Array(_ty, len) if len.is_unknown() => true,
3212 TyKind::Array(ty, _)
3213 | TyKind::Slice(ty)
3214 | TyKind::Raw(_, ty)
3215 | TyKind::Ref(_, _, ty) => go(ty),
3216
3217 TyKind::Scalar(_)
3218 | TyKind::Str
3219 | TyKind::Never
3220 | TyKind::Placeholder(_)
3221 | TyKind::BoundVar(_)
3222 | TyKind::InferenceVar(_, _)
3223 | TyKind::Dyn(_)
3224 | TyKind::Function(_)
3225 | TyKind::Alias(_)
3226 | TyKind::Foreign(_)
3227 | TyKind::Generator(..)
3228 | TyKind::GeneratorWitness(..) => false,
3229 }
3230 }
3231 }
3232
3233 pub fn fields(&self, db: &dyn HirDatabase) -> Vec<(Field, Type)> {
3234 let (variant_id, substs) = match self.ty.kind(Interner) {
3235 TyKind::Adt(hir_ty::AdtId(AdtId::StructId(s)), substs) => ((*s).into(), substs),
3236 TyKind::Adt(hir_ty::AdtId(AdtId::UnionId(u)), substs) => ((*u).into(), substs),
3237 _ => return Vec::new(),
3238 };
3239
3240 db.field_types(variant_id)
3241 .iter()
3242 .map(|(local_id, ty)| {
3243 let def = Field { parent: variant_id.into(), id: local_id };
3244 let ty = ty.clone().substitute(Interner, substs);
3245 (def, self.derived(ty))
3246 })
3247 .collect()
3248 }
3249
3250 pub fn tuple_fields(&self, _db: &dyn HirDatabase) -> Vec<Type> {
3251 if let TyKind::Tuple(_, substs) = &self.ty.kind(Interner) {
3252 substs
3253 .iter(Interner)
3254 .map(|ty| self.derived(ty.assert_ty_ref(Interner).clone()))
3255 .collect()
3256 } else {
3257 Vec::new()
3258 }
3259 }
3260
3261 pub fn as_array(&self, _db: &dyn HirDatabase) -> Option<(Type, usize)> {
3262 if let TyKind::Array(ty, len) = &self.ty.kind(Interner) {
3263 match len.data(Interner).value {
3264 ConstValue::Concrete(ConcreteConst { interned: ConstScalar::UInt(len) }) => {
3265 Some((self.derived(ty.clone()), len as usize))
3266 }
3267 _ => None,
3268 }
3269 } else {
3270 None
3271 }
3272 }
3273
3274 pub fn autoderef<'a>(&'a self, db: &'a dyn HirDatabase) -> impl Iterator<Item = Type> + 'a {
3275 self.autoderef_(db).map(move |ty| self.derived(ty))
3276 }
3277
3278 fn autoderef_<'a>(&'a self, db: &'a dyn HirDatabase) -> impl Iterator<Item = Ty> + 'a {
3279 // There should be no inference vars in types passed here
3280 let canonical = hir_ty::replace_errors_with_variables(&self.ty);
3281 let environment = self.env.clone();
3282 autoderef(db, environment, canonical).map(|canonical| canonical.value)
3283 }
3284
3285 // This would be nicer if it just returned an iterator, but that runs into
3286 // lifetime problems, because we need to borrow temp `CrateImplDefs`.
3287 pub fn iterate_assoc_items<T>(
3288 &self,
3289 db: &dyn HirDatabase,
3290 krate: Crate,
3291 mut callback: impl FnMut(AssocItem) -> Option<T>,
3292 ) -> Option<T> {
3293 let mut slot = None;
3294 self.iterate_assoc_items_dyn(db, krate, &mut |assoc_item_id| {
3295 slot = callback(assoc_item_id.into());
3296 slot.is_some()
3297 });
3298 slot
3299 }
3300
3301 fn iterate_assoc_items_dyn(
3302 &self,
3303 db: &dyn HirDatabase,
3304 krate: Crate,
3305 callback: &mut dyn FnMut(AssocItemId) -> bool,
3306 ) {
3307 let def_crates = match method_resolution::def_crates(db, &self.ty, krate.id) {
3308 Some(it) => it,
3309 None => return,
3310 };
3311 for krate in def_crates {
3312 let impls = db.inherent_impls_in_crate(krate);
3313
3314 for impl_def in impls.for_self_ty(&self.ty) {
3315 for &item in db.impl_data(*impl_def).items.iter() {
3316 if callback(item) {
3317 return;
3318 }
3319 }
3320 }
3321 }
3322 }
3323
3324 pub fn type_arguments(&self) -> impl Iterator<Item = Type> + '_ {
3325 self.ty
3326 .strip_references()
3327 .as_adt()
3328 .into_iter()
3329 .flat_map(|(_, substs)| substs.iter(Interner))
3330 .filter_map(|arg| arg.ty(Interner).cloned())
3331 .map(move |ty| self.derived(ty))
3332 }
3333
3334 pub fn iterate_method_candidates<T>(
3335 &self,
3336 db: &dyn HirDatabase,
3337 scope: &SemanticsScope<'_>,
3338 // FIXME this can be retrieved from `scope`, except autoimport uses this
3339 // to specify a different set, so the method needs to be split
3340 traits_in_scope: &FxHashSet<TraitId>,
3341 with_local_impls: Option<Module>,
3342 name: Option<&Name>,
3343 mut callback: impl FnMut(Function) -> Option<T>,
3344 ) -> Option<T> {
3345 let _p = profile::span("iterate_method_candidates");
3346 let mut slot = None;
3347
3348 self.iterate_method_candidates_dyn(
3349 db,
3350 scope,
3351 traits_in_scope,
3352 with_local_impls,
3353 name,
3354 &mut |assoc_item_id| {
3355 if let AssocItemId::FunctionId(func) = assoc_item_id {
3356 if let Some(res) = callback(func.into()) {
3357 slot = Some(res);
3358 return ControlFlow::Break(());
3359 }
3360 }
3361 ControlFlow::Continue(())
3362 },
3363 );
3364 slot
3365 }
3366
3367 fn iterate_method_candidates_dyn(
3368 &self,
3369 db: &dyn HirDatabase,
3370 scope: &SemanticsScope<'_>,
3371 traits_in_scope: &FxHashSet<TraitId>,
3372 with_local_impls: Option<Module>,
3373 name: Option<&Name>,
3374 callback: &mut dyn FnMut(AssocItemId) -> ControlFlow<()>,
3375 ) {
3376 // There should be no inference vars in types passed here
3377 let canonical = hir_ty::replace_errors_with_variables(&self.ty);
3378
3379 let krate = scope.krate();
3380 let environment = scope.resolver().generic_def().map_or_else(
3381 || Arc::new(TraitEnvironment::empty(krate.id)),
3382 |d| db.trait_environment(d),
3383 );
3384
3385 method_resolution::iterate_method_candidates_dyn(
3386 &canonical,
3387 db,
3388 environment,
3389 traits_in_scope,
3390 with_local_impls.and_then(|b| b.id.containing_block()).into(),
3391 name,
3392 method_resolution::LookupMode::MethodCall,
3393 &mut |_adj, id, _| callback(id),
3394 );
3395 }
3396
3397 pub fn iterate_path_candidates<T>(
3398 &self,
3399 db: &dyn HirDatabase,
3400 scope: &SemanticsScope<'_>,
3401 traits_in_scope: &FxHashSet<TraitId>,
3402 with_local_impls: Option<Module>,
3403 name: Option<&Name>,
3404 mut callback: impl FnMut(AssocItem) -> Option<T>,
3405 ) -> Option<T> {
3406 let _p = profile::span("iterate_path_candidates");
3407 let mut slot = None;
3408 self.iterate_path_candidates_dyn(
3409 db,
3410 scope,
3411 traits_in_scope,
3412 with_local_impls,
3413 name,
3414 &mut |assoc_item_id| {
3415 if let Some(res) = callback(assoc_item_id.into()) {
3416 slot = Some(res);
3417 return ControlFlow::Break(());
3418 }
3419 ControlFlow::Continue(())
3420 },
3421 );
3422 slot
3423 }
3424
3425 fn iterate_path_candidates_dyn(
3426 &self,
3427 db: &dyn HirDatabase,
3428 scope: &SemanticsScope<'_>,
3429 traits_in_scope: &FxHashSet<TraitId>,
3430 with_local_impls: Option<Module>,
3431 name: Option<&Name>,
3432 callback: &mut dyn FnMut(AssocItemId) -> ControlFlow<()>,
3433 ) {
3434 let canonical = hir_ty::replace_errors_with_variables(&self.ty);
3435
3436 let krate = scope.krate();
3437 let environment = scope.resolver().generic_def().map_or_else(
3438 || Arc::new(TraitEnvironment::empty(krate.id)),
3439 |d| db.trait_environment(d),
3440 );
3441
3442 method_resolution::iterate_path_candidates(
3443 &canonical,
3444 db,
3445 environment,
3446 traits_in_scope,
3447 with_local_impls.and_then(|b| b.id.containing_block()).into(),
3448 name,
3449 &mut |id| callback(id),
3450 );
3451 }
3452
3453 pub fn as_adt(&self) -> Option<Adt> {
3454 let (adt, _subst) = self.ty.as_adt()?;
3455 Some(adt.into())
3456 }
3457
3458 pub fn as_builtin(&self) -> Option<BuiltinType> {
3459 self.ty.as_builtin().map(|inner| BuiltinType { inner })
3460 }
3461
3462 pub fn as_dyn_trait(&self) -> Option<Trait> {
3463 self.ty.dyn_trait().map(Into::into)
3464 }
3465
3466 /// If a type can be represented as `dyn Trait`, returns all traits accessible via this type,
3467 /// or an empty iterator otherwise.
3468 pub fn applicable_inherent_traits<'a>(
3469 &'a self,
3470 db: &'a dyn HirDatabase,
3471 ) -> impl Iterator<Item = Trait> + 'a {
3472 let _p = profile::span("applicable_inherent_traits");
3473 self.autoderef_(db)
3474 .filter_map(|ty| ty.dyn_trait())
3475 .flat_map(move |dyn_trait_id| hir_ty::all_super_traits(db.upcast(), dyn_trait_id))
3476 .map(Trait::from)
3477 }
3478
3479 pub fn env_traits<'a>(&'a self, db: &'a dyn HirDatabase) -> impl Iterator<Item = Trait> + 'a {
3480 let _p = profile::span("env_traits");
3481 self.autoderef_(db)
3482 .filter(|ty| matches!(ty.kind(Interner), TyKind::Placeholder(_)))
3483 .flat_map(|ty| {
3484 self.env
3485 .traits_in_scope_from_clauses(ty)
3486 .flat_map(|t| hir_ty::all_super_traits(db.upcast(), t))
3487 })
3488 .map(Trait::from)
3489 }
3490
3491 pub fn as_impl_traits(&self, db: &dyn HirDatabase) -> Option<impl Iterator<Item = Trait>> {
3492 self.ty.impl_trait_bounds(db).map(|it| {
3493 it.into_iter().filter_map(|pred| match pred.skip_binders() {
3494 hir_ty::WhereClause::Implemented(trait_ref) => {
3495 Some(Trait::from(trait_ref.hir_trait_id()))
3496 }
3497 _ => None,
3498 })
3499 })
3500 }
3501
3502 pub fn as_associated_type_parent_trait(&self, db: &dyn HirDatabase) -> Option<Trait> {
3503 self.ty.associated_type_parent_trait(db).map(Into::into)
3504 }
3505
3506 fn derived(&self, ty: Ty) -> Type {
3507 Type { env: self.env.clone(), ty }
3508 }
3509
3510 /// Visits every type, including generic arguments, in this type. `cb` is called with type
3511 /// itself first, and then with its generic arguments.
3512 pub fn walk(&self, db: &dyn HirDatabase, mut cb: impl FnMut(Type)) {
3513 fn walk_substs(
3514 db: &dyn HirDatabase,
3515 type_: &Type,
3516 substs: &Substitution,
3517 cb: &mut impl FnMut(Type),
3518 ) {
3519 for ty in substs.iter(Interner).filter_map(|a| a.ty(Interner)) {
3520 walk_type(db, &type_.derived(ty.clone()), cb);
3521 }
3522 }
3523
3524 fn walk_bounds(
3525 db: &dyn HirDatabase,
3526 type_: &Type,
3527 bounds: &[QuantifiedWhereClause],
3528 cb: &mut impl FnMut(Type),
3529 ) {
3530 for pred in bounds {
3531 if let WhereClause::Implemented(trait_ref) = pred.skip_binders() {
3532 cb(type_.clone());
3533 // skip the self type. it's likely the type we just got the bounds from
3534 for ty in
3535 trait_ref.substitution.iter(Interner).skip(1).filter_map(|a| a.ty(Interner))
3536 {
3537 walk_type(db, &type_.derived(ty.clone()), cb);
3538 }
3539 }
3540 }
3541 }
3542
3543 fn walk_type(db: &dyn HirDatabase, type_: &Type, cb: &mut impl FnMut(Type)) {
3544 let ty = type_.ty.strip_references();
3545 match ty.kind(Interner) {
3546 TyKind::Adt(_, substs) => {
3547 cb(type_.derived(ty.clone()));
3548 walk_substs(db, type_, substs, cb);
3549 }
3550 TyKind::AssociatedType(_, substs) => {
3551 if ty.associated_type_parent_trait(db).is_some() {
3552 cb(type_.derived(ty.clone()));
3553 }
3554 walk_substs(db, type_, substs, cb);
3555 }
3556 TyKind::OpaqueType(_, subst) => {
3557 if let Some(bounds) = ty.impl_trait_bounds(db) {
3558 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
3559 }
3560
3561 walk_substs(db, type_, subst, cb);
3562 }
3563 TyKind::Alias(AliasTy::Opaque(opaque_ty)) => {
3564 if let Some(bounds) = ty.impl_trait_bounds(db) {
3565 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
3566 }
3567
3568 walk_substs(db, type_, &opaque_ty.substitution, cb);
3569 }
3570 TyKind::Placeholder(_) => {
3571 if let Some(bounds) = ty.impl_trait_bounds(db) {
3572 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
3573 }
3574 }
3575 TyKind::Dyn(bounds) => {
3576 walk_bounds(
3577 db,
3578 &type_.derived(ty.clone()),
3579 bounds.bounds.skip_binders().interned(),
3580 cb,
3581 );
3582 }
3583
3584 TyKind::Ref(_, _, ty)
3585 | TyKind::Raw(_, ty)
3586 | TyKind::Array(ty, _)
3587 | TyKind::Slice(ty) => {
3588 walk_type(db, &type_.derived(ty.clone()), cb);
3589 }
3590
3591 TyKind::FnDef(_, substs)
3592 | TyKind::Tuple(_, substs)
3593 | TyKind::Closure(.., substs) => {
3594 walk_substs(db, type_, substs, cb);
3595 }
3596 TyKind::Function(hir_ty::FnPointer { substitution, .. }) => {
3597 walk_substs(db, type_, &substitution.0, cb);
3598 }
3599
3600 _ => {}
3601 }
3602 }
3603
3604 walk_type(db, self, &mut cb);
3605 }
3606
3607 pub fn could_unify_with(&self, db: &dyn HirDatabase, other: &Type) -> bool {
3608 let tys = hir_ty::replace_errors_with_variables(&(self.ty.clone(), other.ty.clone()));
3609 hir_ty::could_unify(db, self.env.clone(), &tys)
3610 }
3611
3612 pub fn could_coerce_to(&self, db: &dyn HirDatabase, to: &Type) -> bool {
3613 let tys = hir_ty::replace_errors_with_variables(&(self.ty.clone(), to.ty.clone()));
3614 hir_ty::could_coerce(db, self.env.clone(), &tys)
3615 }
3616
3617 pub fn as_type_param(&self, db: &dyn HirDatabase) -> Option<TypeParam> {
3618 match self.ty.kind(Interner) {
3619 TyKind::Placeholder(p) => Some(TypeParam {
3620 id: TypeParamId::from_unchecked(hir_ty::from_placeholder_idx(db, *p)),
3621 }),
3622 _ => None,
3623 }
3624 }
3625
3626 /// Returns unique `GenericParam`s contained in this type.
3627 pub fn generic_params(&self, db: &dyn HirDatabase) -> FxHashSet<GenericParam> {
3628 hir_ty::collect_placeholders(&self.ty, db)
3629 .into_iter()
3630 .map(|id| TypeOrConstParam { id }.split(db).either_into())
3631 .collect()
3632 }
3633 }
3634
3635 #[derive(Debug)]
3636 pub struct Callable {
3637 ty: Type,
3638 sig: CallableSig,
3639 callee: Callee,
3640 pub(crate) is_bound_method: bool,
3641 }
3642
3643 #[derive(Debug)]
3644 enum Callee {
3645 Def(CallableDefId),
3646 Closure(ClosureId),
3647 FnPtr,
3648 Other,
3649 }
3650
3651 pub enum CallableKind {
3652 Function(Function),
3653 TupleStruct(Struct),
3654 TupleEnumVariant(Variant),
3655 Closure,
3656 FnPtr,
3657 /// Some other type that implements `FnOnce`.
3658 Other,
3659 }
3660
3661 impl Callable {
3662 pub fn kind(&self) -> CallableKind {
3663 use Callee::*;
3664 match self.callee {
3665 Def(CallableDefId::FunctionId(it)) => CallableKind::Function(it.into()),
3666 Def(CallableDefId::StructId(it)) => CallableKind::TupleStruct(it.into()),
3667 Def(CallableDefId::EnumVariantId(it)) => CallableKind::TupleEnumVariant(it.into()),
3668 Closure(_) => CallableKind::Closure,
3669 FnPtr => CallableKind::FnPtr,
3670 Other => CallableKind::Other,
3671 }
3672 }
3673 pub fn receiver_param(&self, db: &dyn HirDatabase) -> Option<ast::SelfParam> {
3674 let func = match self.callee {
3675 Callee::Def(CallableDefId::FunctionId(it)) if self.is_bound_method => it,
3676 _ => return None,
3677 };
3678 let src = func.lookup(db.upcast()).source(db.upcast());
3679 let param_list = src.value.param_list()?;
3680 param_list.self_param()
3681 }
3682 pub fn n_params(&self) -> usize {
3683 self.sig.params().len() - if self.is_bound_method { 1 } else { 0 }
3684 }
3685 pub fn params(
3686 &self,
3687 db: &dyn HirDatabase,
3688 ) -> Vec<(Option<Either<ast::SelfParam, ast::Pat>>, Type)> {
3689 let types = self
3690 .sig
3691 .params()
3692 .iter()
3693 .skip(if self.is_bound_method { 1 } else { 0 })
3694 .map(|ty| self.ty.derived(ty.clone()));
3695 let map_param = |it: ast::Param| it.pat().map(Either::Right);
3696 let patterns = match self.callee {
3697 Callee::Def(CallableDefId::FunctionId(func)) => {
3698 let src = func.lookup(db.upcast()).source(db.upcast());
3699 src.value.param_list().map(|param_list| {
3700 param_list
3701 .self_param()
3702 .map(|it| Some(Either::Left(it)))
3703 .filter(|_| !self.is_bound_method)
3704 .into_iter()
3705 .chain(param_list.params().map(map_param))
3706 })
3707 }
3708 Callee::Closure(closure_id) => match closure_source(db, closure_id) {
3709 Some(src) => src.param_list().map(|param_list| {
3710 param_list
3711 .self_param()
3712 .map(|it| Some(Either::Left(it)))
3713 .filter(|_| !self.is_bound_method)
3714 .into_iter()
3715 .chain(param_list.params().map(map_param))
3716 }),
3717 None => None,
3718 },
3719 _ => None,
3720 };
3721 patterns.into_iter().flatten().chain(iter::repeat(None)).zip(types).collect()
3722 }
3723 pub fn return_type(&self) -> Type {
3724 self.ty.derived(self.sig.ret().clone())
3725 }
3726 }
3727
3728 fn closure_source(db: &dyn HirDatabase, closure: ClosureId) -> Option<ast::ClosureExpr> {
3729 let (owner, expr_id) = db.lookup_intern_closure(closure.into());
3730 let (_, source_map) = db.body_with_source_map(owner);
3731 let ast = source_map.expr_syntax(expr_id).ok()?;
3732 let root = ast.file_syntax(db.upcast());
3733 let expr = ast.value.to_node(&root);
3734 match expr {
3735 ast::Expr::ClosureExpr(it) => Some(it),
3736 _ => None,
3737 }
3738 }
3739
3740 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
3741 pub enum BindingMode {
3742 Move,
3743 Ref(Mutability),
3744 }
3745
3746 /// For IDE only
3747 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
3748 pub enum ScopeDef {
3749 ModuleDef(ModuleDef),
3750 GenericParam(GenericParam),
3751 ImplSelfType(Impl),
3752 AdtSelfType(Adt),
3753 Local(Local),
3754 Label(Label),
3755 Unknown,
3756 }
3757
3758 impl ScopeDef {
3759 pub fn all_items(def: PerNs) -> ArrayVec<Self, 3> {
3760 let mut items = ArrayVec::new();
3761
3762 match (def.take_types(), def.take_values()) {
3763 (Some(m1), None) => items.push(ScopeDef::ModuleDef(m1.into())),
3764 (None, Some(m2)) => items.push(ScopeDef::ModuleDef(m2.into())),
3765 (Some(m1), Some(m2)) => {
3766 // Some items, like unit structs and enum variants, are
3767 // returned as both a type and a value. Here we want
3768 // to de-duplicate them.
3769 if m1 != m2 {
3770 items.push(ScopeDef::ModuleDef(m1.into()));
3771 items.push(ScopeDef::ModuleDef(m2.into()));
3772 } else {
3773 items.push(ScopeDef::ModuleDef(m1.into()));
3774 }
3775 }
3776 (None, None) => {}
3777 };
3778
3779 if let Some(macro_def_id) = def.take_macros() {
3780 items.push(ScopeDef::ModuleDef(ModuleDef::Macro(macro_def_id.into())));
3781 }
3782
3783 if items.is_empty() {
3784 items.push(ScopeDef::Unknown);
3785 }
3786
3787 items
3788 }
3789
3790 pub fn attrs(&self, db: &dyn HirDatabase) -> Option<AttrsWithOwner> {
3791 match self {
3792 ScopeDef::ModuleDef(it) => it.attrs(db),
3793 ScopeDef::GenericParam(it) => Some(it.attrs(db)),
3794 ScopeDef::ImplSelfType(_)
3795 | ScopeDef::AdtSelfType(_)
3796 | ScopeDef::Local(_)
3797 | ScopeDef::Label(_)
3798 | ScopeDef::Unknown => None,
3799 }
3800 }
3801
3802 pub fn krate(&self, db: &dyn HirDatabase) -> Option<Crate> {
3803 match self {
3804 ScopeDef::ModuleDef(it) => it.module(db).map(|m| m.krate()),
3805 ScopeDef::GenericParam(it) => Some(it.module(db).krate()),
3806 ScopeDef::ImplSelfType(_) => None,
3807 ScopeDef::AdtSelfType(it) => Some(it.module(db).krate()),
3808 ScopeDef::Local(it) => Some(it.module(db).krate()),
3809 ScopeDef::Label(it) => Some(it.module(db).krate()),
3810 ScopeDef::Unknown => None,
3811 }
3812 }
3813 }
3814
3815 impl From<ItemInNs> for ScopeDef {
3816 fn from(item: ItemInNs) -> Self {
3817 match item {
3818 ItemInNs::Types(id) => ScopeDef::ModuleDef(id),
3819 ItemInNs::Values(id) => ScopeDef::ModuleDef(id),
3820 ItemInNs::Macros(id) => ScopeDef::ModuleDef(ModuleDef::Macro(id)),
3821 }
3822 }
3823 }
3824
3825 #[derive(Clone, Debug, PartialEq, Eq)]
3826 pub struct Adjustment {
3827 pub source: Type,
3828 pub target: Type,
3829 pub kind: Adjust,
3830 }
3831
3832 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
3833 pub enum Adjust {
3834 /// Go from ! to any type.
3835 NeverToAny,
3836 /// Dereference once, producing a place.
3837 Deref(Option<OverloadedDeref>),
3838 /// Take the address and produce either a `&` or `*` pointer.
3839 Borrow(AutoBorrow),
3840 Pointer(PointerCast),
3841 }
3842
3843 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
3844 pub enum AutoBorrow {
3845 /// Converts from T to &T.
3846 Ref(Mutability),
3847 /// Converts from T to *T.
3848 RawPtr(Mutability),
3849 }
3850
3851 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
3852 pub struct OverloadedDeref(pub Mutability);
3853
3854 pub trait HasVisibility {
3855 fn visibility(&self, db: &dyn HirDatabase) -> Visibility;
3856 fn is_visible_from(&self, db: &dyn HirDatabase, module: Module) -> bool {
3857 let vis = self.visibility(db);
3858 vis.is_visible_from(db.upcast(), module.id)
3859 }
3860 }
3861
3862 /// Trait for obtaining the defining crate of an item.
3863 pub trait HasCrate {
3864 fn krate(&self, db: &dyn HirDatabase) -> Crate;
3865 }
3866
3867 impl<T: hir_def::HasModule> HasCrate for T {
3868 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3869 self.module(db.upcast()).krate().into()
3870 }
3871 }
3872
3873 impl HasCrate for AssocItem {
3874 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3875 self.module(db).krate()
3876 }
3877 }
3878
3879 impl HasCrate for Struct {
3880 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3881 self.module(db).krate()
3882 }
3883 }
3884
3885 impl HasCrate for Union {
3886 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3887 self.module(db).krate()
3888 }
3889 }
3890
3891 impl HasCrate for Field {
3892 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3893 self.parent_def(db).module(db).krate()
3894 }
3895 }
3896
3897 impl HasCrate for Variant {
3898 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3899 self.module(db).krate()
3900 }
3901 }
3902
3903 impl HasCrate for Function {
3904 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3905 self.module(db).krate()
3906 }
3907 }
3908
3909 impl HasCrate for Const {
3910 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3911 self.module(db).krate()
3912 }
3913 }
3914
3915 impl HasCrate for TypeAlias {
3916 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3917 self.module(db).krate()
3918 }
3919 }
3920
3921 impl HasCrate for Type {
3922 fn krate(&self, _db: &dyn HirDatabase) -> Crate {
3923 self.env.krate.into()
3924 }
3925 }
3926
3927 impl HasCrate for Macro {
3928 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3929 self.module(db).krate()
3930 }
3931 }
3932
3933 impl HasCrate for Trait {
3934 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3935 self.module(db).krate()
3936 }
3937 }
3938
3939 impl HasCrate for Static {
3940 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3941 self.module(db).krate()
3942 }
3943 }
3944
3945 impl HasCrate for Adt {
3946 fn krate(&self, db: &dyn HirDatabase) -> Crate {
3947 self.module(db).krate()
3948 }
3949 }
3950
3951 impl HasCrate for Module {
3952 fn krate(&self, _: &dyn HirDatabase) -> Crate {
3953 Module::krate(*self)
3954 }
3955 }