]> git.lizzy.rs Git - rust.git/blob - crates/hir/src/semantics.rs
Add ConstParams to the HIR
[rust.git] / crates / hir / src / semantics.rs
1 //! See `Semantics`.
2
3 mod source_to_def;
4
5 use std::{cell::RefCell, fmt, iter::successors};
6
7 use base_db::{FileId, FileRange};
8 use hir_def::{
9     resolver::{self, HasResolver, Resolver, TypeNs},
10     AsMacroCall, FunctionId, TraitId, VariantId,
11 };
12 use hir_expand::{hygiene::Hygiene, name::AsName, ExpansionInfo};
13 use hir_ty::associated_type_shorthand_candidates;
14 use itertools::Itertools;
15 use rustc_hash::{FxHashMap, FxHashSet};
16 use syntax::{
17     algo::find_node_at_offset,
18     ast::{self, GenericParamsOwner, LoopBodyOwner},
19     match_ast, AstNode, SyntaxNode, SyntaxToken, TextSize,
20 };
21
22 use crate::{
23     code_model::Access,
24     db::HirDatabase,
25     diagnostics::Diagnostic,
26     semantics::source_to_def::{ChildContainer, SourceToDefCache, SourceToDefCtx},
27     source_analyzer::{resolve_hir_path, SourceAnalyzer},
28     AssocItem, Callable, ConstParam, Crate, Field, Function, HirFileId, Impl, InFile, Label,
29     LifetimeParam, Local, MacroDef, Module, ModuleDef, Name, Path, ScopeDef, Trait, Type,
30     TypeAlias, TypeParam, VariantDef,
31 };
32
33 #[derive(Debug, Clone, PartialEq, Eq)]
34 pub enum PathResolution {
35     /// An item
36     Def(ModuleDef),
37     /// A local binding (only value namespace)
38     Local(Local),
39     /// A generic parameter
40     TypeParam(TypeParam),
41     ConstParam(ConstParam),
42     SelfType(Impl),
43     Macro(MacroDef),
44     AssocItem(AssocItem),
45 }
46
47 impl PathResolution {
48     fn in_type_ns(&self) -> Option<TypeNs> {
49         match self {
50             PathResolution::Def(ModuleDef::Adt(adt)) => Some(TypeNs::AdtId((*adt).into())),
51             PathResolution::Def(ModuleDef::BuiltinType(builtin)) => {
52                 Some(TypeNs::BuiltinType(*builtin))
53             }
54             PathResolution::Def(ModuleDef::Const(_))
55             | PathResolution::Def(ModuleDef::Variant(_))
56             | PathResolution::Def(ModuleDef::Function(_))
57             | PathResolution::Def(ModuleDef::Module(_))
58             | PathResolution::Def(ModuleDef::Static(_))
59             | PathResolution::Def(ModuleDef::Trait(_)) => None,
60             PathResolution::Def(ModuleDef::TypeAlias(alias)) => {
61                 Some(TypeNs::TypeAliasId((*alias).into()))
62             }
63             PathResolution::Local(_) | PathResolution::Macro(_) | PathResolution::ConstParam(_) => {
64                 None
65             }
66             PathResolution::TypeParam(param) => Some(TypeNs::GenericParam((*param).into())),
67             PathResolution::SelfType(impl_def) => Some(TypeNs::SelfType((*impl_def).into())),
68             PathResolution::AssocItem(AssocItem::Const(_))
69             | PathResolution::AssocItem(AssocItem::Function(_)) => None,
70             PathResolution::AssocItem(AssocItem::TypeAlias(alias)) => {
71                 Some(TypeNs::TypeAliasId((*alias).into()))
72             }
73         }
74     }
75
76     /// Returns an iterator over associated types that may be specified after this path (using
77     /// `Ty::Assoc` syntax).
78     pub fn assoc_type_shorthand_candidates<R>(
79         &self,
80         db: &dyn HirDatabase,
81         mut cb: impl FnMut(TypeAlias) -> Option<R>,
82     ) -> Option<R> {
83         associated_type_shorthand_candidates(db, self.in_type_ns()?, |_, _, id| cb(id.into()))
84     }
85 }
86
87 /// Primary API to get semantic information, like types, from syntax trees.
88 pub struct Semantics<'db, DB> {
89     pub db: &'db DB,
90     imp: SemanticsImpl<'db>,
91 }
92
93 pub struct SemanticsImpl<'db> {
94     pub db: &'db dyn HirDatabase,
95     s2d_cache: RefCell<SourceToDefCache>,
96     expansion_info_cache: RefCell<FxHashMap<HirFileId, Option<ExpansionInfo>>>,
97     cache: RefCell<FxHashMap<SyntaxNode, HirFileId>>,
98 }
99
100 impl<DB> fmt::Debug for Semantics<'_, DB> {
101     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
102         write!(f, "Semantics {{ ... }}")
103     }
104 }
105
106 impl<'db, DB: HirDatabase> Semantics<'db, DB> {
107     pub fn new(db: &DB) -> Semantics<DB> {
108         let impl_ = SemanticsImpl::new(db);
109         Semantics { db, imp: impl_ }
110     }
111
112     pub fn parse(&self, file_id: FileId) -> ast::SourceFile {
113         self.imp.parse(file_id)
114     }
115
116     pub fn expand(&self, macro_call: &ast::MacroCall) -> Option<SyntaxNode> {
117         self.imp.expand(macro_call)
118     }
119     pub fn speculative_expand(
120         &self,
121         actual_macro_call: &ast::MacroCall,
122         hypothetical_args: &ast::TokenTree,
123         token_to_map: SyntaxToken,
124     ) -> Option<(SyntaxNode, SyntaxToken)> {
125         self.imp.speculative_expand(actual_macro_call, hypothetical_args, token_to_map)
126     }
127
128     pub fn descend_into_macros(&self, token: SyntaxToken) -> SyntaxToken {
129         self.imp.descend_into_macros(token)
130     }
131
132     pub fn descend_node_at_offset<N: ast::AstNode>(
133         &self,
134         node: &SyntaxNode,
135         offset: TextSize,
136     ) -> Option<N> {
137         self.imp.descend_node_at_offset(node, offset).find_map(N::cast)
138     }
139
140     pub fn original_range(&self, node: &SyntaxNode) -> FileRange {
141         self.imp.original_range(node)
142     }
143
144     pub fn diagnostics_display_range(&self, diagnostics: &dyn Diagnostic) -> FileRange {
145         self.imp.diagnostics_display_range(diagnostics)
146     }
147
148     pub fn ancestors_with_macros(&self, node: SyntaxNode) -> impl Iterator<Item = SyntaxNode> + '_ {
149         self.imp.ancestors_with_macros(node)
150     }
151
152     pub fn ancestors_at_offset_with_macros(
153         &self,
154         node: &SyntaxNode,
155         offset: TextSize,
156     ) -> impl Iterator<Item = SyntaxNode> + '_ {
157         self.imp.ancestors_at_offset_with_macros(node, offset)
158     }
159
160     /// Find a AstNode by offset inside SyntaxNode, if it is inside *Macrofile*,
161     /// search up until it is of the target AstNode type
162     pub fn find_node_at_offset_with_macros<N: AstNode>(
163         &self,
164         node: &SyntaxNode,
165         offset: TextSize,
166     ) -> Option<N> {
167         self.imp.ancestors_at_offset_with_macros(node, offset).find_map(N::cast)
168     }
169
170     /// Find a AstNode by offset inside SyntaxNode, if it is inside *MacroCall*,
171     /// descend it and find again
172     pub fn find_node_at_offset_with_descend<N: AstNode>(
173         &self,
174         node: &SyntaxNode,
175         offset: TextSize,
176     ) -> Option<N> {
177         if let Some(it) = find_node_at_offset(&node, offset) {
178             return Some(it);
179         }
180
181         self.imp.descend_node_at_offset(node, offset).find_map(N::cast)
182     }
183
184     pub fn resolve_lifetime_param(&self, lifetime: &ast::Lifetime) -> Option<LifetimeParam> {
185         self.imp.resolve_lifetime_param(lifetime)
186     }
187
188     pub fn resolve_label(&self, lifetime: &ast::Lifetime) -> Option<Label> {
189         self.imp.resolve_label(lifetime)
190     }
191
192     pub fn type_of_expr(&self, expr: &ast::Expr) -> Option<Type> {
193         self.imp.type_of_expr(expr)
194     }
195
196     pub fn type_of_pat(&self, pat: &ast::Pat) -> Option<Type> {
197         self.imp.type_of_pat(pat)
198     }
199
200     pub fn type_of_self(&self, param: &ast::SelfParam) -> Option<Type> {
201         self.imp.type_of_self(param)
202     }
203
204     pub fn resolve_method_call(&self, call: &ast::MethodCallExpr) -> Option<Function> {
205         self.imp.resolve_method_call(call).map(Function::from)
206     }
207
208     pub fn resolve_method_call_as_callable(&self, call: &ast::MethodCallExpr) -> Option<Callable> {
209         self.imp.resolve_method_call_as_callable(call)
210     }
211
212     pub fn resolve_field(&self, field: &ast::FieldExpr) -> Option<Field> {
213         self.imp.resolve_field(field)
214     }
215
216     pub fn resolve_record_field(
217         &self,
218         field: &ast::RecordExprField,
219     ) -> Option<(Field, Option<Local>)> {
220         self.imp.resolve_record_field(field)
221     }
222
223     pub fn resolve_record_pat_field(&self, field: &ast::RecordPatField) -> Option<Field> {
224         self.imp.resolve_record_pat_field(field)
225     }
226
227     pub fn resolve_macro_call(&self, macro_call: &ast::MacroCall) -> Option<MacroDef> {
228         self.imp.resolve_macro_call(macro_call)
229     }
230
231     pub fn resolve_path(&self, path: &ast::Path) -> Option<PathResolution> {
232         self.imp.resolve_path(path)
233     }
234
235     pub fn resolve_extern_crate(&self, extern_crate: &ast::ExternCrate) -> Option<Crate> {
236         self.imp.resolve_extern_crate(extern_crate)
237     }
238
239     pub fn resolve_variant(&self, record_lit: ast::RecordExpr) -> Option<VariantDef> {
240         self.imp.resolve_variant(record_lit).map(VariantDef::from)
241     }
242
243     pub fn resolve_bind_pat_to_const(&self, pat: &ast::IdentPat) -> Option<ModuleDef> {
244         self.imp.resolve_bind_pat_to_const(pat)
245     }
246
247     // FIXME: use this instead?
248     // pub fn resolve_name_ref(&self, name_ref: &ast::NameRef) -> Option<???>;
249
250     pub fn record_literal_missing_fields(&self, literal: &ast::RecordExpr) -> Vec<(Field, Type)> {
251         self.imp.record_literal_missing_fields(literal)
252     }
253
254     pub fn record_pattern_missing_fields(&self, pattern: &ast::RecordPat) -> Vec<(Field, Type)> {
255         self.imp.record_pattern_missing_fields(pattern)
256     }
257
258     pub fn to_def<T: ToDef>(&self, src: &T) -> Option<T::Def> {
259         let src = self.imp.find_file(src.syntax().clone()).with_value(src).cloned();
260         T::to_def(&self.imp, src)
261     }
262
263     pub fn to_module_def(&self, file: FileId) -> Option<Module> {
264         self.imp.to_module_def(file)
265     }
266
267     pub fn scope(&self, node: &SyntaxNode) -> SemanticsScope<'db> {
268         self.imp.scope(node)
269     }
270
271     pub fn scope_at_offset(&self, node: &SyntaxNode, offset: TextSize) -> SemanticsScope<'db> {
272         self.imp.scope_at_offset(node, offset)
273     }
274
275     pub fn scope_for_def(&self, def: Trait) -> SemanticsScope<'db> {
276         self.imp.scope_for_def(def)
277     }
278
279     pub fn assert_contains_node(&self, node: &SyntaxNode) {
280         self.imp.assert_contains_node(node)
281     }
282
283     pub fn is_unsafe_method_call(&self, method_call_expr: &ast::MethodCallExpr) -> bool {
284         self.imp.is_unsafe_method_call(method_call_expr)
285     }
286
287     pub fn is_unsafe_ref_expr(&self, ref_expr: &ast::RefExpr) -> bool {
288         self.imp.is_unsafe_ref_expr(ref_expr)
289     }
290
291     pub fn is_unsafe_ident_pat(&self, ident_pat: &ast::IdentPat) -> bool {
292         self.imp.is_unsafe_ident_pat(ident_pat)
293     }
294 }
295
296 impl<'db> SemanticsImpl<'db> {
297     fn new(db: &'db dyn HirDatabase) -> Self {
298         SemanticsImpl {
299             db,
300             s2d_cache: Default::default(),
301             cache: Default::default(),
302             expansion_info_cache: Default::default(),
303         }
304     }
305
306     fn parse(&self, file_id: FileId) -> ast::SourceFile {
307         let tree = self.db.parse(file_id).tree();
308         self.cache(tree.syntax().clone(), file_id.into());
309         tree
310     }
311
312     fn expand(&self, macro_call: &ast::MacroCall) -> Option<SyntaxNode> {
313         let sa = self.analyze(macro_call.syntax());
314         let file_id = sa.expand(self.db, InFile::new(sa.file_id, macro_call))?;
315         let node = self.db.parse_or_expand(file_id)?;
316         self.cache(node.clone(), file_id);
317         Some(node)
318     }
319
320     fn speculative_expand(
321         &self,
322         actual_macro_call: &ast::MacroCall,
323         hypothetical_args: &ast::TokenTree,
324         token_to_map: SyntaxToken,
325     ) -> Option<(SyntaxNode, SyntaxToken)> {
326         let sa = self.analyze(actual_macro_call.syntax());
327         let macro_call = InFile::new(sa.file_id, actual_macro_call);
328         let krate = sa.resolver.krate()?;
329         let macro_call_id = macro_call.as_call_id(self.db.upcast(), krate, |path| {
330             sa.resolver.resolve_path_as_macro(self.db.upcast(), &path)
331         })?;
332         hir_expand::db::expand_hypothetical(
333             self.db.upcast(),
334             macro_call_id,
335             hypothetical_args,
336             token_to_map,
337         )
338     }
339
340     fn descend_into_macros(&self, token: SyntaxToken) -> SyntaxToken {
341         let _p = profile::span("descend_into_macros");
342         let parent = token.parent();
343         let sa = self.analyze(&parent);
344
345         let token = successors(Some(InFile::new(sa.file_id, token)), |token| {
346             self.db.check_canceled();
347             let macro_call = token.value.ancestors().find_map(ast::MacroCall::cast)?;
348             let tt = macro_call.token_tree()?;
349             if !tt.syntax().text_range().contains_range(token.value.text_range()) {
350                 return None;
351             }
352             let file_id = sa.expand(self.db, token.with_value(&macro_call))?;
353             let token = self
354                 .expansion_info_cache
355                 .borrow_mut()
356                 .entry(file_id)
357                 .or_insert_with(|| file_id.expansion_info(self.db.upcast()))
358                 .as_ref()?
359                 .map_token_down(token.as_ref())?;
360
361             self.cache(find_root(&token.value.parent()), token.file_id);
362
363             Some(token)
364         })
365         .last()
366         .unwrap();
367
368         token.value
369     }
370
371     fn descend_node_at_offset(
372         &self,
373         node: &SyntaxNode,
374         offset: TextSize,
375     ) -> impl Iterator<Item = SyntaxNode> + '_ {
376         // Handle macro token cases
377         node.token_at_offset(offset)
378             .map(|token| self.descend_into_macros(token))
379             .map(|it| self.ancestors_with_macros(it.parent()))
380             .flatten()
381     }
382
383     fn original_range(&self, node: &SyntaxNode) -> FileRange {
384         let node = self.find_file(node.clone());
385         node.as_ref().original_file_range(self.db.upcast())
386     }
387
388     fn diagnostics_display_range(&self, diagnostics: &dyn Diagnostic) -> FileRange {
389         let src = diagnostics.display_source();
390         let root = self.db.parse_or_expand(src.file_id).unwrap();
391         let node = src.value.to_node(&root);
392         self.cache(root, src.file_id);
393         src.with_value(&node).original_file_range(self.db.upcast())
394     }
395
396     fn ancestors_with_macros(&self, node: SyntaxNode) -> impl Iterator<Item = SyntaxNode> + '_ {
397         let node = self.find_file(node);
398         node.ancestors_with_macros(self.db.upcast()).map(|it| it.value)
399     }
400
401     fn ancestors_at_offset_with_macros(
402         &self,
403         node: &SyntaxNode,
404         offset: TextSize,
405     ) -> impl Iterator<Item = SyntaxNode> + '_ {
406         node.token_at_offset(offset)
407             .map(|token| self.ancestors_with_macros(token.parent()))
408             .kmerge_by(|node1, node2| node1.text_range().len() < node2.text_range().len())
409     }
410
411     fn resolve_lifetime_param(&self, lifetime: &ast::Lifetime) -> Option<LifetimeParam> {
412         let text = lifetime.text();
413         let lifetime_param = lifetime.syntax().ancestors().find_map(|syn| {
414             let gpl = match_ast! {
415                 match syn {
416                     ast::Fn(it) => it.generic_param_list()?,
417                     ast::TypeAlias(it) => it.generic_param_list()?,
418                     ast::Struct(it) => it.generic_param_list()?,
419                     ast::Enum(it) => it.generic_param_list()?,
420                     ast::Union(it) => it.generic_param_list()?,
421                     ast::Trait(it) => it.generic_param_list()?,
422                     ast::Impl(it) => it.generic_param_list()?,
423                     ast::WherePred(it) => it.generic_param_list()?,
424                     ast::ForType(it) => it.generic_param_list()?,
425                     _ => return None,
426                 }
427             };
428             gpl.lifetime_params()
429                 .find(|tp| tp.lifetime().as_ref().map(|lt| lt.text()) == Some(text))
430         })?;
431         let src = self.find_file(lifetime_param.syntax().clone()).with_value(lifetime_param);
432         ToDef::to_def(self, src)
433     }
434
435     fn resolve_label(&self, lifetime: &ast::Lifetime) -> Option<Label> {
436         let text = lifetime.text();
437         let label = lifetime.syntax().ancestors().find_map(|syn| {
438             let label = match_ast! {
439                 match syn {
440                     ast::ForExpr(it) => it.label(),
441                     ast::WhileExpr(it) => it.label(),
442                     ast::LoopExpr(it) => it.label(),
443                     ast::EffectExpr(it) => it.label(),
444                     _ => None,
445                 }
446             };
447             label.filter(|l| {
448                 l.lifetime()
449                     .and_then(|lt| lt.lifetime_ident_token())
450                     .map_or(false, |lt| lt.text() == text)
451             })
452         })?;
453         let src = self.find_file(label.syntax().clone()).with_value(label);
454         ToDef::to_def(self, src)
455     }
456
457     fn type_of_expr(&self, expr: &ast::Expr) -> Option<Type> {
458         self.analyze(expr.syntax()).type_of_expr(self.db, expr)
459     }
460
461     fn type_of_pat(&self, pat: &ast::Pat) -> Option<Type> {
462         self.analyze(pat.syntax()).type_of_pat(self.db, pat)
463     }
464
465     fn type_of_self(&self, param: &ast::SelfParam) -> Option<Type> {
466         self.analyze(param.syntax()).type_of_self(self.db, param)
467     }
468
469     fn resolve_method_call(&self, call: &ast::MethodCallExpr) -> Option<FunctionId> {
470         self.analyze(call.syntax()).resolve_method_call(self.db, call)
471     }
472
473     fn resolve_method_call_as_callable(&self, call: &ast::MethodCallExpr) -> Option<Callable> {
474         // FIXME: this erases Substs
475         let func = self.resolve_method_call(call)?;
476         let ty = self.db.value_ty(func.into());
477         let resolver = self.analyze(call.syntax()).resolver;
478         let ty = Type::new_with_resolver(self.db, &resolver, ty.value)?;
479         let mut res = ty.as_callable(self.db)?;
480         res.is_bound_method = true;
481         Some(res)
482     }
483
484     fn resolve_field(&self, field: &ast::FieldExpr) -> Option<Field> {
485         self.analyze(field.syntax()).resolve_field(self.db, field)
486     }
487
488     fn resolve_record_field(&self, field: &ast::RecordExprField) -> Option<(Field, Option<Local>)> {
489         self.analyze(field.syntax()).resolve_record_field(self.db, field)
490     }
491
492     fn resolve_record_pat_field(&self, field: &ast::RecordPatField) -> Option<Field> {
493         self.analyze(field.syntax()).resolve_record_pat_field(self.db, field)
494     }
495
496     fn resolve_macro_call(&self, macro_call: &ast::MacroCall) -> Option<MacroDef> {
497         let sa = self.analyze(macro_call.syntax());
498         let macro_call = self.find_file(macro_call.syntax().clone()).with_value(macro_call);
499         sa.resolve_macro_call(self.db, macro_call)
500     }
501
502     fn resolve_path(&self, path: &ast::Path) -> Option<PathResolution> {
503         self.analyze(path.syntax()).resolve_path(self.db, path)
504     }
505
506     fn resolve_extern_crate(&self, extern_crate: &ast::ExternCrate) -> Option<Crate> {
507         let krate = self.scope(extern_crate.syntax()).krate()?;
508         krate.dependencies(self.db).into_iter().find_map(|dep| {
509             if dep.name == extern_crate.name_ref()?.as_name() {
510                 Some(dep.krate)
511             } else {
512                 None
513             }
514         })
515     }
516
517     fn resolve_variant(&self, record_lit: ast::RecordExpr) -> Option<VariantId> {
518         self.analyze(record_lit.syntax()).resolve_variant(self.db, record_lit)
519     }
520
521     fn resolve_bind_pat_to_const(&self, pat: &ast::IdentPat) -> Option<ModuleDef> {
522         self.analyze(pat.syntax()).resolve_bind_pat_to_const(self.db, pat)
523     }
524
525     fn record_literal_missing_fields(&self, literal: &ast::RecordExpr) -> Vec<(Field, Type)> {
526         self.analyze(literal.syntax())
527             .record_literal_missing_fields(self.db, literal)
528             .unwrap_or_default()
529     }
530
531     fn record_pattern_missing_fields(&self, pattern: &ast::RecordPat) -> Vec<(Field, Type)> {
532         self.analyze(pattern.syntax())
533             .record_pattern_missing_fields(self.db, pattern)
534             .unwrap_or_default()
535     }
536
537     fn with_ctx<F: FnOnce(&mut SourceToDefCtx) -> T, T>(&self, f: F) -> T {
538         let mut cache = self.s2d_cache.borrow_mut();
539         let mut ctx = SourceToDefCtx { db: self.db, cache: &mut *cache };
540         f(&mut ctx)
541     }
542
543     fn to_module_def(&self, file: FileId) -> Option<Module> {
544         self.with_ctx(|ctx| ctx.file_to_def(file)).map(Module::from)
545     }
546
547     fn scope(&self, node: &SyntaxNode) -> SemanticsScope<'db> {
548         let sa = self.analyze(node);
549         SemanticsScope { db: self.db, file_id: sa.file_id, resolver: sa.resolver }
550     }
551
552     fn scope_at_offset(&self, node: &SyntaxNode, offset: TextSize) -> SemanticsScope<'db> {
553         let sa = self.analyze_with_offset(node, offset);
554         SemanticsScope { db: self.db, file_id: sa.file_id, resolver: sa.resolver }
555     }
556
557     fn scope_for_def(&self, def: Trait) -> SemanticsScope<'db> {
558         let file_id = self.db.lookup_intern_trait(def.id).id.file_id;
559         let resolver = def.id.resolver(self.db.upcast());
560         SemanticsScope { db: self.db, file_id, resolver }
561     }
562
563     fn analyze(&self, node: &SyntaxNode) -> SourceAnalyzer {
564         self.analyze_impl(node, None)
565     }
566     fn analyze_with_offset(&self, node: &SyntaxNode, offset: TextSize) -> SourceAnalyzer {
567         self.analyze_impl(node, Some(offset))
568     }
569     fn analyze_impl(&self, node: &SyntaxNode, offset: Option<TextSize>) -> SourceAnalyzer {
570         let _p = profile::span("Semantics::analyze_impl");
571         let node = self.find_file(node.clone());
572         let node = node.as_ref();
573
574         let container = match self.with_ctx(|ctx| ctx.find_container(node)) {
575             Some(it) => it,
576             None => return SourceAnalyzer::new_for_resolver(Resolver::default(), node),
577         };
578
579         let resolver = match container {
580             ChildContainer::DefWithBodyId(def) => {
581                 return SourceAnalyzer::new_for_body(self.db, def, node, offset)
582             }
583             ChildContainer::TraitId(it) => it.resolver(self.db.upcast()),
584             ChildContainer::ImplId(it) => it.resolver(self.db.upcast()),
585             ChildContainer::ModuleId(it) => it.resolver(self.db.upcast()),
586             ChildContainer::EnumId(it) => it.resolver(self.db.upcast()),
587             ChildContainer::VariantId(it) => it.resolver(self.db.upcast()),
588             ChildContainer::TypeAliasId(it) => it.resolver(self.db.upcast()),
589             ChildContainer::GenericDefId(it) => it.resolver(self.db.upcast()),
590         };
591         SourceAnalyzer::new_for_resolver(resolver, node)
592     }
593
594     fn cache(&self, root_node: SyntaxNode, file_id: HirFileId) {
595         assert!(root_node.parent().is_none());
596         let mut cache = self.cache.borrow_mut();
597         let prev = cache.insert(root_node, file_id);
598         assert!(prev == None || prev == Some(file_id))
599     }
600
601     fn assert_contains_node(&self, node: &SyntaxNode) {
602         self.find_file(node.clone());
603     }
604
605     fn lookup(&self, root_node: &SyntaxNode) -> Option<HirFileId> {
606         let cache = self.cache.borrow();
607         cache.get(root_node).copied()
608     }
609
610     fn find_file(&self, node: SyntaxNode) -> InFile<SyntaxNode> {
611         let root_node = find_root(&node);
612         let file_id = self.lookup(&root_node).unwrap_or_else(|| {
613             panic!(
614                 "\n\nFailed to lookup {:?} in this Semantics.\n\
615                  Make sure to use only query nodes, derived from this instance of Semantics.\n\
616                  root node:   {:?}\n\
617                  known nodes: {}\n\n",
618                 node,
619                 root_node,
620                 self.cache
621                     .borrow()
622                     .keys()
623                     .map(|it| format!("{:?}", it))
624                     .collect::<Vec<_>>()
625                     .join(", ")
626             )
627         });
628         InFile::new(file_id, node)
629     }
630
631     fn is_unsafe_method_call(&self, method_call_expr: &ast::MethodCallExpr) -> bool {
632         method_call_expr
633             .receiver()
634             .and_then(|expr| {
635                 let field_expr = match expr {
636                     ast::Expr::FieldExpr(field_expr) => field_expr,
637                     _ => return None,
638                 };
639                 let ty = self.type_of_expr(&field_expr.expr()?)?;
640                 if !ty.is_packed(self.db) {
641                     return None;
642                 }
643
644                 let func = self.resolve_method_call(&method_call_expr).map(Function::from)?;
645                 let res = match func.self_param(self.db)?.access(self.db) {
646                     Access::Shared | Access::Exclusive => true,
647                     Access::Owned => false,
648                 };
649                 Some(res)
650             })
651             .unwrap_or(false)
652     }
653
654     fn is_unsafe_ref_expr(&self, ref_expr: &ast::RefExpr) -> bool {
655         ref_expr
656             .expr()
657             .and_then(|expr| {
658                 let field_expr = match expr {
659                     ast::Expr::FieldExpr(field_expr) => field_expr,
660                     _ => return None,
661                 };
662                 let expr = field_expr.expr()?;
663                 self.type_of_expr(&expr)
664             })
665             // Binding a reference to a packed type is possibly unsafe.
666             .map(|ty| ty.is_packed(self.db))
667             .unwrap_or(false)
668
669         // FIXME This needs layout computation to be correct. It will highlight
670         // more than it should with the current implementation.
671     }
672
673     fn is_unsafe_ident_pat(&self, ident_pat: &ast::IdentPat) -> bool {
674         if !ident_pat.ref_token().is_some() {
675             return false;
676         }
677
678         ident_pat
679             .syntax()
680             .parent()
681             .and_then(|parent| {
682                 // `IdentPat` can live under `RecordPat` directly under `RecordPatField` or
683                 // `RecordPatFieldList`. `RecordPatField` also lives under `RecordPatFieldList`,
684                 // so this tries to lookup the `IdentPat` anywhere along that structure to the
685                 // `RecordPat` so we can get the containing type.
686                 let record_pat = ast::RecordPatField::cast(parent.clone())
687                     .and_then(|record_pat| record_pat.syntax().parent())
688                     .or_else(|| Some(parent.clone()))
689                     .and_then(|parent| {
690                         ast::RecordPatFieldList::cast(parent)?
691                             .syntax()
692                             .parent()
693                             .and_then(ast::RecordPat::cast)
694                     });
695
696                 // If this doesn't match a `RecordPat`, fallback to a `LetStmt` to see if
697                 // this is initialized from a `FieldExpr`.
698                 if let Some(record_pat) = record_pat {
699                     self.type_of_pat(&ast::Pat::RecordPat(record_pat))
700                 } else if let Some(let_stmt) = ast::LetStmt::cast(parent) {
701                     let field_expr = match let_stmt.initializer()? {
702                         ast::Expr::FieldExpr(field_expr) => field_expr,
703                         _ => return None,
704                     };
705
706                     self.type_of_expr(&field_expr.expr()?)
707                 } else {
708                     None
709                 }
710             })
711             // Binding a reference to a packed type is possibly unsafe.
712             .map(|ty| ty.is_packed(self.db))
713             .unwrap_or(false)
714     }
715 }
716
717 pub trait ToDef: AstNode + Clone {
718     type Def;
719
720     fn to_def(sema: &SemanticsImpl, src: InFile<Self>) -> Option<Self::Def>;
721 }
722
723 macro_rules! to_def_impls {
724     ($(($def:path, $ast:path, $meth:ident)),* ,) => {$(
725         impl ToDef for $ast {
726             type Def = $def;
727             fn to_def(sema: &SemanticsImpl, src: InFile<Self>) -> Option<Self::Def> {
728                 sema.with_ctx(|ctx| ctx.$meth(src)).map(<$def>::from)
729             }
730         }
731     )*}
732 }
733
734 to_def_impls![
735     (crate::Module, ast::Module, module_to_def),
736     (crate::Struct, ast::Struct, struct_to_def),
737     (crate::Enum, ast::Enum, enum_to_def),
738     (crate::Union, ast::Union, union_to_def),
739     (crate::Trait, ast::Trait, trait_to_def),
740     (crate::Impl, ast::Impl, impl_to_def),
741     (crate::TypeAlias, ast::TypeAlias, type_alias_to_def),
742     (crate::Const, ast::Const, const_to_def),
743     (crate::Static, ast::Static, static_to_def),
744     (crate::Function, ast::Fn, fn_to_def),
745     (crate::Field, ast::RecordField, record_field_to_def),
746     (crate::Field, ast::TupleField, tuple_field_to_def),
747     (crate::Variant, ast::Variant, enum_variant_to_def),
748     (crate::TypeParam, ast::TypeParam, type_param_to_def),
749     (crate::LifetimeParam, ast::LifetimeParam, lifetime_param_to_def),
750     (crate::ConstParam, ast::ConstParam, const_param_to_def),
751     (crate::MacroDef, ast::MacroRules, macro_rules_to_def),
752     (crate::Local, ast::IdentPat, bind_pat_to_def),
753     (crate::Label, ast::Label, label_to_def),
754 ];
755
756 fn find_root(node: &SyntaxNode) -> SyntaxNode {
757     node.ancestors().last().unwrap()
758 }
759
760 /// `SemanticScope` encapsulates the notion of a scope (the set of visible
761 /// names) at a particular program point.
762 ///
763 /// It is a bit tricky, as scopes do not really exist inside the compiler.
764 /// Rather, the compiler directly computes for each reference the definition it
765 /// refers to. It might transiently compute the explicit scope map while doing
766 /// so, but, generally, this is not something left after the analysis.
767 ///
768 /// However, we do very much need explicit scopes for IDE purposes --
769 /// completion, at its core, lists the contents of the current scope. The notion
770 /// of scope is also useful to answer questions like "what would be the meaning
771 /// of this piece of code if we inserted it into this position?".
772 ///
773 /// So `SemanticsScope` is constructed from a specific program point (a syntax
774 /// node or just a raw offset) and provides access to the set of visible names
775 /// on a somewhat best-effort basis.
776 ///
777 /// Note that if you are wondering "what does this specific existing name mean?",
778 /// you'd better use the `resolve_` family of methods.
779 #[derive(Debug)]
780 pub struct SemanticsScope<'a> {
781     pub db: &'a dyn HirDatabase,
782     file_id: HirFileId,
783     resolver: Resolver,
784 }
785
786 impl<'a> SemanticsScope<'a> {
787     pub fn module(&self) -> Option<Module> {
788         Some(Module { id: self.resolver.module()? })
789     }
790
791     pub fn krate(&self) -> Option<Crate> {
792         Some(Crate { id: self.resolver.krate()? })
793     }
794
795     /// Note: `FxHashSet<TraitId>` should be treated as an opaque type, passed into `Type
796     // FIXME: rename to visible_traits to not repeat scope?
797     pub fn traits_in_scope(&self) -> FxHashSet<TraitId> {
798         let resolver = &self.resolver;
799         resolver.traits_in_scope(self.db.upcast())
800     }
801
802     pub fn process_all_names(&self, f: &mut dyn FnMut(Name, ScopeDef)) {
803         let resolver = &self.resolver;
804
805         resolver.process_all_names(self.db.upcast(), &mut |name, def| {
806             let def = match def {
807                 resolver::ScopeDef::PerNs(it) => {
808                     let items = ScopeDef::all_items(it);
809                     for item in items {
810                         f(name.clone(), item);
811                     }
812                     return;
813                 }
814                 resolver::ScopeDef::ImplSelfType(it) => ScopeDef::ImplSelfType(it.into()),
815                 resolver::ScopeDef::AdtSelfType(it) => ScopeDef::AdtSelfType(it.into()),
816                 resolver::ScopeDef::GenericParam(id) => ScopeDef::GenericParam(TypeParam { id }),
817                 resolver::ScopeDef::Local(pat_id) => {
818                     let parent = resolver.body_owner().unwrap().into();
819                     ScopeDef::Local(Local { parent, pat_id })
820                 }
821             };
822             f(name, def)
823         })
824     }
825
826     /// Resolve a path as-if it was written at the given scope. This is
827     /// necessary a heuristic, as it doesn't take hygiene into account.
828     pub fn speculative_resolve(&self, path: &ast::Path) -> Option<PathResolution> {
829         let hygiene = Hygiene::new(self.db.upcast(), self.file_id);
830         let path = Path::from_src(path.clone(), &hygiene)?;
831         resolve_hir_path(self.db, &self.resolver, &path)
832     }
833 }