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