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