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