]> git.lizzy.rs Git - rust.git/blob - crates/hir/src/lib.rs
Merge #11257
[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::{self, diagnostics::DefDiagnostic},
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 _, HasDocComments, 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             emit_def_diagnostic(db, acc, diag);
527         }
528         for decl in self.declarations(db) {
529             match decl {
530                 ModuleDef::Module(m) => {
531                     // Only add diagnostics from inline modules
532                     if def_map[m.id.local_id].origin.is_inline() {
533                         m.diagnostics(db, acc)
534                     }
535                 }
536                 _ => acc.extend(decl.diagnostics(db)),
537             }
538         }
539
540         for impl_def in self.impl_defs(db) {
541             for item in impl_def.items(db) {
542                 let def: DefWithBody = match item {
543                     AssocItem::Function(it) => it.into(),
544                     AssocItem::Const(it) => it.into(),
545                     AssocItem::TypeAlias(_) => continue,
546                 };
547
548                 def.diagnostics(db, acc);
549             }
550         }
551     }
552
553     pub fn declarations(self, db: &dyn HirDatabase) -> Vec<ModuleDef> {
554         let def_map = self.id.def_map(db.upcast());
555         let scope = &def_map[self.id.local_id].scope;
556         scope
557             .declarations()
558             .map(ModuleDef::from)
559             .chain(scope.unnamed_consts().map(|id| ModuleDef::Const(Const::from(id))))
560             .collect()
561     }
562
563     pub fn impl_defs(self, db: &dyn HirDatabase) -> Vec<Impl> {
564         let def_map = self.id.def_map(db.upcast());
565         def_map[self.id.local_id].scope.impls().map(Impl::from).collect()
566     }
567
568     /// Finds a path that can be used to refer to the given item from within
569     /// this module, if possible.
570     pub fn find_use_path(self, db: &dyn DefDatabase, item: impl Into<ItemInNs>) -> Option<ModPath> {
571         hir_def::find_path::find_path(db, item.into().into(), self.into())
572     }
573
574     /// Finds a path that can be used to refer to the given item from within
575     /// this module, if possible. This is used for returning import paths for use-statements.
576     pub fn find_use_path_prefixed(
577         self,
578         db: &dyn DefDatabase,
579         item: impl Into<ItemInNs>,
580         prefix_kind: PrefixKind,
581     ) -> Option<ModPath> {
582         hir_def::find_path::find_path_prefixed(db, item.into().into(), self.into(), prefix_kind)
583     }
584 }
585
586 fn emit_def_diagnostic(db: &dyn HirDatabase, acc: &mut Vec<AnyDiagnostic>, diag: &DefDiagnostic) {
587     match &diag.kind {
588         DefDiagnosticKind::UnresolvedModule { ast: declaration, candidate } => {
589             let decl = declaration.to_node(db.upcast());
590             acc.push(
591                 UnresolvedModule {
592                     decl: InFile::new(declaration.file_id, AstPtr::new(&decl)),
593                     candidate: candidate.clone(),
594                 }
595                 .into(),
596             )
597         }
598         DefDiagnosticKind::UnresolvedExternCrate { ast } => {
599             let item = ast.to_node(db.upcast());
600             acc.push(
601                 UnresolvedExternCrate { decl: InFile::new(ast.file_id, AstPtr::new(&item)) }.into(),
602             );
603         }
604
605         DefDiagnosticKind::UnresolvedImport { id, index } => {
606             let file_id = id.file_id();
607             let item_tree = id.item_tree(db.upcast());
608             let import = &item_tree[id.value];
609
610             let use_tree = import.use_tree_to_ast(db.upcast(), file_id, *index);
611             acc.push(
612                 UnresolvedImport { decl: InFile::new(file_id, AstPtr::new(&use_tree)) }.into(),
613             );
614         }
615
616         DefDiagnosticKind::UnconfiguredCode { ast, cfg, opts } => {
617             let item = ast.to_node(db.upcast());
618             acc.push(
619                 InactiveCode {
620                     node: ast.with_value(AstPtr::new(&item).into()),
621                     cfg: cfg.clone(),
622                     opts: opts.clone(),
623                 }
624                 .into(),
625             );
626         }
627
628         DefDiagnosticKind::UnresolvedProcMacro { ast } => {
629             let mut precise_location = None;
630             let (node, name) = match ast {
631                 MacroCallKind::FnLike { ast_id, .. } => {
632                     let node = ast_id.to_node(db.upcast());
633                     (ast_id.with_value(SyntaxNodePtr::from(AstPtr::new(&node))), None)
634                 }
635                 MacroCallKind::Derive { ast_id, derive_name, .. } => {
636                     let node = ast_id.to_node(db.upcast());
637
638                     // Compute the precise location of the macro name's token in the derive
639                     // list.
640                     // FIXME: This does not handle paths to the macro, but neither does the
641                     // rest of r-a.
642                     let derive_attrs =
643                         node.attrs().filter_map(|attr| match attr.as_simple_call() {
644                             Some((name, args)) if name == "derive" => Some(args),
645                             _ => None,
646                         });
647                     'outer: for attr in derive_attrs {
648                         let tokens =
649                             attr.syntax().children_with_tokens().filter_map(|elem| match elem {
650                                 syntax::NodeOrToken::Node(_) => None,
651                                 syntax::NodeOrToken::Token(tok) => Some(tok),
652                             });
653                         for token in tokens {
654                             if token.kind() == SyntaxKind::IDENT && token.text() == &**derive_name {
655                                 precise_location = Some(token.text_range());
656                                 break 'outer;
657                             }
658                         }
659                     }
660
661                     (
662                         ast_id.with_value(SyntaxNodePtr::from(AstPtr::new(&node))),
663                         Some(derive_name.clone()),
664                     )
665                 }
666                 MacroCallKind::Attr { ast_id, invoc_attr_index, attr_name, .. } => {
667                     let node = ast_id.to_node(db.upcast());
668                     let attr = node
669                         .doc_comments_and_attrs()
670                         .nth((*invoc_attr_index) as usize)
671                         .and_then(Either::right)
672                         .unwrap_or_else(|| panic!("cannot find attribute #{}", invoc_attr_index));
673                     (
674                         ast_id.with_value(SyntaxNodePtr::from(AstPtr::new(&attr))),
675                         Some(attr_name.clone()),
676                     )
677                 }
678             };
679             acc.push(
680                 UnresolvedProcMacro { node, precise_location, macro_name: name.map(Into::into) }
681                     .into(),
682             );
683         }
684
685         DefDiagnosticKind::UnresolvedMacroCall { ast, path } => {
686             let node = ast.to_node(db.upcast());
687             acc.push(
688                 UnresolvedMacroCall {
689                     macro_call: InFile::new(ast.file_id, AstPtr::new(&node)),
690                     path: path.clone(),
691                 }
692                 .into(),
693             );
694         }
695
696         DefDiagnosticKind::MacroError { ast, message } => {
697             let node = match ast {
698                 MacroCallKind::FnLike { ast_id, .. } => {
699                     let node = ast_id.to_node(db.upcast());
700                     ast_id.with_value(SyntaxNodePtr::from(AstPtr::new(&node)))
701                 }
702                 MacroCallKind::Derive { ast_id, .. } => {
703                     // FIXME: point to the attribute instead, this creates very large diagnostics
704                     let node = ast_id.to_node(db.upcast());
705                     ast_id.with_value(SyntaxNodePtr::from(AstPtr::new(&node)))
706                 }
707                 MacroCallKind::Attr { ast_id, .. } => {
708                     // FIXME: point to the attribute instead, this creates very large diagnostics
709                     let node = ast_id.to_node(db.upcast());
710                     ast_id.with_value(SyntaxNodePtr::from(AstPtr::new(&node)))
711                 }
712             };
713             acc.push(MacroError { node, message: message.clone() }.into());
714         }
715
716         DefDiagnosticKind::UnimplementedBuiltinMacro { ast } => {
717             let node = ast.to_node(db.upcast());
718             // Must have a name, otherwise we wouldn't emit it.
719             let name = node.name().expect("unimplemented builtin macro with no name");
720             acc.push(
721                 UnimplementedBuiltinMacro {
722                     node: ast.with_value(SyntaxNodePtr::from(AstPtr::new(&name))),
723                 }
724                 .into(),
725             );
726         }
727         DefDiagnosticKind::InvalidDeriveTarget { ast, id } => {
728             let node = ast.to_node(db.upcast());
729             let derive = node.attrs().nth(*id as usize);
730             match derive {
731                 Some(derive) => {
732                     acc.push(
733                         InvalidDeriveTarget {
734                             node: ast.with_value(SyntaxNodePtr::from(AstPtr::new(&derive))),
735                         }
736                         .into(),
737                     );
738                 }
739                 None => stdx::never!("derive diagnostic on item without derive attribute"),
740             }
741         }
742         DefDiagnosticKind::MalformedDerive { ast, id } => {
743             let node = ast.to_node(db.upcast());
744             let derive = node.attrs().nth(*id as usize);
745             match derive {
746                 Some(derive) => {
747                     acc.push(
748                         MalformedDerive {
749                             node: ast.with_value(SyntaxNodePtr::from(AstPtr::new(&derive))),
750                         }
751                         .into(),
752                     );
753                 }
754                 None => stdx::never!("derive diagnostic on item without derive attribute"),
755             }
756         }
757     }
758 }
759
760 impl HasVisibility for Module {
761     fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
762         let def_map = self.id.def_map(db.upcast());
763         let module_data = &def_map[self.id.local_id];
764         module_data.visibility
765     }
766 }
767
768 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
769 pub struct Field {
770     pub(crate) parent: VariantDef,
771     pub(crate) id: LocalFieldId,
772 }
773
774 #[derive(Debug, PartialEq, Eq)]
775 pub enum FieldSource {
776     Named(ast::RecordField),
777     Pos(ast::TupleField),
778 }
779
780 impl Field {
781     pub fn name(&self, db: &dyn HirDatabase) -> Name {
782         self.parent.variant_data(db).fields()[self.id].name.clone()
783     }
784
785     /// Returns the type as in the signature of the struct (i.e., with
786     /// placeholder types for type parameters). Only use this in the context of
787     /// the field definition.
788     pub fn ty(&self, db: &dyn HirDatabase) -> Type {
789         let var_id = self.parent.into();
790         let generic_def_id: GenericDefId = match self.parent {
791             VariantDef::Struct(it) => it.id.into(),
792             VariantDef::Union(it) => it.id.into(),
793             VariantDef::Variant(it) => it.parent.id.into(),
794         };
795         let substs = TyBuilder::type_params_subst(db, generic_def_id);
796         let ty = db.field_types(var_id)[self.id].clone().substitute(Interner, &substs);
797         Type::new(db, self.parent.module(db).id.krate(), var_id, ty)
798     }
799
800     pub fn parent_def(&self, _db: &dyn HirDatabase) -> VariantDef {
801         self.parent
802     }
803 }
804
805 impl HasVisibility for Field {
806     fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
807         let variant_data = self.parent.variant_data(db);
808         let visibility = &variant_data.fields()[self.id].visibility;
809         let parent_id: hir_def::VariantId = self.parent.into();
810         visibility.resolve(db.upcast(), &parent_id.resolver(db.upcast()))
811     }
812 }
813
814 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
815 pub struct Struct {
816     pub(crate) id: StructId,
817 }
818
819 impl Struct {
820     pub fn module(self, db: &dyn HirDatabase) -> Module {
821         Module { id: self.id.lookup(db.upcast()).container }
822     }
823
824     pub fn name(self, db: &dyn HirDatabase) -> Name {
825         db.struct_data(self.id).name.clone()
826     }
827
828     pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
829         db.struct_data(self.id)
830             .variant_data
831             .fields()
832             .iter()
833             .map(|(id, _)| Field { parent: self.into(), id })
834             .collect()
835     }
836
837     pub fn ty(self, db: &dyn HirDatabase) -> Type {
838         Type::from_def(db, self.id.lookup(db.upcast()).container.krate(), self.id)
839     }
840
841     pub fn repr(self, db: &dyn HirDatabase) -> Option<ReprKind> {
842         db.struct_data(self.id).repr.clone()
843     }
844
845     pub fn kind(self, db: &dyn HirDatabase) -> StructKind {
846         self.variant_data(db).kind()
847     }
848
849     fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
850         db.struct_data(self.id).variant_data.clone()
851     }
852 }
853
854 impl HasVisibility for Struct {
855     fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
856         db.struct_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
857     }
858 }
859
860 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
861 pub struct Union {
862     pub(crate) id: UnionId,
863 }
864
865 impl Union {
866     pub fn name(self, db: &dyn HirDatabase) -> Name {
867         db.union_data(self.id).name.clone()
868     }
869
870     pub fn module(self, db: &dyn HirDatabase) -> Module {
871         Module { id: self.id.lookup(db.upcast()).container }
872     }
873
874     pub fn ty(self, db: &dyn HirDatabase) -> Type {
875         Type::from_def(db, self.id.lookup(db.upcast()).container.krate(), self.id)
876     }
877
878     pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
879         db.union_data(self.id)
880             .variant_data
881             .fields()
882             .iter()
883             .map(|(id, _)| Field { parent: self.into(), id })
884             .collect()
885     }
886
887     fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
888         db.union_data(self.id).variant_data.clone()
889     }
890 }
891
892 impl HasVisibility for Union {
893     fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
894         db.union_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
895     }
896 }
897
898 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
899 pub struct Enum {
900     pub(crate) id: EnumId,
901 }
902
903 impl Enum {
904     pub fn module(self, db: &dyn HirDatabase) -> Module {
905         Module { id: self.id.lookup(db.upcast()).container }
906     }
907
908     pub fn name(self, db: &dyn HirDatabase) -> Name {
909         db.enum_data(self.id).name.clone()
910     }
911
912     pub fn variants(self, db: &dyn HirDatabase) -> Vec<Variant> {
913         db.enum_data(self.id).variants.iter().map(|(id, _)| Variant { parent: self, id }).collect()
914     }
915
916     pub fn ty(self, db: &dyn HirDatabase) -> Type {
917         Type::from_def(db, self.id.lookup(db.upcast()).container.krate(), self.id)
918     }
919 }
920
921 impl HasVisibility for Enum {
922     fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
923         db.enum_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
924     }
925 }
926
927 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
928 pub struct Variant {
929     pub(crate) parent: Enum,
930     pub(crate) id: LocalEnumVariantId,
931 }
932
933 impl Variant {
934     pub fn module(self, db: &dyn HirDatabase) -> Module {
935         self.parent.module(db)
936     }
937
938     pub fn parent_enum(self, _db: &dyn HirDatabase) -> Enum {
939         self.parent
940     }
941
942     pub fn name(self, db: &dyn HirDatabase) -> Name {
943         db.enum_data(self.parent.id).variants[self.id].name.clone()
944     }
945
946     pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
947         self.variant_data(db)
948             .fields()
949             .iter()
950             .map(|(id, _)| Field { parent: self.into(), id })
951             .collect()
952     }
953
954     pub fn kind(self, db: &dyn HirDatabase) -> StructKind {
955         self.variant_data(db).kind()
956     }
957
958     pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
959         db.enum_data(self.parent.id).variants[self.id].variant_data.clone()
960     }
961 }
962
963 /// Variants inherit visibility from the parent enum.
964 impl HasVisibility for Variant {
965     fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
966         self.parent_enum(db).visibility(db)
967     }
968 }
969
970 /// A Data Type
971 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
972 pub enum Adt {
973     Struct(Struct),
974     Union(Union),
975     Enum(Enum),
976 }
977 impl_from!(Struct, Union, Enum for Adt);
978
979 impl Adt {
980     pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
981         let subst = db.generic_defaults(self.into());
982         subst.iter().any(|ty| ty.skip_binders().is_unknown())
983     }
984
985     /// Turns this ADT into a type. Any type parameters of the ADT will be
986     /// turned into unknown types, which is good for e.g. finding the most
987     /// general set of completions, but will not look very nice when printed.
988     pub fn ty(self, db: &dyn HirDatabase) -> Type {
989         let id = AdtId::from(self);
990         Type::from_def(db, id.module(db.upcast()).krate(), id)
991     }
992
993     pub fn module(self, db: &dyn HirDatabase) -> Module {
994         match self {
995             Adt::Struct(s) => s.module(db),
996             Adt::Union(s) => s.module(db),
997             Adt::Enum(e) => e.module(db),
998         }
999     }
1000
1001     pub fn name(self, db: &dyn HirDatabase) -> Name {
1002         match self {
1003             Adt::Struct(s) => s.name(db),
1004             Adt::Union(u) => u.name(db),
1005             Adt::Enum(e) => e.name(db),
1006         }
1007     }
1008 }
1009
1010 impl HasVisibility for Adt {
1011     fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1012         match self {
1013             Adt::Struct(it) => it.visibility(db),
1014             Adt::Union(it) => it.visibility(db),
1015             Adt::Enum(it) => it.visibility(db),
1016         }
1017     }
1018 }
1019
1020 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1021 pub enum VariantDef {
1022     Struct(Struct),
1023     Union(Union),
1024     Variant(Variant),
1025 }
1026 impl_from!(Struct, Union, Variant for VariantDef);
1027
1028 impl VariantDef {
1029     pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
1030         match self {
1031             VariantDef::Struct(it) => it.fields(db),
1032             VariantDef::Union(it) => it.fields(db),
1033             VariantDef::Variant(it) => it.fields(db),
1034         }
1035     }
1036
1037     pub fn module(self, db: &dyn HirDatabase) -> Module {
1038         match self {
1039             VariantDef::Struct(it) => it.module(db),
1040             VariantDef::Union(it) => it.module(db),
1041             VariantDef::Variant(it) => it.module(db),
1042         }
1043     }
1044
1045     pub fn name(&self, db: &dyn HirDatabase) -> Name {
1046         match self {
1047             VariantDef::Struct(s) => s.name(db),
1048             VariantDef::Union(u) => u.name(db),
1049             VariantDef::Variant(e) => e.name(db),
1050         }
1051     }
1052
1053     pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
1054         match self {
1055             VariantDef::Struct(it) => it.variant_data(db),
1056             VariantDef::Union(it) => it.variant_data(db),
1057             VariantDef::Variant(it) => it.variant_data(db),
1058         }
1059     }
1060 }
1061
1062 /// The defs which have a body.
1063 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1064 pub enum DefWithBody {
1065     Function(Function),
1066     Static(Static),
1067     Const(Const),
1068 }
1069 impl_from!(Function, Const, Static for DefWithBody);
1070
1071 impl DefWithBody {
1072     pub fn module(self, db: &dyn HirDatabase) -> Module {
1073         match self {
1074             DefWithBody::Const(c) => c.module(db),
1075             DefWithBody::Function(f) => f.module(db),
1076             DefWithBody::Static(s) => s.module(db),
1077         }
1078     }
1079
1080     pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1081         match self {
1082             DefWithBody::Function(f) => Some(f.name(db)),
1083             DefWithBody::Static(s) => Some(s.name(db)),
1084             DefWithBody::Const(c) => c.name(db),
1085         }
1086     }
1087
1088     /// Returns the type this def's body has to evaluate to.
1089     pub fn body_type(self, db: &dyn HirDatabase) -> Type {
1090         match self {
1091             DefWithBody::Function(it) => it.ret_type(db),
1092             DefWithBody::Static(it) => it.ty(db),
1093             DefWithBody::Const(it) => it.ty(db),
1094         }
1095     }
1096
1097     pub fn diagnostics(self, db: &dyn HirDatabase, acc: &mut Vec<AnyDiagnostic>) {
1098         let krate = self.module(db).id.krate();
1099
1100         let (body, source_map) = db.body_with_source_map(self.into());
1101
1102         for (_, def_map) in body.blocks(db.upcast()) {
1103             for diag in def_map.diagnostics() {
1104                 emit_def_diagnostic(db, acc, diag);
1105             }
1106         }
1107
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 lang(db: &dyn HirDatabase, krate: Crate, name: &Name) -> Option<Trait> {
1611         db.lang_item(krate.into(), name.to_smol_str())
1612             .and_then(LangItemTarget::as_trait)
1613             .map(Into::into)
1614     }
1615
1616     pub fn module(self, db: &dyn HirDatabase) -> Module {
1617         Module { id: self.id.lookup(db.upcast()).container }
1618     }
1619
1620     pub fn name(self, db: &dyn HirDatabase) -> Name {
1621         db.trait_data(self.id).name.clone()
1622     }
1623
1624     pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
1625         db.trait_data(self.id).items.iter().map(|(_name, it)| (*it).into()).collect()
1626     }
1627
1628     pub fn is_auto(self, db: &dyn HirDatabase) -> bool {
1629         db.trait_data(self.id).is_auto
1630     }
1631
1632     pub fn is_unsafe(&self, db: &dyn HirDatabase) -> bool {
1633         db.trait_data(self.id).is_unsafe
1634     }
1635 }
1636
1637 impl HasVisibility for Trait {
1638     fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1639         db.trait_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1640     }
1641 }
1642
1643 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1644 pub struct TypeAlias {
1645     pub(crate) id: TypeAliasId,
1646 }
1647
1648 impl TypeAlias {
1649     pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
1650         let subst = db.generic_defaults(self.id.into());
1651         subst.iter().any(|ty| ty.skip_binders().is_unknown())
1652     }
1653
1654     pub fn module(self, db: &dyn HirDatabase) -> Module {
1655         Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
1656     }
1657
1658     pub fn type_ref(self, db: &dyn HirDatabase) -> Option<TypeRef> {
1659         db.type_alias_data(self.id).type_ref.as_deref().cloned()
1660     }
1661
1662     pub fn ty(self, db: &dyn HirDatabase) -> Type {
1663         Type::from_def(db, self.id.lookup(db.upcast()).module(db.upcast()).krate(), self.id)
1664     }
1665
1666     pub fn name(self, db: &dyn HirDatabase) -> Name {
1667         db.type_alias_data(self.id).name.clone()
1668     }
1669 }
1670
1671 impl HasVisibility for TypeAlias {
1672     fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1673         let function_data = db.type_alias_data(self.id);
1674         let visibility = &function_data.visibility;
1675         visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1676     }
1677 }
1678
1679 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1680 pub struct BuiltinType {
1681     pub(crate) inner: hir_def::builtin_type::BuiltinType,
1682 }
1683
1684 impl BuiltinType {
1685     pub fn str() -> BuiltinType {
1686         BuiltinType { inner: hir_def::builtin_type::BuiltinType::Str }
1687     }
1688
1689     pub fn ty(self, db: &dyn HirDatabase, module: Module) -> Type {
1690         let resolver = module.id.resolver(db.upcast());
1691         Type::new_with_resolver(db, &resolver, TyBuilder::builtin(self.inner))
1692             .expect("crate not present in resolver")
1693     }
1694
1695     pub fn name(self) -> Name {
1696         self.inner.as_name()
1697     }
1698
1699     pub fn is_int(&self) -> bool {
1700         matches!(self.inner, hir_def::builtin_type::BuiltinType::Int(_))
1701     }
1702
1703     pub fn is_uint(&self) -> bool {
1704         matches!(self.inner, hir_def::builtin_type::BuiltinType::Uint(_))
1705     }
1706
1707     pub fn is_float(&self) -> bool {
1708         matches!(self.inner, hir_def::builtin_type::BuiltinType::Float(_))
1709     }
1710
1711     pub fn is_char(&self) -> bool {
1712         matches!(self.inner, hir_def::builtin_type::BuiltinType::Char)
1713     }
1714
1715     pub fn is_str(&self) -> bool {
1716         matches!(self.inner, hir_def::builtin_type::BuiltinType::Str)
1717     }
1718 }
1719
1720 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1721 pub enum MacroKind {
1722     /// `macro_rules!` or Macros 2.0 macro.
1723     Declarative,
1724     /// A built-in or custom derive.
1725     Derive,
1726     /// A built-in function-like macro.
1727     BuiltIn,
1728     /// A procedural attribute macro.
1729     Attr,
1730     /// A function-like procedural macro.
1731     ProcMacro,
1732 }
1733
1734 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1735 pub struct MacroDef {
1736     pub(crate) id: MacroDefId,
1737 }
1738
1739 impl MacroDef {
1740     /// FIXME: right now, this just returns the root module of the crate that
1741     /// defines this macro. The reasons for this is that macros are expanded
1742     /// early, in `hir_expand`, where modules simply do not exist yet.
1743     pub fn module(self, db: &dyn HirDatabase) -> Option<Module> {
1744         let krate = self.id.krate;
1745         let def_map = db.crate_def_map(krate);
1746         let module_id = def_map.root();
1747         Some(Module { id: def_map.module_id(module_id) })
1748     }
1749
1750     /// XXX: this parses the file
1751     pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1752         match self.source(db)?.value {
1753             Either::Left(it) => it.name().map(|it| it.as_name()),
1754             Either::Right(_) => {
1755                 let krate = self.id.krate;
1756                 let def_map = db.crate_def_map(krate);
1757                 let (_, name) = def_map.exported_proc_macros().find(|&(id, _)| id == self.id)?;
1758                 Some(name)
1759             }
1760         }
1761     }
1762
1763     pub fn kind(&self) -> MacroKind {
1764         match self.id.kind {
1765             MacroDefKind::Declarative(_) => MacroKind::Declarative,
1766             MacroDefKind::BuiltIn(_, _) | MacroDefKind::BuiltInEager(_, _) => MacroKind::BuiltIn,
1767             MacroDefKind::BuiltInDerive(_, _) => MacroKind::Derive,
1768             MacroDefKind::BuiltInAttr(_, _) => MacroKind::Attr,
1769             MacroDefKind::ProcMacro(_, base_db::ProcMacroKind::CustomDerive, _) => {
1770                 MacroKind::Derive
1771             }
1772             MacroDefKind::ProcMacro(_, base_db::ProcMacroKind::Attr, _) => MacroKind::Attr,
1773             MacroDefKind::ProcMacro(_, base_db::ProcMacroKind::FuncLike, _) => MacroKind::ProcMacro,
1774         }
1775     }
1776
1777     pub fn is_fn_like(&self) -> bool {
1778         match self.kind() {
1779             MacroKind::Declarative | MacroKind::BuiltIn | MacroKind::ProcMacro => true,
1780             MacroKind::Attr | MacroKind::Derive => false,
1781         }
1782     }
1783
1784     pub fn is_attr(&self) -> bool {
1785         matches!(self.kind(), MacroKind::Attr)
1786     }
1787 }
1788
1789 #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
1790 pub enum ItemInNs {
1791     Types(ModuleDef),
1792     Values(ModuleDef),
1793     Macros(MacroDef),
1794 }
1795
1796 impl From<MacroDef> for ItemInNs {
1797     fn from(it: MacroDef) -> Self {
1798         Self::Macros(it)
1799     }
1800 }
1801
1802 impl From<ModuleDef> for ItemInNs {
1803     fn from(module_def: ModuleDef) -> Self {
1804         match module_def {
1805             ModuleDef::Static(_) | ModuleDef::Const(_) | ModuleDef::Function(_) => {
1806                 ItemInNs::Values(module_def)
1807             }
1808             _ => ItemInNs::Types(module_def),
1809         }
1810     }
1811 }
1812
1813 impl ItemInNs {
1814     pub fn as_module_def(self) -> Option<ModuleDef> {
1815         match self {
1816             ItemInNs::Types(id) | ItemInNs::Values(id) => Some(id),
1817             ItemInNs::Macros(_) => None,
1818         }
1819     }
1820
1821     /// Returns the crate defining this item (or `None` if `self` is built-in).
1822     pub fn krate(&self, db: &dyn HirDatabase) -> Option<Crate> {
1823         match self {
1824             ItemInNs::Types(did) | ItemInNs::Values(did) => did.module(db).map(|m| m.krate()),
1825             ItemInNs::Macros(id) => id.module(db).map(|m| m.krate()),
1826         }
1827     }
1828
1829     pub fn attrs(&self, db: &dyn HirDatabase) -> Option<AttrsWithOwner> {
1830         match self {
1831             ItemInNs::Types(it) | ItemInNs::Values(it) => it.attrs(db),
1832             ItemInNs::Macros(it) => Some(it.attrs(db)),
1833         }
1834     }
1835 }
1836
1837 /// Invariant: `inner.as_assoc_item(db).is_some()`
1838 /// We do not actively enforce this invariant.
1839 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1840 pub enum AssocItem {
1841     Function(Function),
1842     Const(Const),
1843     TypeAlias(TypeAlias),
1844 }
1845 #[derive(Debug)]
1846 pub enum AssocItemContainer {
1847     Trait(Trait),
1848     Impl(Impl),
1849 }
1850 pub trait AsAssocItem {
1851     fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem>;
1852 }
1853
1854 impl AsAssocItem for Function {
1855     fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1856         as_assoc_item(db, AssocItem::Function, self.id)
1857     }
1858 }
1859 impl AsAssocItem for Const {
1860     fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1861         as_assoc_item(db, AssocItem::Const, self.id)
1862     }
1863 }
1864 impl AsAssocItem for TypeAlias {
1865     fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1866         as_assoc_item(db, AssocItem::TypeAlias, self.id)
1867     }
1868 }
1869 impl AsAssocItem for ModuleDef {
1870     fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1871         match self {
1872             ModuleDef::Function(it) => it.as_assoc_item(db),
1873             ModuleDef::Const(it) => it.as_assoc_item(db),
1874             ModuleDef::TypeAlias(it) => it.as_assoc_item(db),
1875             _ => None,
1876         }
1877     }
1878 }
1879 fn as_assoc_item<ID, DEF, CTOR, AST>(db: &dyn HirDatabase, ctor: CTOR, id: ID) -> Option<AssocItem>
1880 where
1881     ID: Lookup<Data = AssocItemLoc<AST>>,
1882     DEF: From<ID>,
1883     CTOR: FnOnce(DEF) -> AssocItem,
1884     AST: ItemTreeNode,
1885 {
1886     match id.lookup(db.upcast()).container {
1887         ItemContainerId::TraitId(_) | ItemContainerId::ImplId(_) => Some(ctor(DEF::from(id))),
1888         ItemContainerId::ModuleId(_) | ItemContainerId::ExternBlockId(_) => None,
1889     }
1890 }
1891
1892 impl AssocItem {
1893     pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1894         match self {
1895             AssocItem::Function(it) => Some(it.name(db)),
1896             AssocItem::Const(it) => it.name(db),
1897             AssocItem::TypeAlias(it) => Some(it.name(db)),
1898         }
1899     }
1900     pub fn module(self, db: &dyn HirDatabase) -> Module {
1901         match self {
1902             AssocItem::Function(f) => f.module(db),
1903             AssocItem::Const(c) => c.module(db),
1904             AssocItem::TypeAlias(t) => t.module(db),
1905         }
1906     }
1907     pub fn container(self, db: &dyn HirDatabase) -> AssocItemContainer {
1908         let container = match self {
1909             AssocItem::Function(it) => it.id.lookup(db.upcast()).container,
1910             AssocItem::Const(it) => it.id.lookup(db.upcast()).container,
1911             AssocItem::TypeAlias(it) => it.id.lookup(db.upcast()).container,
1912         };
1913         match container {
1914             ItemContainerId::TraitId(id) => AssocItemContainer::Trait(id.into()),
1915             ItemContainerId::ImplId(id) => AssocItemContainer::Impl(id.into()),
1916             ItemContainerId::ModuleId(_) | ItemContainerId::ExternBlockId(_) => {
1917                 panic!("invalid AssocItem")
1918             }
1919         }
1920     }
1921
1922     pub fn containing_trait(self, db: &dyn HirDatabase) -> Option<Trait> {
1923         match self.container(db) {
1924             AssocItemContainer::Trait(t) => Some(t),
1925             _ => None,
1926         }
1927     }
1928
1929     pub fn containing_trait_impl(self, db: &dyn HirDatabase) -> Option<Trait> {
1930         match self.container(db) {
1931             AssocItemContainer::Impl(i) => i.trait_(db),
1932             _ => None,
1933         }
1934     }
1935
1936     pub fn containing_trait_or_trait_impl(self, db: &dyn HirDatabase) -> Option<Trait> {
1937         match self.container(db) {
1938             AssocItemContainer::Trait(t) => Some(t),
1939             AssocItemContainer::Impl(i) => i.trait_(db),
1940         }
1941     }
1942 }
1943
1944 impl HasVisibility for AssocItem {
1945     fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1946         match self {
1947             AssocItem::Function(f) => f.visibility(db),
1948             AssocItem::Const(c) => c.visibility(db),
1949             AssocItem::TypeAlias(t) => t.visibility(db),
1950         }
1951     }
1952 }
1953
1954 impl From<AssocItem> for ModuleDef {
1955     fn from(assoc: AssocItem) -> Self {
1956         match assoc {
1957             AssocItem::Function(it) => ModuleDef::Function(it),
1958             AssocItem::Const(it) => ModuleDef::Const(it),
1959             AssocItem::TypeAlias(it) => ModuleDef::TypeAlias(it),
1960         }
1961     }
1962 }
1963
1964 #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
1965 pub enum GenericDef {
1966     Function(Function),
1967     Adt(Adt),
1968     Trait(Trait),
1969     TypeAlias(TypeAlias),
1970     Impl(Impl),
1971     // enum variants cannot have generics themselves, but their parent enums
1972     // can, and this makes some code easier to write
1973     Variant(Variant),
1974     // consts can have type parameters from their parents (i.e. associated consts of traits)
1975     Const(Const),
1976 }
1977 impl_from!(
1978     Function,
1979     Adt(Struct, Enum, Union),
1980     Trait,
1981     TypeAlias,
1982     Impl,
1983     Variant,
1984     Const
1985     for GenericDef
1986 );
1987
1988 impl GenericDef {
1989     pub fn params(self, db: &dyn HirDatabase) -> Vec<GenericParam> {
1990         let generics = db.generic_params(self.into());
1991         let ty_params = generics
1992             .types
1993             .iter()
1994             .map(|(local_id, _)| TypeParam { id: TypeParamId { parent: self.into(), local_id } })
1995             .map(GenericParam::TypeParam);
1996         let lt_params = generics
1997             .lifetimes
1998             .iter()
1999             .map(|(local_id, _)| LifetimeParam {
2000                 id: LifetimeParamId { parent: self.into(), local_id },
2001             })
2002             .map(GenericParam::LifetimeParam);
2003         let const_params = generics
2004             .consts
2005             .iter()
2006             .map(|(local_id, _)| ConstParam { id: ConstParamId { parent: self.into(), local_id } })
2007             .map(GenericParam::ConstParam);
2008         ty_params.chain(lt_params).chain(const_params).collect()
2009     }
2010
2011     pub fn type_params(self, db: &dyn HirDatabase) -> Vec<TypeParam> {
2012         let generics = db.generic_params(self.into());
2013         generics
2014             .types
2015             .iter()
2016             .map(|(local_id, _)| TypeParam { id: TypeParamId { parent: self.into(), local_id } })
2017             .collect()
2018     }
2019 }
2020
2021 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2022 pub struct Local {
2023     pub(crate) parent: DefWithBodyId,
2024     pub(crate) pat_id: PatId,
2025 }
2026
2027 impl Local {
2028     pub fn is_param(self, db: &dyn HirDatabase) -> bool {
2029         let src = self.source(db);
2030         match src.value {
2031             Either::Left(bind_pat) => {
2032                 bind_pat.syntax().ancestors().any(|it| ast::Param::can_cast(it.kind()))
2033             }
2034             Either::Right(_self_param) => true,
2035         }
2036     }
2037
2038     pub fn as_self_param(self, db: &dyn HirDatabase) -> Option<SelfParam> {
2039         match self.parent {
2040             DefWithBodyId::FunctionId(func) if self.is_self(db) => Some(SelfParam { func }),
2041             _ => None,
2042         }
2043     }
2044
2045     // FIXME: why is this an option? It shouldn't be?
2046     pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
2047         let body = db.body(self.parent);
2048         match &body[self.pat_id] {
2049             Pat::Bind { name, .. } => Some(name.clone()),
2050             _ => None,
2051         }
2052     }
2053
2054     pub fn is_self(self, db: &dyn HirDatabase) -> bool {
2055         self.name(db) == Some(name![self])
2056     }
2057
2058     pub fn is_mut(self, db: &dyn HirDatabase) -> bool {
2059         let body = db.body(self.parent);
2060         matches!(&body[self.pat_id], Pat::Bind { mode: BindingAnnotation::Mutable, .. })
2061     }
2062
2063     pub fn is_ref(self, db: &dyn HirDatabase) -> bool {
2064         let body = db.body(self.parent);
2065         matches!(
2066             &body[self.pat_id],
2067             Pat::Bind { mode: BindingAnnotation::Ref | BindingAnnotation::RefMut, .. }
2068         )
2069     }
2070
2071     pub fn parent(self, _db: &dyn HirDatabase) -> DefWithBody {
2072         self.parent.into()
2073     }
2074
2075     pub fn module(self, db: &dyn HirDatabase) -> Module {
2076         self.parent(db).module(db)
2077     }
2078
2079     pub fn ty(self, db: &dyn HirDatabase) -> Type {
2080         let def = self.parent;
2081         let infer = db.infer(def);
2082         let ty = infer[self.pat_id].clone();
2083         let krate = def.module(db.upcast()).krate();
2084         Type::new(db, krate, def, ty)
2085     }
2086
2087     pub fn source(self, db: &dyn HirDatabase) -> InFile<Either<ast::IdentPat, ast::SelfParam>> {
2088         let (_body, source_map) = db.body_with_source_map(self.parent);
2089         let src = source_map.pat_syntax(self.pat_id).unwrap(); // Hmm...
2090         let root = src.file_syntax(db.upcast());
2091         src.map(|ast| {
2092             ast.map_left(|it| it.cast().unwrap().to_node(&root)).map_right(|it| it.to_node(&root))
2093         })
2094     }
2095 }
2096
2097 // FIXME: Wrong name? This is could also be a registered attribute
2098 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2099 pub struct BuiltinAttr {
2100     krate: Option<CrateId>,
2101     idx: usize,
2102 }
2103
2104 impl BuiltinAttr {
2105     // FIXME: consider crates\hir_def\src\nameres\attr_resolution.rs?
2106     pub(crate) fn by_name(db: &dyn HirDatabase, krate: Crate, name: &str) -> Option<Self> {
2107         if let builtin @ Some(_) = Self::builtin(name) {
2108             return builtin;
2109         }
2110         let idx = db.crate_def_map(krate.id).registered_attrs().iter().position(|it| it == name)?;
2111         Some(BuiltinAttr { krate: Some(krate.id), idx })
2112     }
2113
2114     pub(crate) fn builtin(name: &str) -> Option<Self> {
2115         hir_def::builtin_attr::INERT_ATTRIBUTES
2116             .iter()
2117             .position(|tool| tool.name == name)
2118             .map(|idx| BuiltinAttr { krate: None, idx })
2119     }
2120
2121     pub fn name(&self, db: &dyn HirDatabase) -> SmolStr {
2122         // FIXME: Return a `Name` here
2123         match self.krate {
2124             Some(krate) => db.crate_def_map(krate).registered_attrs()[self.idx].clone(),
2125             None => SmolStr::new(hir_def::builtin_attr::INERT_ATTRIBUTES[self.idx].name),
2126         }
2127     }
2128
2129     pub fn template(&self, _: &dyn HirDatabase) -> Option<AttributeTemplate> {
2130         match self.krate {
2131             Some(_) => None,
2132             None => Some(hir_def::builtin_attr::INERT_ATTRIBUTES[self.idx].template),
2133         }
2134     }
2135 }
2136
2137 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2138 pub struct ToolModule {
2139     krate: Option<CrateId>,
2140     idx: usize,
2141 }
2142
2143 impl ToolModule {
2144     // FIXME: consider crates\hir_def\src\nameres\attr_resolution.rs?
2145     pub(crate) fn by_name(db: &dyn HirDatabase, krate: Crate, name: &str) -> Option<Self> {
2146         if let builtin @ Some(_) = Self::builtin(name) {
2147             return builtin;
2148         }
2149         let idx = db.crate_def_map(krate.id).registered_tools().iter().position(|it| it == name)?;
2150         Some(ToolModule { krate: Some(krate.id), idx })
2151     }
2152
2153     pub(crate) fn builtin(name: &str) -> Option<Self> {
2154         hir_def::builtin_attr::TOOL_MODULES
2155             .iter()
2156             .position(|&tool| tool == name)
2157             .map(|idx| ToolModule { krate: None, idx })
2158     }
2159
2160     pub fn name(&self, db: &dyn HirDatabase) -> SmolStr {
2161         // FIXME: Return a `Name` here
2162         match self.krate {
2163             Some(krate) => db.crate_def_map(krate).registered_tools()[self.idx].clone(),
2164             None => SmolStr::new(hir_def::builtin_attr::TOOL_MODULES[self.idx]),
2165         }
2166     }
2167 }
2168
2169 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2170 pub struct Label {
2171     pub(crate) parent: DefWithBodyId,
2172     pub(crate) label_id: LabelId,
2173 }
2174
2175 impl Label {
2176     pub fn module(self, db: &dyn HirDatabase) -> Module {
2177         self.parent(db).module(db)
2178     }
2179
2180     pub fn parent(self, _db: &dyn HirDatabase) -> DefWithBody {
2181         self.parent.into()
2182     }
2183
2184     pub fn name(self, db: &dyn HirDatabase) -> Name {
2185         let body = db.body(self.parent);
2186         body[self.label_id].name.clone()
2187     }
2188
2189     pub fn source(self, db: &dyn HirDatabase) -> InFile<ast::Label> {
2190         let (_body, source_map) = db.body_with_source_map(self.parent);
2191         let src = source_map.label_syntax(self.label_id);
2192         let root = src.file_syntax(db.upcast());
2193         src.map(|ast| ast.to_node(&root))
2194     }
2195 }
2196
2197 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2198 pub enum GenericParam {
2199     TypeParam(TypeParam),
2200     LifetimeParam(LifetimeParam),
2201     ConstParam(ConstParam),
2202 }
2203 impl_from!(TypeParam, LifetimeParam, ConstParam for GenericParam);
2204
2205 impl GenericParam {
2206     pub fn module(self, db: &dyn HirDatabase) -> Module {
2207         match self {
2208             GenericParam::TypeParam(it) => it.module(db),
2209             GenericParam::LifetimeParam(it) => it.module(db),
2210             GenericParam::ConstParam(it) => it.module(db),
2211         }
2212     }
2213
2214     pub fn name(self, db: &dyn HirDatabase) -> Name {
2215         match self {
2216             GenericParam::TypeParam(it) => it.name(db),
2217             GenericParam::LifetimeParam(it) => it.name(db),
2218             GenericParam::ConstParam(it) => it.name(db),
2219         }
2220     }
2221 }
2222
2223 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2224 pub struct TypeParam {
2225     pub(crate) id: TypeParamId,
2226 }
2227
2228 impl TypeParam {
2229     pub fn name(self, db: &dyn HirDatabase) -> Name {
2230         let params = db.generic_params(self.id.parent);
2231         params.types[self.id.local_id].name.clone().unwrap_or_else(Name::missing)
2232     }
2233
2234     pub fn module(self, db: &dyn HirDatabase) -> Module {
2235         self.id.parent.module(db.upcast()).into()
2236     }
2237
2238     pub fn ty(self, db: &dyn HirDatabase) -> Type {
2239         let resolver = self.id.parent.resolver(db.upcast());
2240         let krate = self.id.parent.module(db.upcast()).krate();
2241         let ty = TyKind::Placeholder(hir_ty::to_placeholder_idx(db, self.id)).intern(Interner);
2242         Type::new_with_resolver_inner(db, krate, &resolver, ty)
2243     }
2244
2245     pub fn trait_bounds(self, db: &dyn HirDatabase) -> Vec<Trait> {
2246         db.generic_predicates_for_param(self.id, None)
2247             .iter()
2248             .filter_map(|pred| match &pred.skip_binders().skip_binders() {
2249                 hir_ty::WhereClause::Implemented(trait_ref) => {
2250                     Some(Trait::from(trait_ref.hir_trait_id()))
2251                 }
2252                 _ => None,
2253             })
2254             .collect()
2255     }
2256
2257     pub fn default(self, db: &dyn HirDatabase) -> Option<Type> {
2258         let params = db.generic_defaults(self.id.parent);
2259         let local_idx = hir_ty::param_idx(db, self.id)?;
2260         let resolver = self.id.parent.resolver(db.upcast());
2261         let krate = self.id.parent.module(db.upcast()).krate();
2262         let ty = params.get(local_idx)?.clone();
2263         let subst = TyBuilder::type_params_subst(db, self.id.parent);
2264         let ty = ty.substitute(Interner, &subst_prefix(&subst, local_idx));
2265         Some(Type::new_with_resolver_inner(db, krate, &resolver, ty))
2266     }
2267 }
2268
2269 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2270 pub struct LifetimeParam {
2271     pub(crate) id: LifetimeParamId,
2272 }
2273
2274 impl LifetimeParam {
2275     pub fn name(self, db: &dyn HirDatabase) -> Name {
2276         let params = db.generic_params(self.id.parent);
2277         params.lifetimes[self.id.local_id].name.clone()
2278     }
2279
2280     pub fn module(self, db: &dyn HirDatabase) -> Module {
2281         self.id.parent.module(db.upcast()).into()
2282     }
2283
2284     pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef {
2285         self.id.parent.into()
2286     }
2287 }
2288
2289 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2290 pub struct ConstParam {
2291     pub(crate) id: ConstParamId,
2292 }
2293
2294 impl ConstParam {
2295     pub fn name(self, db: &dyn HirDatabase) -> Name {
2296         let params = db.generic_params(self.id.parent);
2297         params.consts[self.id.local_id].name.clone()
2298     }
2299
2300     pub fn module(self, db: &dyn HirDatabase) -> Module {
2301         self.id.parent.module(db.upcast()).into()
2302     }
2303
2304     pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef {
2305         self.id.parent.into()
2306     }
2307
2308     pub fn ty(self, db: &dyn HirDatabase) -> Type {
2309         let def = self.id.parent;
2310         let krate = def.module(db.upcast()).krate();
2311         Type::new(db, krate, def, db.const_param_ty(self.id))
2312     }
2313 }
2314
2315 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2316 pub struct Impl {
2317     pub(crate) id: ImplId,
2318 }
2319
2320 impl Impl {
2321     pub fn all_in_crate(db: &dyn HirDatabase, krate: Crate) -> Vec<Impl> {
2322         let inherent = db.inherent_impls_in_crate(krate.id);
2323         let trait_ = db.trait_impls_in_crate(krate.id);
2324
2325         inherent.all_impls().chain(trait_.all_impls()).map(Self::from).collect()
2326     }
2327
2328     pub fn all_for_type(db: &dyn HirDatabase, Type { krate, ty, .. }: Type) -> Vec<Impl> {
2329         let def_crates = match method_resolution::def_crates(db, &ty, krate) {
2330             Some(def_crates) => def_crates,
2331             None => return Vec::new(),
2332         };
2333
2334         let filter = |impl_def: &Impl| {
2335             let self_ty = impl_def.self_ty(db);
2336             let rref = self_ty.remove_ref();
2337             ty.equals_ctor(rref.as_ref().map_or(&self_ty.ty, |it| &it.ty))
2338         };
2339
2340         let fp = TyFingerprint::for_inherent_impl(&ty);
2341         let fp = match fp {
2342             Some(fp) => fp,
2343             None => return Vec::new(),
2344         };
2345
2346         let mut all = Vec::new();
2347         def_crates.iter().for_each(|&id| {
2348             all.extend(
2349                 db.inherent_impls_in_crate(id)
2350                     .for_self_ty(&ty)
2351                     .iter()
2352                     .cloned()
2353                     .map(Self::from)
2354                     .filter(filter),
2355             )
2356         });
2357         for id in def_crates
2358             .iter()
2359             .flat_map(|&id| Crate { id }.transitive_reverse_dependencies(db))
2360             .map(|Crate { id }| id)
2361             .chain(def_crates.iter().copied())
2362             .unique()
2363         {
2364             all.extend(
2365                 db.trait_impls_in_crate(id)
2366                     .for_self_ty_without_blanket_impls(fp)
2367                     .map(Self::from)
2368                     .filter(filter),
2369             );
2370         }
2371         all
2372     }
2373
2374     pub fn all_for_trait(db: &dyn HirDatabase, trait_: Trait) -> Vec<Impl> {
2375         let krate = trait_.module(db).krate();
2376         let mut all = Vec::new();
2377         for Crate { id } in krate.transitive_reverse_dependencies(db).into_iter() {
2378             let impls = db.trait_impls_in_crate(id);
2379             all.extend(impls.for_trait(trait_.id).map(Self::from))
2380         }
2381         all
2382     }
2383
2384     // FIXME: the return type is wrong. This should be a hir version of
2385     // `TraitRef` (to account for parameters and qualifiers)
2386     pub fn trait_(self, db: &dyn HirDatabase) -> Option<Trait> {
2387         let trait_ref = db.impl_trait(self.id)?.skip_binders().clone();
2388         let id = hir_ty::from_chalk_trait_id(trait_ref.trait_id);
2389         Some(Trait { id })
2390     }
2391
2392     pub fn self_ty(self, db: &dyn HirDatabase) -> Type {
2393         let impl_data = db.impl_data(self.id);
2394         let resolver = self.id.resolver(db.upcast());
2395         let krate = self.id.lookup(db.upcast()).container.krate();
2396         let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
2397         let ty = ctx.lower_ty(&impl_data.self_ty);
2398         Type::new_with_resolver_inner(db, krate, &resolver, ty)
2399     }
2400
2401     pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
2402         db.impl_data(self.id).items.iter().map(|it| (*it).into()).collect()
2403     }
2404
2405     pub fn is_negative(self, db: &dyn HirDatabase) -> bool {
2406         db.impl_data(self.id).is_negative
2407     }
2408
2409     pub fn module(self, db: &dyn HirDatabase) -> Module {
2410         self.id.lookup(db.upcast()).container.into()
2411     }
2412
2413     pub fn is_builtin_derive(self, db: &dyn HirDatabase) -> Option<InFile<ast::Attr>> {
2414         let src = self.source(db)?;
2415         let item = src.file_id.is_builtin_derive(db.upcast())?;
2416         let hygenic = hir_expand::hygiene::Hygiene::new(db.upcast(), item.file_id);
2417
2418         // FIXME: handle `cfg_attr`
2419         let attr = item
2420             .value
2421             .attrs()
2422             .filter_map(|it| {
2423                 let path = ModPath::from_src(db.upcast(), it.path()?, &hygenic)?;
2424                 if path.as_ident()?.to_smol_str() == "derive" {
2425                     Some(it)
2426                 } else {
2427                     None
2428                 }
2429             })
2430             .last()?;
2431
2432         Some(item.with_value(attr))
2433     }
2434 }
2435
2436 #[derive(Clone, PartialEq, Eq, Debug)]
2437 pub struct Type {
2438     krate: CrateId,
2439     env: Arc<TraitEnvironment>,
2440     ty: Ty,
2441 }
2442
2443 impl Type {
2444     pub(crate) fn new_with_resolver(
2445         db: &dyn HirDatabase,
2446         resolver: &Resolver,
2447         ty: Ty,
2448     ) -> Option<Type> {
2449         let krate = resolver.krate()?;
2450         Some(Type::new_with_resolver_inner(db, krate, resolver, ty))
2451     }
2452     pub(crate) fn new_with_resolver_inner(
2453         db: &dyn HirDatabase,
2454         krate: CrateId,
2455         resolver: &Resolver,
2456         ty: Ty,
2457     ) -> Type {
2458         let environment = resolver
2459             .generic_def()
2460             .map_or_else(|| Arc::new(TraitEnvironment::empty(krate)), |d| db.trait_environment(d));
2461         Type { krate, env: environment, ty }
2462     }
2463
2464     fn new(db: &dyn HirDatabase, krate: CrateId, lexical_env: impl HasResolver, ty: Ty) -> Type {
2465         let resolver = lexical_env.resolver(db.upcast());
2466         let environment = resolver
2467             .generic_def()
2468             .map_or_else(|| Arc::new(TraitEnvironment::empty(krate)), |d| db.trait_environment(d));
2469         Type { krate, env: environment, ty }
2470     }
2471
2472     fn from_def(
2473         db: &dyn HirDatabase,
2474         krate: CrateId,
2475         def: impl HasResolver + Into<TyDefId>,
2476     ) -> Type {
2477         let ty = TyBuilder::def_ty(db, def.into()).fill_with_unknown().build();
2478         Type::new(db, krate, def, ty)
2479     }
2480
2481     pub fn new_slice(ty: Type) -> Type {
2482         Type { krate: ty.krate, env: ty.env, ty: TyBuilder::slice(ty.ty) }
2483     }
2484
2485     pub fn is_unit(&self) -> bool {
2486         matches!(self.ty.kind(Interner), TyKind::Tuple(0, ..))
2487     }
2488
2489     pub fn is_bool(&self) -> bool {
2490         matches!(self.ty.kind(Interner), TyKind::Scalar(Scalar::Bool))
2491     }
2492
2493     pub fn is_never(&self) -> bool {
2494         matches!(self.ty.kind(Interner), TyKind::Never)
2495     }
2496
2497     pub fn is_mutable_reference(&self) -> bool {
2498         matches!(self.ty.kind(Interner), TyKind::Ref(hir_ty::Mutability::Mut, ..))
2499     }
2500
2501     pub fn is_reference(&self) -> bool {
2502         matches!(self.ty.kind(Interner), TyKind::Ref(..))
2503     }
2504
2505     pub fn is_usize(&self) -> bool {
2506         matches!(self.ty.kind(Interner), TyKind::Scalar(Scalar::Uint(UintTy::Usize)))
2507     }
2508
2509     pub fn remove_ref(&self) -> Option<Type> {
2510         match &self.ty.kind(Interner) {
2511             TyKind::Ref(.., ty) => Some(self.derived(ty.clone())),
2512             _ => None,
2513         }
2514     }
2515
2516     pub fn strip_references(&self) -> Type {
2517         self.derived(self.ty.strip_references().clone())
2518     }
2519
2520     pub fn is_unknown(&self) -> bool {
2521         self.ty.is_unknown()
2522     }
2523
2524     /// Checks that particular type `ty` implements `std::future::Future`.
2525     /// This function is used in `.await` syntax completion.
2526     pub fn impls_future(&self, db: &dyn HirDatabase) -> bool {
2527         // No special case for the type of async block, since Chalk can figure it out.
2528
2529         let krate = self.krate;
2530
2531         let std_future_trait =
2532             db.lang_item(krate, SmolStr::new_inline("future_trait")).and_then(|it| it.as_trait());
2533         let std_future_trait = match std_future_trait {
2534             Some(it) => it,
2535             None => return false,
2536         };
2537
2538         let canonical_ty =
2539             Canonical { value: self.ty.clone(), binders: CanonicalVarKinds::empty(Interner) };
2540         method_resolution::implements_trait(
2541             &canonical_ty,
2542             db,
2543             self.env.clone(),
2544             krate,
2545             std_future_trait,
2546         )
2547     }
2548
2549     /// Checks that particular type `ty` implements `std::ops::FnOnce`.
2550     ///
2551     /// This function can be used to check if a particular type is callable, since FnOnce is a
2552     /// supertrait of Fn and FnMut, so all callable types implements at least FnOnce.
2553     pub fn impls_fnonce(&self, db: &dyn HirDatabase) -> bool {
2554         let krate = self.krate;
2555
2556         let fnonce_trait = match FnTrait::FnOnce.get_id(db, krate) {
2557             Some(it) => it,
2558             None => return false,
2559         };
2560
2561         let canonical_ty =
2562             Canonical { value: self.ty.clone(), binders: CanonicalVarKinds::empty(Interner) };
2563         method_resolution::implements_trait_unique(
2564             &canonical_ty,
2565             db,
2566             self.env.clone(),
2567             krate,
2568             fnonce_trait,
2569         )
2570     }
2571
2572     pub fn impls_trait(&self, db: &dyn HirDatabase, trait_: Trait, args: &[Type]) -> bool {
2573         let trait_ref = TyBuilder::trait_ref(db, trait_.id)
2574             .push(self.ty.clone())
2575             .fill(args.iter().map(|t| t.ty.clone()))
2576             .build();
2577
2578         let goal = Canonical {
2579             value: hir_ty::InEnvironment::new(&self.env.env, trait_ref.cast(Interner)),
2580             binders: CanonicalVarKinds::empty(Interner),
2581         };
2582
2583         db.trait_solve(self.krate, goal).is_some()
2584     }
2585
2586     pub fn normalize_trait_assoc_type(
2587         &self,
2588         db: &dyn HirDatabase,
2589         args: &[Type],
2590         alias: TypeAlias,
2591     ) -> Option<Type> {
2592         let projection = TyBuilder::assoc_type_projection(db, alias.id)
2593             .push(self.ty.clone())
2594             .fill(args.iter().map(|t| t.ty.clone()))
2595             .build();
2596         let goal = hir_ty::make_canonical(
2597             InEnvironment::new(
2598                 &self.env.env,
2599                 AliasEq {
2600                     alias: AliasTy::Projection(projection),
2601                     ty: TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0))
2602                         .intern(Interner),
2603                 }
2604                 .cast(Interner),
2605             ),
2606             [TyVariableKind::General].into_iter(),
2607         );
2608
2609         match db.trait_solve(self.krate, goal)? {
2610             Solution::Unique(s) => s
2611                 .value
2612                 .subst
2613                 .as_slice(Interner)
2614                 .first()
2615                 .map(|ty| self.derived(ty.assert_ty_ref(Interner).clone())),
2616             Solution::Ambig(_) => None,
2617         }
2618     }
2619
2620     pub fn is_copy(&self, db: &dyn HirDatabase) -> bool {
2621         let lang_item = db.lang_item(self.krate, SmolStr::new_inline("copy"));
2622         let copy_trait = match lang_item {
2623             Some(LangItemTarget::TraitId(it)) => it,
2624             _ => return false,
2625         };
2626         self.impls_trait(db, copy_trait.into(), &[])
2627     }
2628
2629     pub fn as_callable(&self, db: &dyn HirDatabase) -> Option<Callable> {
2630         let def = self.ty.callable_def(db);
2631
2632         let sig = self.ty.callable_sig(db)?;
2633         Some(Callable { ty: self.clone(), sig, def, is_bound_method: false })
2634     }
2635
2636     pub fn is_closure(&self) -> bool {
2637         matches!(&self.ty.kind(Interner), TyKind::Closure { .. })
2638     }
2639
2640     pub fn is_fn(&self) -> bool {
2641         matches!(&self.ty.kind(Interner), TyKind::FnDef(..) | TyKind::Function { .. })
2642     }
2643
2644     pub fn is_array(&self) -> bool {
2645         matches!(&self.ty.kind(Interner), TyKind::Array(..))
2646     }
2647
2648     pub fn is_packed(&self, db: &dyn HirDatabase) -> bool {
2649         let adt_id = match *self.ty.kind(Interner) {
2650             TyKind::Adt(hir_ty::AdtId(adt_id), ..) => adt_id,
2651             _ => return false,
2652         };
2653
2654         let adt = adt_id.into();
2655         match adt {
2656             Adt::Struct(s) => matches!(s.repr(db), Some(ReprKind::Packed)),
2657             _ => false,
2658         }
2659     }
2660
2661     pub fn is_raw_ptr(&self) -> bool {
2662         matches!(&self.ty.kind(Interner), TyKind::Raw(..))
2663     }
2664
2665     pub fn contains_unknown(&self) -> bool {
2666         return go(&self.ty);
2667
2668         fn go(ty: &Ty) -> bool {
2669             match ty.kind(Interner) {
2670                 TyKind::Error => true,
2671
2672                 TyKind::Adt(_, substs)
2673                 | TyKind::AssociatedType(_, substs)
2674                 | TyKind::Tuple(_, substs)
2675                 | TyKind::OpaqueType(_, substs)
2676                 | TyKind::FnDef(_, substs)
2677                 | TyKind::Closure(_, substs) => {
2678                     substs.iter(Interner).filter_map(|a| a.ty(Interner)).any(go)
2679                 }
2680
2681                 TyKind::Array(_ty, len) if len.is_unknown() => true,
2682                 TyKind::Array(ty, _)
2683                 | TyKind::Slice(ty)
2684                 | TyKind::Raw(_, ty)
2685                 | TyKind::Ref(_, _, ty) => go(ty),
2686
2687                 TyKind::Scalar(_)
2688                 | TyKind::Str
2689                 | TyKind::Never
2690                 | TyKind::Placeholder(_)
2691                 | TyKind::BoundVar(_)
2692                 | TyKind::InferenceVar(_, _)
2693                 | TyKind::Dyn(_)
2694                 | TyKind::Function(_)
2695                 | TyKind::Alias(_)
2696                 | TyKind::Foreign(_)
2697                 | TyKind::Generator(..)
2698                 | TyKind::GeneratorWitness(..) => false,
2699             }
2700         }
2701     }
2702
2703     pub fn fields(&self, db: &dyn HirDatabase) -> Vec<(Field, Type)> {
2704         let (variant_id, substs) = match self.ty.kind(Interner) {
2705             TyKind::Adt(hir_ty::AdtId(AdtId::StructId(s)), substs) => ((*s).into(), substs),
2706             TyKind::Adt(hir_ty::AdtId(AdtId::UnionId(u)), substs) => ((*u).into(), substs),
2707             _ => return Vec::new(),
2708         };
2709
2710         db.field_types(variant_id)
2711             .iter()
2712             .map(|(local_id, ty)| {
2713                 let def = Field { parent: variant_id.into(), id: local_id };
2714                 let ty = ty.clone().substitute(Interner, substs);
2715                 (def, self.derived(ty))
2716             })
2717             .collect()
2718     }
2719
2720     pub fn tuple_fields(&self, _db: &dyn HirDatabase) -> Vec<Type> {
2721         if let TyKind::Tuple(_, substs) = &self.ty.kind(Interner) {
2722             substs
2723                 .iter(Interner)
2724                 .map(|ty| self.derived(ty.assert_ty_ref(Interner).clone()))
2725                 .collect()
2726         } else {
2727             Vec::new()
2728         }
2729     }
2730
2731     pub fn autoderef<'a>(&'a self, db: &'a dyn HirDatabase) -> impl Iterator<Item = Type> + 'a {
2732         self.autoderef_(db).map(move |ty| self.derived(ty))
2733     }
2734
2735     pub fn autoderef_<'a>(&'a self, db: &'a dyn HirDatabase) -> impl Iterator<Item = Ty> + 'a {
2736         // There should be no inference vars in types passed here
2737         let canonical = hir_ty::replace_errors_with_variables(&self.ty);
2738         let environment = self.env.env.clone();
2739         let ty = InEnvironment { goal: canonical, environment };
2740         autoderef(db, Some(self.krate), ty).map(|canonical| canonical.value)
2741     }
2742
2743     // This would be nicer if it just returned an iterator, but that runs into
2744     // lifetime problems, because we need to borrow temp `CrateImplDefs`.
2745     pub fn iterate_assoc_items<T>(
2746         &self,
2747         db: &dyn HirDatabase,
2748         krate: Crate,
2749         mut callback: impl FnMut(AssocItem) -> Option<T>,
2750     ) -> Option<T> {
2751         let mut slot = None;
2752         self.iterate_assoc_items_dyn(db, krate, &mut |assoc_item_id| {
2753             slot = callback(assoc_item_id.into());
2754             slot.is_some()
2755         });
2756         slot
2757     }
2758
2759     fn iterate_assoc_items_dyn(
2760         &self,
2761         db: &dyn HirDatabase,
2762         krate: Crate,
2763         callback: &mut dyn FnMut(AssocItemId) -> bool,
2764     ) {
2765         let def_crates = match method_resolution::def_crates(db, &self.ty, krate.id) {
2766             Some(it) => it,
2767             None => return,
2768         };
2769         for krate in def_crates {
2770             let impls = db.inherent_impls_in_crate(krate);
2771
2772             for impl_def in impls.for_self_ty(&self.ty) {
2773                 for &item in db.impl_data(*impl_def).items.iter() {
2774                     if callback(item) {
2775                         return;
2776                     }
2777                 }
2778             }
2779         }
2780     }
2781
2782     pub fn type_arguments(&self) -> impl Iterator<Item = Type> + '_ {
2783         self.ty
2784             .strip_references()
2785             .as_adt()
2786             .into_iter()
2787             .flat_map(|(_, substs)| substs.iter(Interner))
2788             .filter_map(|arg| arg.ty(Interner).cloned())
2789             .map(move |ty| self.derived(ty))
2790     }
2791
2792     pub fn iterate_method_candidates<T>(
2793         &self,
2794         db: &dyn HirDatabase,
2795         krate: Crate,
2796         traits_in_scope: &FxHashSet<TraitId>,
2797         name: Option<&Name>,
2798         mut callback: impl FnMut(Type, Function) -> Option<T>,
2799     ) -> Option<T> {
2800         let _p = profile::span("iterate_method_candidates");
2801         let mut slot = None;
2802
2803         self.iterate_method_candidates_dyn(
2804             db,
2805             krate,
2806             traits_in_scope,
2807             name,
2808             &mut |ty, assoc_item_id| {
2809                 if let AssocItemId::FunctionId(func) = assoc_item_id {
2810                     if let Some(res) = callback(self.derived(ty.clone()), func.into()) {
2811                         slot = Some(res);
2812                         return ControlFlow::Break(());
2813                     }
2814                 }
2815                 ControlFlow::Continue(())
2816             },
2817         );
2818         slot
2819     }
2820
2821     fn iterate_method_candidates_dyn(
2822         &self,
2823         db: &dyn HirDatabase,
2824         krate: Crate,
2825         traits_in_scope: &FxHashSet<TraitId>,
2826         name: Option<&Name>,
2827         callback: &mut dyn FnMut(&Ty, AssocItemId) -> ControlFlow<()>,
2828     ) {
2829         // There should be no inference vars in types passed here
2830         let canonical = hir_ty::replace_errors_with_variables(&self.ty);
2831
2832         let env = self.env.clone();
2833         let krate = krate.id;
2834
2835         method_resolution::iterate_method_candidates_dyn(
2836             &canonical,
2837             db,
2838             env,
2839             krate,
2840             traits_in_scope,
2841             None,
2842             name,
2843             method_resolution::LookupMode::MethodCall,
2844             &mut |ty, id| callback(&ty.value, id),
2845         );
2846     }
2847
2848     pub fn iterate_path_candidates<T>(
2849         &self,
2850         db: &dyn HirDatabase,
2851         krate: Crate,
2852         traits_in_scope: &FxHashSet<TraitId>,
2853         name: Option<&Name>,
2854         mut callback: impl FnMut(Type, AssocItem) -> Option<T>,
2855     ) -> Option<T> {
2856         let _p = profile::span("iterate_path_candidates");
2857         let mut slot = None;
2858         self.iterate_path_candidates_dyn(
2859             db,
2860             krate,
2861             traits_in_scope,
2862             name,
2863             &mut |ty, assoc_item_id| {
2864                 if let Some(res) = callback(self.derived(ty.clone()), assoc_item_id.into()) {
2865                     slot = Some(res);
2866                     return ControlFlow::Break(());
2867                 }
2868                 ControlFlow::Continue(())
2869             },
2870         );
2871         slot
2872     }
2873
2874     fn iterate_path_candidates_dyn(
2875         &self,
2876         db: &dyn HirDatabase,
2877         krate: Crate,
2878         traits_in_scope: &FxHashSet<TraitId>,
2879         name: Option<&Name>,
2880         callback: &mut dyn FnMut(&Ty, AssocItemId) -> ControlFlow<()>,
2881     ) {
2882         let canonical = hir_ty::replace_errors_with_variables(&self.ty);
2883
2884         let env = self.env.clone();
2885         let krate = krate.id;
2886
2887         method_resolution::iterate_method_candidates_dyn(
2888             &canonical,
2889             db,
2890             env,
2891             krate,
2892             traits_in_scope,
2893             None,
2894             name,
2895             method_resolution::LookupMode::Path,
2896             &mut |ty, id| callback(&ty.value, id),
2897         );
2898     }
2899
2900     pub fn as_adt(&self) -> Option<Adt> {
2901         let (adt, _subst) = self.ty.as_adt()?;
2902         Some(adt.into())
2903     }
2904
2905     pub fn as_builtin(&self) -> Option<BuiltinType> {
2906         self.ty.as_builtin().map(|inner| BuiltinType { inner })
2907     }
2908
2909     pub fn as_dyn_trait(&self) -> Option<Trait> {
2910         self.ty.dyn_trait().map(Into::into)
2911     }
2912
2913     /// If a type can be represented as `dyn Trait`, returns all traits accessible via this type,
2914     /// or an empty iterator otherwise.
2915     pub fn applicable_inherent_traits<'a>(
2916         &'a self,
2917         db: &'a dyn HirDatabase,
2918     ) -> impl Iterator<Item = Trait> + 'a {
2919         let _p = profile::span("applicable_inherent_traits");
2920         self.autoderef_(db)
2921             .filter_map(|ty| ty.dyn_trait())
2922             .flat_map(move |dyn_trait_id| hir_ty::all_super_traits(db.upcast(), dyn_trait_id))
2923             .map(Trait::from)
2924     }
2925
2926     pub fn env_traits<'a>(&'a self, db: &'a dyn HirDatabase) -> impl Iterator<Item = Trait> + 'a {
2927         let _p = profile::span("env_traits");
2928         self.autoderef_(db)
2929             .filter(|ty| matches!(ty.kind(Interner), TyKind::Placeholder(_)))
2930             .flat_map(|ty| {
2931                 self.env
2932                     .traits_in_scope_from_clauses(ty)
2933                     .flat_map(|t| hir_ty::all_super_traits(db.upcast(), t))
2934             })
2935             .map(Trait::from)
2936     }
2937
2938     pub fn as_impl_traits(&self, db: &dyn HirDatabase) -> Option<impl Iterator<Item = Trait>> {
2939         self.ty.impl_trait_bounds(db).map(|it| {
2940             it.into_iter().filter_map(|pred| match pred.skip_binders() {
2941                 hir_ty::WhereClause::Implemented(trait_ref) => {
2942                     Some(Trait::from(trait_ref.hir_trait_id()))
2943                 }
2944                 _ => None,
2945             })
2946         })
2947     }
2948
2949     pub fn as_associated_type_parent_trait(&self, db: &dyn HirDatabase) -> Option<Trait> {
2950         self.ty.associated_type_parent_trait(db).map(Into::into)
2951     }
2952
2953     fn derived(&self, ty: Ty) -> Type {
2954         Type { krate: self.krate, env: self.env.clone(), ty }
2955     }
2956
2957     pub fn walk(&self, db: &dyn HirDatabase, mut cb: impl FnMut(Type)) {
2958         // TypeWalk::walk for a Ty at first visits parameters and only after that the Ty itself.
2959         // We need a different order here.
2960
2961         fn walk_substs(
2962             db: &dyn HirDatabase,
2963             type_: &Type,
2964             substs: &Substitution,
2965             cb: &mut impl FnMut(Type),
2966         ) {
2967             for ty in substs.iter(Interner).filter_map(|a| a.ty(Interner)) {
2968                 walk_type(db, &type_.derived(ty.clone()), cb);
2969             }
2970         }
2971
2972         fn walk_bounds(
2973             db: &dyn HirDatabase,
2974             type_: &Type,
2975             bounds: &[QuantifiedWhereClause],
2976             cb: &mut impl FnMut(Type),
2977         ) {
2978             for pred in bounds {
2979                 if let WhereClause::Implemented(trait_ref) = pred.skip_binders() {
2980                     cb(type_.clone());
2981                     // skip the self type. it's likely the type we just got the bounds from
2982                     for ty in
2983                         trait_ref.substitution.iter(Interner).skip(1).filter_map(|a| a.ty(Interner))
2984                     {
2985                         walk_type(db, &type_.derived(ty.clone()), cb);
2986                     }
2987                 }
2988             }
2989         }
2990
2991         fn walk_type(db: &dyn HirDatabase, type_: &Type, cb: &mut impl FnMut(Type)) {
2992             let ty = type_.ty.strip_references();
2993             match ty.kind(Interner) {
2994                 TyKind::Adt(_, substs) => {
2995                     cb(type_.derived(ty.clone()));
2996                     walk_substs(db, type_, substs, cb);
2997                 }
2998                 TyKind::AssociatedType(_, substs) => {
2999                     if ty.associated_type_parent_trait(db).is_some() {
3000                         cb(type_.derived(ty.clone()));
3001                     }
3002                     walk_substs(db, type_, substs, cb);
3003                 }
3004                 TyKind::OpaqueType(_, subst) => {
3005                     if let Some(bounds) = ty.impl_trait_bounds(db) {
3006                         walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
3007                     }
3008
3009                     walk_substs(db, type_, subst, cb);
3010                 }
3011                 TyKind::Alias(AliasTy::Opaque(opaque_ty)) => {
3012                     if let Some(bounds) = ty.impl_trait_bounds(db) {
3013                         walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
3014                     }
3015
3016                     walk_substs(db, type_, &opaque_ty.substitution, cb);
3017                 }
3018                 TyKind::Placeholder(_) => {
3019                     if let Some(bounds) = ty.impl_trait_bounds(db) {
3020                         walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
3021                     }
3022                 }
3023                 TyKind::Dyn(bounds) => {
3024                     walk_bounds(
3025                         db,
3026                         &type_.derived(ty.clone()),
3027                         bounds.bounds.skip_binders().interned(),
3028                         cb,
3029                     );
3030                 }
3031
3032                 TyKind::Ref(_, _, ty)
3033                 | TyKind::Raw(_, ty)
3034                 | TyKind::Array(ty, _)
3035                 | TyKind::Slice(ty) => {
3036                     walk_type(db, &type_.derived(ty.clone()), cb);
3037                 }
3038
3039                 TyKind::FnDef(_, substs)
3040                 | TyKind::Tuple(_, substs)
3041                 | TyKind::Closure(.., substs) => {
3042                     walk_substs(db, type_, substs, cb);
3043                 }
3044                 TyKind::Function(hir_ty::FnPointer { substitution, .. }) => {
3045                     walk_substs(db, type_, &substitution.0, cb);
3046                 }
3047
3048                 _ => {}
3049             }
3050         }
3051
3052         walk_type(db, self, &mut cb);
3053     }
3054
3055     pub fn could_unify_with(&self, db: &dyn HirDatabase, other: &Type) -> bool {
3056         let tys = hir_ty::replace_errors_with_variables(&(self.ty.clone(), other.ty.clone()));
3057         could_unify(db, self.env.clone(), &tys)
3058     }
3059 }
3060
3061 // FIXME: closures
3062 #[derive(Debug)]
3063 pub struct Callable {
3064     ty: Type,
3065     sig: CallableSig,
3066     def: Option<CallableDefId>,
3067     pub(crate) is_bound_method: bool,
3068 }
3069
3070 pub enum CallableKind {
3071     Function(Function),
3072     TupleStruct(Struct),
3073     TupleEnumVariant(Variant),
3074     Closure,
3075 }
3076
3077 impl Callable {
3078     pub fn kind(&self) -> CallableKind {
3079         match self.def {
3080             Some(CallableDefId::FunctionId(it)) => CallableKind::Function(it.into()),
3081             Some(CallableDefId::StructId(it)) => CallableKind::TupleStruct(it.into()),
3082             Some(CallableDefId::EnumVariantId(it)) => CallableKind::TupleEnumVariant(it.into()),
3083             None => CallableKind::Closure,
3084         }
3085     }
3086     pub fn receiver_param(&self, db: &dyn HirDatabase) -> Option<ast::SelfParam> {
3087         let func = match self.def {
3088             Some(CallableDefId::FunctionId(it)) if self.is_bound_method => it,
3089             _ => return None,
3090         };
3091         let src = func.lookup(db.upcast()).source(db.upcast());
3092         let param_list = src.value.param_list()?;
3093         param_list.self_param()
3094     }
3095     pub fn n_params(&self) -> usize {
3096         self.sig.params().len() - if self.is_bound_method { 1 } else { 0 }
3097     }
3098     pub fn params(
3099         &self,
3100         db: &dyn HirDatabase,
3101     ) -> Vec<(Option<Either<ast::SelfParam, ast::Pat>>, Type)> {
3102         let types = self
3103             .sig
3104             .params()
3105             .iter()
3106             .skip(if self.is_bound_method { 1 } else { 0 })
3107             .map(|ty| self.ty.derived(ty.clone()));
3108         let patterns = match self.def {
3109             Some(CallableDefId::FunctionId(func)) => {
3110                 let src = func.lookup(db.upcast()).source(db.upcast());
3111                 src.value.param_list().map(|param_list| {
3112                     param_list
3113                         .self_param()
3114                         .map(|it| Some(Either::Left(it)))
3115                         .filter(|_| !self.is_bound_method)
3116                         .into_iter()
3117                         .chain(param_list.params().map(|it| it.pat().map(Either::Right)))
3118                 })
3119             }
3120             _ => None,
3121         };
3122         patterns.into_iter().flatten().chain(iter::repeat(None)).zip(types).collect()
3123     }
3124     pub fn return_type(&self) -> Type {
3125         self.ty.derived(self.sig.ret().clone())
3126     }
3127 }
3128
3129 /// For IDE only
3130 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
3131 pub enum ScopeDef {
3132     ModuleDef(ModuleDef),
3133     MacroDef(MacroDef),
3134     GenericParam(GenericParam),
3135     ImplSelfType(Impl),
3136     AdtSelfType(Adt),
3137     Local(Local),
3138     Label(Label),
3139     Unknown,
3140 }
3141
3142 impl ScopeDef {
3143     pub fn all_items(def: PerNs) -> ArrayVec<Self, 3> {
3144         let mut items = ArrayVec::new();
3145
3146         match (def.take_types(), def.take_values()) {
3147             (Some(m1), None) => items.push(ScopeDef::ModuleDef(m1.into())),
3148             (None, Some(m2)) => items.push(ScopeDef::ModuleDef(m2.into())),
3149             (Some(m1), Some(m2)) => {
3150                 // Some items, like unit structs and enum variants, are
3151                 // returned as both a type and a value. Here we want
3152                 // to de-duplicate them.
3153                 if m1 != m2 {
3154                     items.push(ScopeDef::ModuleDef(m1.into()));
3155                     items.push(ScopeDef::ModuleDef(m2.into()));
3156                 } else {
3157                     items.push(ScopeDef::ModuleDef(m1.into()));
3158                 }
3159             }
3160             (None, None) => {}
3161         };
3162
3163         if let Some(macro_def_id) = def.take_macros() {
3164             items.push(ScopeDef::MacroDef(macro_def_id.into()));
3165         }
3166
3167         if items.is_empty() {
3168             items.push(ScopeDef::Unknown);
3169         }
3170
3171         items
3172     }
3173
3174     pub fn attrs(&self, db: &dyn HirDatabase) -> Option<AttrsWithOwner> {
3175         match self {
3176             ScopeDef::ModuleDef(it) => it.attrs(db),
3177             ScopeDef::MacroDef(it) => Some(it.attrs(db)),
3178             ScopeDef::GenericParam(it) => Some(it.attrs(db)),
3179             ScopeDef::ImplSelfType(_)
3180             | ScopeDef::AdtSelfType(_)
3181             | ScopeDef::Local(_)
3182             | ScopeDef::Label(_)
3183             | ScopeDef::Unknown => None,
3184         }
3185     }
3186
3187     pub fn krate(&self, db: &dyn HirDatabase) -> Option<Crate> {
3188         match self {
3189             ScopeDef::ModuleDef(it) => it.module(db).map(|m| m.krate()),
3190             ScopeDef::MacroDef(it) => it.module(db).map(|m| m.krate()),
3191             ScopeDef::GenericParam(it) => Some(it.module(db).krate()),
3192             ScopeDef::ImplSelfType(_) => None,
3193             ScopeDef::AdtSelfType(it) => Some(it.module(db).krate()),
3194             ScopeDef::Local(it) => Some(it.module(db).krate()),
3195             ScopeDef::Label(it) => Some(it.module(db).krate()),
3196             ScopeDef::Unknown => None,
3197         }
3198     }
3199 }
3200
3201 impl From<ItemInNs> for ScopeDef {
3202     fn from(item: ItemInNs) -> Self {
3203         match item {
3204             ItemInNs::Types(id) => ScopeDef::ModuleDef(id),
3205             ItemInNs::Values(id) => ScopeDef::ModuleDef(id),
3206             ItemInNs::Macros(id) => ScopeDef::MacroDef(id),
3207         }
3208     }
3209 }
3210
3211 pub trait HasVisibility {
3212     fn visibility(&self, db: &dyn HirDatabase) -> Visibility;
3213     fn is_visible_from(&self, db: &dyn HirDatabase, module: Module) -> bool {
3214         let vis = self.visibility(db);
3215         vis.is_visible_from(db.upcast(), module.id)
3216     }
3217 }
3218
3219 /// Trait for obtaining the defining crate of an item.
3220 pub trait HasCrate {
3221     fn krate(&self, db: &dyn HirDatabase) -> Crate;
3222 }
3223
3224 impl<T: hir_def::HasModule> HasCrate for T {
3225     fn krate(&self, db: &dyn HirDatabase) -> Crate {
3226         self.module(db.upcast()).krate().into()
3227     }
3228 }
3229
3230 impl HasCrate for AssocItem {
3231     fn krate(&self, db: &dyn HirDatabase) -> Crate {
3232         self.module(db).krate()
3233     }
3234 }
3235
3236 impl HasCrate for Field {
3237     fn krate(&self, db: &dyn HirDatabase) -> Crate {
3238         self.parent_def(db).module(db).krate()
3239     }
3240 }
3241
3242 impl HasCrate for Function {
3243     fn krate(&self, db: &dyn HirDatabase) -> Crate {
3244         self.module(db).krate()
3245     }
3246 }
3247
3248 impl HasCrate for Const {
3249     fn krate(&self, db: &dyn HirDatabase) -> Crate {
3250         self.module(db).krate()
3251     }
3252 }
3253
3254 impl HasCrate for TypeAlias {
3255     fn krate(&self, db: &dyn HirDatabase) -> Crate {
3256         self.module(db).krate()
3257     }
3258 }
3259
3260 impl HasCrate for Type {
3261     fn krate(&self, _db: &dyn HirDatabase) -> Crate {
3262         self.krate.into()
3263     }
3264 }