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