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