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