aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_hir/src/semantics.rs
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_hir/src/semantics.rs')
-rw-r--r--crates/ra_hir/src/semantics.rs841
1 files changed, 0 insertions, 841 deletions
diff --git a/crates/ra_hir/src/semantics.rs b/crates/ra_hir/src/semantics.rs
deleted file mode 100644
index 36b688ccb..000000000
--- a/crates/ra_hir/src/semantics.rs
+++ /dev/null
@@ -1,841 +0,0 @@
1//! See `Semantics`.
2
3mod source_to_def;
4
5use std::{cell::RefCell, fmt, iter::successors};
6
7use hir_def::{
8 resolver::{self, HasResolver, Resolver},
9 AsMacroCall, FunctionId, TraitId, VariantId,
10};
11use hir_expand::{hygiene::Hygiene, name::AsName, ExpansionInfo};
12use hir_ty::associated_type_shorthand_candidates;
13use itertools::Itertools;
14use ra_db::{FileId, FileRange};
15use ra_prof::profile;
16use ra_syntax::{
17 algo::{find_node_at_offset, skip_trivia_token},
18 ast, AstNode, Direction, SyntaxNode, SyntaxToken, TextRange, TextSize,
19};
20use rustc_hash::{FxHashMap, FxHashSet};
21
22use crate::{
23 db::HirDatabase,
24 diagnostics::Diagnostic,
25 semantics::source_to_def::{ChildContainer, SourceToDefCache, SourceToDefCtx},
26 source_analyzer::{resolve_hir_path, resolve_hir_path_qualifier, SourceAnalyzer},
27 AssocItem, Callable, Crate, Field, Function, HirFileId, ImplDef, InFile, Local, MacroDef,
28 Module, ModuleDef, Name, Origin, Path, ScopeDef, Trait, Type, TypeAlias, TypeParam, TypeRef,
29 VariantDef,
30};
31use resolver::TypeNs;
32
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub 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
46impl 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.
85pub struct Semantics<'db, DB> {
86 pub db: &'db DB,
87 imp: SemanticsImpl<'db>,
88}
89
90pub 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
97impl<DB> fmt::Debug for Semantics<'_, DB> {
98 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99 write!(f, "Semantics {{ ... }}")
100 }
101}
102
103impl<'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
117 pub fn expand_hypothetical(
118 &self,
119 actual_macro_call: &ast::MacroCall,
120 hypothetical_args: &ast::TokenTree,
121 token_to_map: SyntaxToken,
122 ) -> Option<(SyntaxNode, SyntaxToken)> {
123 self.imp.expand_hypothetical(actual_macro_call, hypothetical_args, token_to_map)
124 }
125
126 pub fn descend_into_macros(&self, token: SyntaxToken) -> SyntaxToken {
127 self.imp.descend_into_macros(token)
128 }
129
130 pub fn descend_node_at_offset<N: ast::AstNode>(
131 &self,
132 node: &SyntaxNode,
133 offset: TextSize,
134 ) -> Option<N> {
135 self.imp.descend_node_at_offset(node, offset).find_map(N::cast)
136 }
137
138 pub fn original_range(&self, node: &SyntaxNode) -> FileRange {
139 self.imp.original_range(node)
140 }
141
142 pub fn diagnostics_display_range(&self, diagnostics: &dyn Diagnostic) -> FileRange {
143 self.imp.diagnostics_display_range(diagnostics)
144 }
145
146 pub fn ancestors_with_macros(&self, node: SyntaxNode) -> impl Iterator<Item = SyntaxNode> + '_ {
147 self.imp.ancestors_with_macros(node)
148 }
149
150 pub fn ancestors_at_offset_with_macros(
151 &self,
152 node: &SyntaxNode,
153 offset: TextSize,
154 ) -> impl Iterator<Item = SyntaxNode> + '_ {
155 self.imp.ancestors_at_offset_with_macros(node, offset)
156 }
157
158 /// Find a AstNode by offset inside SyntaxNode, if it is inside *Macrofile*,
159 /// search up until it is of the target AstNode type
160 pub fn find_node_at_offset_with_macros<N: AstNode>(
161 &self,
162 node: &SyntaxNode,
163 offset: TextSize,
164 ) -> Option<N> {
165 self.imp.ancestors_at_offset_with_macros(node, offset).find_map(N::cast)
166 }
167
168 /// Find a AstNode by offset inside SyntaxNode, if it is inside *MacroCall*,
169 /// descend it and find again
170 pub fn find_node_at_offset_with_descend<N: AstNode>(
171 &self,
172 node: &SyntaxNode,
173 offset: TextSize,
174 ) -> Option<N> {
175 if let Some(it) = find_node_at_offset(&node, offset) {
176 return Some(it);
177 }
178
179 self.imp.descend_node_at_offset(node, offset).find_map(N::cast)
180 }
181
182 pub fn type_of_expr(&self, expr: &ast::Expr) -> Option<Type> {
183 self.imp.type_of_expr(expr)
184 }
185
186 pub fn type_of_pat(&self, pat: &ast::Pat) -> Option<Type> {
187 self.imp.type_of_pat(pat)
188 }
189
190 pub fn type_of_self(&self, param: &ast::SelfParam) -> Option<Type> {
191 self.imp.type_of_self(param)
192 }
193
194 pub fn resolve_method_call(&self, call: &ast::MethodCallExpr) -> Option<Function> {
195 self.imp.resolve_method_call(call).map(Function::from)
196 }
197
198 pub fn resolve_method_call_as_callable(&self, call: &ast::MethodCallExpr) -> Option<Callable> {
199 self.imp.resolve_method_call_as_callable(call)
200 }
201
202 pub fn resolve_field(&self, field: &ast::FieldExpr) -> Option<Field> {
203 self.imp.resolve_field(field)
204 }
205
206 pub fn resolve_record_field(
207 &self,
208 field: &ast::RecordExprField,
209 ) -> Option<(Field, Option<Local>)> {
210 self.imp.resolve_record_field(field)
211 }
212
213 pub fn resolve_record_field_pat(&self, field: &ast::RecordPatField) -> Option<Field> {
214 self.imp.resolve_record_field_pat(field)
215 }
216
217 pub fn resolve_macro_call(&self, macro_call: &ast::MacroCall) -> Option<MacroDef> {
218 self.imp.resolve_macro_call(macro_call)
219 }
220
221 pub fn resolve_path(&self, path: &ast::Path) -> Option<PathResolution> {
222 self.imp.resolve_path(path)
223 }
224
225 pub fn resolve_extern_crate(&self, extern_crate: &ast::ExternCrate) -> Option<Crate> {
226 self.imp.resolve_extern_crate(extern_crate)
227 }
228
229 pub fn resolve_variant(&self, record_lit: ast::RecordExpr) -> Option<VariantDef> {
230 self.imp.resolve_variant(record_lit).map(VariantDef::from)
231 }
232
233 pub fn lower_path(&self, path: &ast::Path) -> Option<Path> {
234 self.imp.lower_path(path)
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
290impl<'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 macro_call = self.find_file(macro_call.syntax().clone()).with_value(macro_call);
308 let sa = self.analyze2(macro_call.map(|it| it.syntax()), None);
309 let file_id = sa.expand(self.db, macro_call)?;
310 let node = self.db.parse_or_expand(file_id)?;
311 self.cache(node.clone(), file_id);
312 Some(node)
313 }
314
315 fn expand_hypothetical(
316 &self,
317 actual_macro_call: &ast::MacroCall,
318 hypothetical_args: &ast::TokenTree,
319 token_to_map: SyntaxToken,
320 ) -> Option<(SyntaxNode, SyntaxToken)> {
321 let macro_call =
322 self.find_file(actual_macro_call.syntax().clone()).with_value(actual_macro_call);
323 let sa = self.analyze2(macro_call.map(|it| it.syntax()), None);
324 let krate = sa.resolver.krate()?;
325 let macro_call_id = macro_call.as_call_id(self.db.upcast(), krate, |path| {
326 sa.resolver.resolve_path_as_macro(self.db.upcast(), &path)
327 })?;
328 hir_expand::db::expand_hypothetical(
329 self.db.upcast(),
330 macro_call_id,
331 hypothetical_args,
332 token_to_map,
333 )
334 }
335
336 fn descend_into_macros(&self, token: SyntaxToken) -> SyntaxToken {
337 let _p = profile("descend_into_macros");
338 let parent = token.parent();
339 let parent = self.find_file(parent);
340 let sa = self.analyze2(parent.as_ref(), None);
341
342 let token = successors(Some(parent.with_value(token)), |token| {
343 self.db.check_canceled();
344 let macro_call = token.value.ancestors().find_map(ast::MacroCall::cast)?;
345 let tt = macro_call.token_tree()?;
346 if !tt.syntax().text_range().contains_range(token.value.text_range()) {
347 return None;
348 }
349 let file_id = sa.expand(self.db, token.with_value(&macro_call))?;
350 let token = self
351 .expansion_info_cache
352 .borrow_mut()
353 .entry(file_id)
354 .or_insert_with(|| file_id.expansion_info(self.db.upcast()))
355 .as_ref()?
356 .map_token_down(token.as_ref())?;
357
358 self.cache(find_root(&token.value.parent()), token.file_id);
359
360 Some(token)
361 })
362 .last()
363 .unwrap();
364
365 token.value
366 }
367
368 fn descend_node_at_offset(
369 &self,
370 node: &SyntaxNode,
371 offset: TextSize,
372 ) -> impl Iterator<Item = SyntaxNode> + '_ {
373 // Handle macro token cases
374 node.token_at_offset(offset)
375 .map(|token| self.descend_into_macros(token))
376 .map(|it| self.ancestors_with_macros(it.parent()))
377 .flatten()
378 }
379
380 fn original_range(&self, node: &SyntaxNode) -> FileRange {
381 let node = self.find_file(node.clone());
382 original_range(self.db, node.as_ref())
383 }
384
385 fn diagnostics_display_range(&self, diagnostics: &dyn Diagnostic) -> FileRange {
386 let src = diagnostics.display_source();
387 let root = self.db.parse_or_expand(src.file_id).unwrap();
388 let node = src.value.to_node(&root);
389 self.cache(root, src.file_id);
390 original_range(self.db, src.with_value(&node))
391 }
392
393 fn ancestors_with_macros(&self, node: SyntaxNode) -> impl Iterator<Item = SyntaxNode> + '_ {
394 let node = self.find_file(node);
395 node.ancestors_with_macros(self.db.upcast()).map(|it| it.value)
396 }
397
398 fn ancestors_at_offset_with_macros(
399 &self,
400 node: &SyntaxNode,
401 offset: TextSize,
402 ) -> impl Iterator<Item = SyntaxNode> + '_ {
403 node.token_at_offset(offset)
404 .map(|token| self.ancestors_with_macros(token.parent()))
405 .kmerge_by(|node1, node2| node1.text_range().len() < node2.text_range().len())
406 }
407
408 fn type_of_expr(&self, expr: &ast::Expr) -> Option<Type> {
409 self.analyze(expr.syntax()).type_of_expr(self.db, &expr)
410 }
411
412 fn type_of_pat(&self, pat: &ast::Pat) -> Option<Type> {
413 self.analyze(pat.syntax()).type_of_pat(self.db, &pat)
414 }
415
416 fn type_of_self(&self, param: &ast::SelfParam) -> Option<Type> {
417 self.analyze(param.syntax()).type_of_self(self.db, &param)
418 }
419
420 fn resolve_method_call(&self, call: &ast::MethodCallExpr) -> Option<FunctionId> {
421 self.analyze(call.syntax()).resolve_method_call(self.db, call)
422 }
423
424 fn resolve_method_call_as_callable(&self, call: &ast::MethodCallExpr) -> Option<Callable> {
425 // FIXME: this erases Substs
426 let func = self.resolve_method_call(call)?;
427 let ty = self.db.value_ty(func.into());
428 let resolver = self.analyze(call.syntax()).resolver;
429 let ty = Type::new_with_resolver(self.db, &resolver, ty.value)?;
430 let mut res = ty.as_callable(self.db)?;
431 res.is_bound_method = true;
432 Some(res)
433 }
434
435 fn resolve_field(&self, field: &ast::FieldExpr) -> Option<Field> {
436 self.analyze(field.syntax()).resolve_field(self.db, field)
437 }
438
439 fn resolve_record_field(&self, field: &ast::RecordExprField) -> Option<(Field, Option<Local>)> {
440 self.analyze(field.syntax()).resolve_record_field(self.db, field)
441 }
442
443 fn resolve_record_field_pat(&self, field: &ast::RecordPatField) -> Option<Field> {
444 self.analyze(field.syntax()).resolve_record_field_pat(self.db, field)
445 }
446
447 fn resolve_macro_call(&self, macro_call: &ast::MacroCall) -> Option<MacroDef> {
448 let sa = self.analyze(macro_call.syntax());
449 let macro_call = self.find_file(macro_call.syntax().clone()).with_value(macro_call);
450 sa.resolve_macro_call(self.db, macro_call)
451 }
452
453 fn resolve_path(&self, path: &ast::Path) -> Option<PathResolution> {
454 self.analyze(path.syntax()).resolve_path(self.db, path)
455 }
456
457 fn resolve_extern_crate(&self, extern_crate: &ast::ExternCrate) -> Option<Crate> {
458 let krate = self.scope(extern_crate.syntax()).krate()?;
459 krate.dependencies(self.db).into_iter().find_map(|dep| {
460 if dep.name == extern_crate.name_ref()?.as_name() {
461 Some(dep.krate)
462 } else {
463 None
464 }
465 })
466 }
467
468 fn resolve_variant(&self, record_lit: ast::RecordExpr) -> Option<VariantId> {
469 self.analyze(record_lit.syntax()).resolve_variant(self.db, record_lit)
470 }
471
472 fn lower_path(&self, path: &ast::Path) -> Option<Path> {
473 let src = self.find_file(path.syntax().clone());
474 Path::from_src(path.clone(), &Hygiene::new(self.db.upcast(), src.file_id.into()))
475 }
476
477 fn resolve_bind_pat_to_const(&self, pat: &ast::IdentPat) -> Option<ModuleDef> {
478 self.analyze(pat.syntax()).resolve_bind_pat_to_const(self.db, pat)
479 }
480
481 fn record_literal_missing_fields(&self, literal: &ast::RecordExpr) -> Vec<(Field, Type)> {
482 self.analyze(literal.syntax())
483 .record_literal_missing_fields(self.db, literal)
484 .unwrap_or_default()
485 }
486
487 fn record_pattern_missing_fields(&self, pattern: &ast::RecordPat) -> Vec<(Field, Type)> {
488 self.analyze(pattern.syntax())
489 .record_pattern_missing_fields(self.db, pattern)
490 .unwrap_or_default()
491 }
492
493 fn with_ctx<F: FnOnce(&mut SourceToDefCtx) -> T, T>(&self, f: F) -> T {
494 let mut cache = self.s2d_cache.borrow_mut();
495 let mut ctx = SourceToDefCtx { db: self.db, cache: &mut *cache };
496 f(&mut ctx)
497 }
498
499 fn to_module_def(&self, file: FileId) -> Option<Module> {
500 self.with_ctx(|ctx| ctx.file_to_def(file)).map(Module::from)
501 }
502
503 fn scope(&self, node: &SyntaxNode) -> SemanticsScope<'db> {
504 let node = self.find_file(node.clone());
505 let resolver = self.analyze2(node.as_ref(), None).resolver;
506 SemanticsScope { db: self.db, resolver }
507 }
508
509 fn scope_at_offset(&self, node: &SyntaxNode, offset: TextSize) -> SemanticsScope<'db> {
510 let node = self.find_file(node.clone());
511 let resolver = self.analyze2(node.as_ref(), Some(offset)).resolver;
512 SemanticsScope { db: self.db, resolver }
513 }
514
515 fn scope_for_def(&self, def: Trait) -> SemanticsScope<'db> {
516 let resolver = def.id.resolver(self.db.upcast());
517 SemanticsScope { db: self.db, resolver }
518 }
519
520 fn analyze(&self, node: &SyntaxNode) -> SourceAnalyzer {
521 let src = self.find_file(node.clone());
522 self.analyze2(src.as_ref(), None)
523 }
524
525 fn analyze2(&self, src: InFile<&SyntaxNode>, offset: Option<TextSize>) -> SourceAnalyzer {
526 let _p = profile("Semantics::analyze2");
527
528 let container = match self.with_ctx(|ctx| ctx.find_container(src)) {
529 Some(it) => it,
530 None => return SourceAnalyzer::new_for_resolver(Resolver::default(), src),
531 };
532
533 let resolver = match container {
534 ChildContainer::DefWithBodyId(def) => {
535 return SourceAnalyzer::new_for_body(self.db, def, src, offset)
536 }
537 ChildContainer::TraitId(it) => it.resolver(self.db.upcast()),
538 ChildContainer::ImplId(it) => it.resolver(self.db.upcast()),
539 ChildContainer::ModuleId(it) => it.resolver(self.db.upcast()),
540 ChildContainer::EnumId(it) => it.resolver(self.db.upcast()),
541 ChildContainer::VariantId(it) => it.resolver(self.db.upcast()),
542 ChildContainer::TypeAliasId(it) => it.resolver(self.db.upcast()),
543 ChildContainer::GenericDefId(it) => it.resolver(self.db.upcast()),
544 };
545 SourceAnalyzer::new_for_resolver(resolver, src)
546 }
547
548 fn cache(&self, root_node: SyntaxNode, file_id: HirFileId) {
549 assert!(root_node.parent().is_none());
550 let mut cache = self.cache.borrow_mut();
551 let prev = cache.insert(root_node, file_id);
552 assert!(prev == None || prev == Some(file_id))
553 }
554
555 fn assert_contains_node(&self, node: &SyntaxNode) {
556 self.find_file(node.clone());
557 }
558
559 fn lookup(&self, root_node: &SyntaxNode) -> Option<HirFileId> {
560 let cache = self.cache.borrow();
561 cache.get(root_node).copied()
562 }
563
564 fn find_file(&self, node: SyntaxNode) -> InFile<SyntaxNode> {
565 let root_node = find_root(&node);
566 let file_id = self.lookup(&root_node).unwrap_or_else(|| {
567 panic!(
568 "\n\nFailed to lookup {:?} in this Semantics.\n\
569 Make sure to use only query nodes, derived from this instance of Semantics.\n\
570 root node: {:?}\n\
571 known nodes: {}\n\n",
572 node,
573 root_node,
574 self.cache
575 .borrow()
576 .keys()
577 .map(|it| format!("{:?}", it))
578 .collect::<Vec<_>>()
579 .join(", ")
580 )
581 });
582 InFile::new(file_id, node)
583 }
584
585 pub fn is_unsafe_method_call(&self, method_call_expr: ast::MethodCallExpr) -> bool {
586 method_call_expr
587 .expr()
588 .and_then(|expr| {
589 let field_expr = if let ast::Expr::FieldExpr(field_expr) = expr {
590 field_expr
591 } else {
592 return None;
593 };
594 let ty = self.type_of_expr(&field_expr.expr()?)?;
595 if !ty.is_packed(self.db) {
596 return None;
597 }
598
599 let func = self.resolve_method_call(&method_call_expr).map(Function::from)?;
600 let is_unsafe = func.has_self_param(self.db)
601 && matches!(func.params(self.db).first(), Some(TypeRef::Reference(..)));
602 Some(is_unsafe)
603 })
604 .unwrap_or(false)
605 }
606
607 pub fn is_unsafe_ref_expr(&self, ref_expr: &ast::RefExpr) -> bool {
608 ref_expr
609 .expr()
610 .and_then(|expr| {
611 let field_expr = match expr {
612 ast::Expr::FieldExpr(field_expr) => field_expr,
613 _ => return None,
614 };
615 let expr = field_expr.expr()?;
616 self.type_of_expr(&expr)
617 })
618 // Binding a reference to a packed type is possibly unsafe.
619 .map(|ty| ty.is_packed(self.db))
620 .unwrap_or(false)
621
622 // FIXME This needs layout computation to be correct. It will highlight
623 // more than it should with the current implementation.
624 }
625
626 pub fn is_unsafe_ident_pat(&self, ident_pat: &ast::IdentPat) -> bool {
627 if !ident_pat.ref_token().is_some() {
628 return false;
629 }
630
631 ident_pat
632 .syntax()
633 .parent()
634 .and_then(|parent| {
635 // `IdentPat` can live under `RecordPat` directly under `RecordPatField` or
636 // `RecordPatFieldList`. `RecordPatField` also lives under `RecordPatFieldList`,
637 // so this tries to lookup the `IdentPat` anywhere along that structure to the
638 // `RecordPat` so we can get the containing type.
639 let record_pat = ast::RecordPatField::cast(parent.clone())
640 .and_then(|record_pat| record_pat.syntax().parent())
641 .or_else(|| Some(parent.clone()))
642 .and_then(|parent| {
643 ast::RecordPatFieldList::cast(parent)?
644 .syntax()
645 .parent()
646 .and_then(ast::RecordPat::cast)
647 });
648
649 // If this doesn't match a `RecordPat`, fallback to a `LetStmt` to see if
650 // this is initialized from a `FieldExpr`.
651 if let Some(record_pat) = record_pat {
652 self.type_of_pat(&ast::Pat::RecordPat(record_pat))
653 } else if let Some(let_stmt) = ast::LetStmt::cast(parent) {
654 let field_expr = match let_stmt.initializer()? {
655 ast::Expr::FieldExpr(field_expr) => field_expr,
656 _ => return None,
657 };
658
659 self.type_of_expr(&field_expr.expr()?)
660 } else {
661 None
662 }
663 })
664 // Binding a reference to a packed type is possibly unsafe.
665 .map(|ty| ty.is_packed(self.db))
666 .unwrap_or(false)
667 }
668}
669
670pub trait ToDef: AstNode + Clone {
671 type Def;
672
673 fn to_def(sema: &SemanticsImpl, src: InFile<Self>) -> Option<Self::Def>;
674}
675
676macro_rules! to_def_impls {
677 ($(($def:path, $ast:path, $meth:ident)),* ,) => {$(
678 impl ToDef for $ast {
679 type Def = $def;
680 fn to_def(sema: &SemanticsImpl, src: InFile<Self>) -> Option<Self::Def> {
681 sema.with_ctx(|ctx| ctx.$meth(src)).map(<$def>::from)
682 }
683 }
684 )*}
685}
686
687to_def_impls![
688 (crate::Module, ast::Module, module_to_def),
689 (crate::Struct, ast::Struct, struct_to_def),
690 (crate::Enum, ast::Enum, enum_to_def),
691 (crate::Union, ast::Union, union_to_def),
692 (crate::Trait, ast::Trait, trait_to_def),
693 (crate::ImplDef, ast::Impl, impl_to_def),
694 (crate::TypeAlias, ast::TypeAlias, type_alias_to_def),
695 (crate::Const, ast::Const, const_to_def),
696 (crate::Static, ast::Static, static_to_def),
697 (crate::Function, ast::Fn, fn_to_def),
698 (crate::Field, ast::RecordField, record_field_to_def),
699 (crate::Field, ast::TupleField, tuple_field_to_def),
700 (crate::EnumVariant, ast::Variant, enum_variant_to_def),
701 (crate::TypeParam, ast::TypeParam, type_param_to_def),
702 (crate::MacroDef, ast::MacroCall, macro_call_to_def), // this one is dubious, not all calls are macros
703 (crate::Local, ast::IdentPat, bind_pat_to_def),
704];
705
706fn find_root(node: &SyntaxNode) -> SyntaxNode {
707 node.ancestors().last().unwrap()
708}
709
710#[derive(Debug)]
711pub struct SemanticsScope<'a> {
712 pub db: &'a dyn HirDatabase,
713 resolver: Resolver,
714}
715
716impl<'a> SemanticsScope<'a> {
717 pub fn module(&self) -> Option<Module> {
718 Some(Module { id: self.resolver.module()? })
719 }
720
721 pub fn krate(&self) -> Option<Crate> {
722 Some(Crate { id: self.resolver.krate()? })
723 }
724
725 /// Note: `FxHashSet<TraitId>` should be treated as an opaque type, passed into `Type
726 // FIXME: rename to visible_traits to not repeat scope?
727 pub fn traits_in_scope(&self) -> FxHashSet<TraitId> {
728 let resolver = &self.resolver;
729 resolver.traits_in_scope(self.db.upcast())
730 }
731
732 pub fn process_all_names(&self, f: &mut dyn FnMut(Name, ScopeDef)) {
733 let resolver = &self.resolver;
734
735 resolver.process_all_names(self.db.upcast(), &mut |name, def| {
736 let def = match def {
737 resolver::ScopeDef::PerNs(it) => {
738 let items = ScopeDef::all_items(it);
739 for item in items {
740 f(name.clone(), item);
741 }
742 return;
743 }
744 resolver::ScopeDef::ImplSelfType(it) => ScopeDef::ImplSelfType(it.into()),
745 resolver::ScopeDef::AdtSelfType(it) => ScopeDef::AdtSelfType(it.into()),
746 resolver::ScopeDef::GenericParam(id) => ScopeDef::GenericParam(TypeParam { id }),
747 resolver::ScopeDef::Local(pat_id) => {
748 let parent = resolver.body_owner().unwrap().into();
749 ScopeDef::Local(Local { parent, pat_id })
750 }
751 };
752 f(name, def)
753 })
754 }
755
756 pub fn resolve_hir_path(&self, path: &Path) -> Option<PathResolution> {
757 resolve_hir_path(self.db, &self.resolver, path)
758 }
759
760 /// Resolves a path where we know it is a qualifier of another path.
761 ///
762 /// For example, if we have:
763 /// ```
764 /// mod my {
765 /// pub mod foo {
766 /// struct Bar;
767 /// }
768 ///
769 /// pub fn foo() {}
770 /// }
771 /// ```
772 /// then we know that `foo` in `my::foo::Bar` refers to the module, not the function.
773 pub fn resolve_hir_path_qualifier(&self, path: &Path) -> Option<PathResolution> {
774 resolve_hir_path_qualifier(self.db, &self.resolver, path)
775 }
776}
777
778// FIXME: Change `HasSource` trait to work with `Semantics` and remove this?
779pub fn original_range(db: &dyn HirDatabase, node: InFile<&SyntaxNode>) -> FileRange {
780 if let Some(range) = original_range_opt(db, node) {
781 let original_file = range.file_id.original_file(db.upcast());
782 if range.file_id == original_file.into() {
783 return FileRange { file_id: original_file, range: range.value };
784 }
785
786 log::error!("Fail to mapping up more for {:?}", range);
787 return FileRange { file_id: range.file_id.original_file(db.upcast()), range: range.value };
788 }
789
790 // Fall back to whole macro call
791 if let Some(expansion) = node.file_id.expansion_info(db.upcast()) {
792 if let Some(call_node) = expansion.call_node() {
793 return FileRange {
794 file_id: call_node.file_id.original_file(db.upcast()),
795 range: call_node.value.text_range(),
796 };
797 }
798 }
799
800 FileRange { file_id: node.file_id.original_file(db.upcast()), range: node.value.text_range() }
801}
802
803fn original_range_opt(
804 db: &dyn HirDatabase,
805 node: InFile<&SyntaxNode>,
806) -> Option<InFile<TextRange>> {
807 let expansion = node.file_id.expansion_info(db.upcast())?;
808
809 // the input node has only one token ?
810 let single = skip_trivia_token(node.value.first_token()?, Direction::Next)?
811 == skip_trivia_token(node.value.last_token()?, Direction::Prev)?;
812
813 Some(node.value.descendants().find_map(|it| {
814 let first = skip_trivia_token(it.first_token()?, Direction::Next)?;
815 let first = ascend_call_token(db, &expansion, node.with_value(first))?;
816
817 let last = skip_trivia_token(it.last_token()?, Direction::Prev)?;
818 let last = ascend_call_token(db, &expansion, node.with_value(last))?;
819
820 if (!single && first == last) || (first.file_id != last.file_id) {
821 return None;
822 }
823
824 Some(first.with_value(first.value.text_range().cover(last.value.text_range())))
825 })?)
826}
827
828fn ascend_call_token(
829 db: &dyn HirDatabase,
830 expansion: &ExpansionInfo,
831 token: InFile<SyntaxToken>,
832) -> Option<InFile<SyntaxToken>> {
833 let (mapped, origin) = expansion.map_token_up(token.as_ref())?;
834 if origin != Origin::Call {
835 return None;
836 }
837 if let Some(info) = mapped.file_id.expansion_info(db.upcast()) {
838 return ascend_call_token(db, &info, mapped);
839 }
840 Some(mapped)
841}