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