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