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