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.rs750
1 files changed, 0 insertions, 750 deletions
diff --git a/crates/ra_hir/src/semantics.rs b/crates/ra_hir/src/semantics.rs
deleted file mode 100644
index e392130ab..000000000
--- a/crates/ra_hir/src/semantics.rs
+++ /dev/null
@@ -1,750 +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::{diagnostics::AstDiagnostic, 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, VariantDef,
29};
30use resolver::TypeNs;
31
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub enum PathResolution {
34 /// An item
35 Def(ModuleDef),
36 /// A local binding (only value namespace)
37 Local(Local),
38 /// A generic parameter
39 TypeParam(TypeParam),
40 SelfType(ImplDef),
41 Macro(MacroDef),
42 AssocItem(AssocItem),
43}
44
45impl PathResolution {
46 fn in_type_ns(&self) -> Option<TypeNs> {
47 match self {
48 PathResolution::Def(ModuleDef::Adt(adt)) => Some(TypeNs::AdtId((*adt).into())),
49 PathResolution::Def(ModuleDef::BuiltinType(builtin)) => {
50 Some(TypeNs::BuiltinType(*builtin))
51 }
52 PathResolution::Def(ModuleDef::Const(_))
53 | PathResolution::Def(ModuleDef::EnumVariant(_))
54 | PathResolution::Def(ModuleDef::Function(_))
55 | PathResolution::Def(ModuleDef::Module(_))
56 | PathResolution::Def(ModuleDef::Static(_))
57 | PathResolution::Def(ModuleDef::Trait(_)) => None,
58 PathResolution::Def(ModuleDef::TypeAlias(alias)) => {
59 Some(TypeNs::TypeAliasId((*alias).into()))
60 }
61 PathResolution::Local(_) | PathResolution::Macro(_) => None,
62 PathResolution::TypeParam(param) => Some(TypeNs::GenericParam((*param).into())),
63 PathResolution::SelfType(impl_def) => Some(TypeNs::SelfType((*impl_def).into())),
64 PathResolution::AssocItem(AssocItem::Const(_))
65 | PathResolution::AssocItem(AssocItem::Function(_)) => None,
66 PathResolution::AssocItem(AssocItem::TypeAlias(alias)) => {
67 Some(TypeNs::TypeAliasId((*alias).into()))
68 }
69 }
70 }
71
72 /// Returns an iterator over associated types that may be specified after this path (using
73 /// `Ty::Assoc` syntax).
74 pub fn assoc_type_shorthand_candidates<R>(
75 &self,
76 db: &dyn HirDatabase,
77 mut cb: impl FnMut(TypeAlias) -> Option<R>,
78 ) -> Option<R> {
79 associated_type_shorthand_candidates(db, self.in_type_ns()?, |_, _, id| cb(id.into()))
80 }
81}
82
83/// Primary API to get semantic information, like types, from syntax trees.
84pub struct Semantics<'db, DB> {
85 pub db: &'db DB,
86 imp: SemanticsImpl<'db>,
87}
88
89pub struct SemanticsImpl<'db> {
90 pub db: &'db dyn HirDatabase,
91 s2d_cache: RefCell<SourceToDefCache>,
92 expansion_info_cache: RefCell<FxHashMap<HirFileId, Option<ExpansionInfo>>>,
93 cache: RefCell<FxHashMap<SyntaxNode, HirFileId>>,
94}
95
96impl<DB> fmt::Debug for Semantics<'_, DB> {
97 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98 write!(f, "Semantics {{ ... }}")
99 }
100}
101
102impl<'db, DB: HirDatabase> Semantics<'db, DB> {
103 pub fn new(db: &DB) -> Semantics<DB> {
104 let impl_ = SemanticsImpl::new(db);
105 Semantics { db, imp: impl_ }
106 }
107
108 pub fn parse(&self, file_id: FileId) -> ast::SourceFile {
109 self.imp.parse(file_id)
110 }
111
112 pub fn ast<T: AstDiagnostic + Diagnostic>(&self, d: &T) -> <T as AstDiagnostic>::AST {
113 let file_id = d.source().file_id;
114 let root = self.db.parse_or_expand(file_id).unwrap();
115 self.imp.cache(root, file_id);
116 d.ast(self.db.upcast())
117 }
118
119 pub fn expand(&self, macro_call: &ast::MacroCall) -> Option<SyntaxNode> {
120 self.imp.expand(macro_call)
121 }
122
123 pub fn expand_hypothetical(
124 &self,
125 actual_macro_call: &ast::MacroCall,
126 hypothetical_args: &ast::TokenTree,
127 token_to_map: SyntaxToken,
128 ) -> Option<(SyntaxNode, SyntaxToken)> {
129 self.imp.expand_hypothetical(actual_macro_call, hypothetical_args, token_to_map)
130 }
131
132 pub fn descend_into_macros(&self, token: SyntaxToken) -> SyntaxToken {
133 self.imp.descend_into_macros(token)
134 }
135
136 pub fn descend_node_at_offset<N: ast::AstNode>(
137 &self,
138 node: &SyntaxNode,
139 offset: TextSize,
140 ) -> Option<N> {
141 self.imp.descend_node_at_offset(node, offset).find_map(N::cast)
142 }
143
144 pub fn original_range(&self, node: &SyntaxNode) -> FileRange {
145 self.imp.original_range(node)
146 }
147
148 pub fn diagnostics_range(&self, diagnostics: &dyn Diagnostic) -> FileRange {
149 self.imp.diagnostics_range(diagnostics)
150 }
151
152 pub fn ancestors_with_macros(&self, node: SyntaxNode) -> impl Iterator<Item = SyntaxNode> + '_ {
153 self.imp.ancestors_with_macros(node)
154 }
155
156 pub fn ancestors_at_offset_with_macros(
157 &self,
158 node: &SyntaxNode,
159 offset: TextSize,
160 ) -> impl Iterator<Item = SyntaxNode> + '_ {
161 self.imp.ancestors_at_offset_with_macros(node, offset)
162 }
163
164 /// Find a AstNode by offset inside SyntaxNode, if it is inside *Macrofile*,
165 /// search up until it is of the target AstNode type
166 pub fn find_node_at_offset_with_macros<N: AstNode>(
167 &self,
168 node: &SyntaxNode,
169 offset: TextSize,
170 ) -> Option<N> {
171 self.imp.ancestors_at_offset_with_macros(node, offset).find_map(N::cast)
172 }
173
174 /// Find a AstNode by offset inside SyntaxNode, if it is inside *MacroCall*,
175 /// descend it and find again
176 pub fn find_node_at_offset_with_descend<N: AstNode>(
177 &self,
178 node: &SyntaxNode,
179 offset: TextSize,
180 ) -> Option<N> {
181 if let Some(it) = find_node_at_offset(&node, offset) {
182 return Some(it);
183 }
184
185 self.imp.descend_node_at_offset(node, offset).find_map(N::cast)
186 }
187
188 pub fn type_of_expr(&self, expr: &ast::Expr) -> Option<Type> {
189 self.imp.type_of_expr(expr)
190 }
191
192 pub fn type_of_pat(&self, pat: &ast::Pat) -> Option<Type> {
193 self.imp.type_of_pat(pat)
194 }
195
196 pub fn type_of_self(&self, param: &ast::SelfParam) -> Option<Type> {
197 self.imp.type_of_self(param)
198 }
199
200 pub fn resolve_method_call(&self, call: &ast::MethodCallExpr) -> Option<Function> {
201 self.imp.resolve_method_call(call).map(Function::from)
202 }
203
204 pub fn resolve_method_call_as_callable(&self, call: &ast::MethodCallExpr) -> Option<Callable> {
205 self.imp.resolve_method_call_as_callable(call)
206 }
207
208 pub fn resolve_field(&self, field: &ast::FieldExpr) -> Option<Field> {
209 self.imp.resolve_field(field)
210 }
211
212 pub fn resolve_record_field(
213 &self,
214 field: &ast::RecordExprField,
215 ) -> Option<(Field, Option<Local>)> {
216 self.imp.resolve_record_field(field)
217 }
218
219 pub fn resolve_record_field_pat(&self, field: &ast::RecordPatField) -> Option<Field> {
220 self.imp.resolve_record_field_pat(field)
221 }
222
223 pub fn resolve_macro_call(&self, macro_call: &ast::MacroCall) -> Option<MacroDef> {
224 self.imp.resolve_macro_call(macro_call)
225 }
226
227 pub fn resolve_path(&self, path: &ast::Path) -> Option<PathResolution> {
228 self.imp.resolve_path(path)
229 }
230
231 pub fn resolve_extern_crate(&self, extern_crate: &ast::ExternCrate) -> Option<Crate> {
232 self.imp.resolve_extern_crate(extern_crate)
233 }
234
235 pub fn resolve_variant(&self, record_lit: ast::RecordExpr) -> Option<VariantDef> {
236 self.imp.resolve_variant(record_lit).map(VariantDef::from)
237 }
238
239 pub fn lower_path(&self, path: &ast::Path) -> Option<Path> {
240 self.imp.lower_path(path)
241 }
242
243 pub fn resolve_bind_pat_to_const(&self, pat: &ast::IdentPat) -> Option<ModuleDef> {
244 self.imp.resolve_bind_pat_to_const(pat)
245 }
246
247 // FIXME: use this instead?
248 // pub fn resolve_name_ref(&self, name_ref: &ast::NameRef) -> Option<???>;
249
250 pub fn record_literal_missing_fields(&self, literal: &ast::RecordExpr) -> Vec<(Field, Type)> {
251 self.imp.record_literal_missing_fields(literal)
252 }
253
254 pub fn record_pattern_missing_fields(&self, pattern: &ast::RecordPat) -> Vec<(Field, Type)> {
255 self.imp.record_pattern_missing_fields(pattern)
256 }
257
258 pub fn to_def<T: ToDef>(&self, src: &T) -> Option<T::Def> {
259 let src = self.imp.find_file(src.syntax().clone()).with_value(src).cloned();
260 T::to_def(&self.imp, src)
261 }
262
263 pub fn to_module_def(&self, file: FileId) -> Option<Module> {
264 self.imp.to_module_def(file)
265 }
266
267 pub fn scope(&self, node: &SyntaxNode) -> SemanticsScope<'db> {
268 self.imp.scope(node)
269 }
270
271 pub fn scope_at_offset(&self, node: &SyntaxNode, offset: TextSize) -> SemanticsScope<'db> {
272 self.imp.scope_at_offset(node, offset)
273 }
274
275 pub fn scope_for_def(&self, def: Trait) -> SemanticsScope<'db> {
276 self.imp.scope_for_def(def)
277 }
278
279 pub fn assert_contains_node(&self, node: &SyntaxNode) {
280 self.imp.assert_contains_node(node)
281 }
282}
283
284impl<'db> SemanticsImpl<'db> {
285 fn new(db: &'db dyn HirDatabase) -> Self {
286 SemanticsImpl {
287 db,
288 s2d_cache: Default::default(),
289 cache: Default::default(),
290 expansion_info_cache: Default::default(),
291 }
292 }
293
294 fn parse(&self, file_id: FileId) -> ast::SourceFile {
295 let tree = self.db.parse(file_id).tree();
296 self.cache(tree.syntax().clone(), file_id.into());
297 tree
298 }
299
300 fn expand(&self, macro_call: &ast::MacroCall) -> Option<SyntaxNode> {
301 let macro_call = self.find_file(macro_call.syntax().clone()).with_value(macro_call);
302 let sa = self.analyze2(macro_call.map(|it| it.syntax()), None);
303 let file_id = sa.expand(self.db, macro_call)?;
304 let node = self.db.parse_or_expand(file_id)?;
305 self.cache(node.clone(), file_id);
306 Some(node)
307 }
308
309 fn expand_hypothetical(
310 &self,
311 actual_macro_call: &ast::MacroCall,
312 hypothetical_args: &ast::TokenTree,
313 token_to_map: SyntaxToken,
314 ) -> Option<(SyntaxNode, SyntaxToken)> {
315 let macro_call =
316 self.find_file(actual_macro_call.syntax().clone()).with_value(actual_macro_call);
317 let sa = self.analyze2(macro_call.map(|it| it.syntax()), None);
318 let krate = sa.resolver.krate()?;
319 let macro_call_id = macro_call.as_call_id(self.db.upcast(), krate, |path| {
320 sa.resolver.resolve_path_as_macro(self.db.upcast(), &path)
321 })?;
322 hir_expand::db::expand_hypothetical(
323 self.db.upcast(),
324 macro_call_id,
325 hypothetical_args,
326 token_to_map,
327 )
328 }
329
330 fn descend_into_macros(&self, token: SyntaxToken) -> SyntaxToken {
331 let _p = profile("descend_into_macros");
332 let parent = token.parent();
333 let parent = self.find_file(parent);
334 let sa = self.analyze2(parent.as_ref(), None);
335
336 let token = successors(Some(parent.with_value(token)), |token| {
337 self.db.check_canceled();
338 let macro_call = token.value.ancestors().find_map(ast::MacroCall::cast)?;
339 let tt = macro_call.token_tree()?;
340 if !tt.syntax().text_range().contains_range(token.value.text_range()) {
341 return None;
342 }
343 let file_id = sa.expand(self.db, token.with_value(&macro_call))?;
344 let token = self
345 .expansion_info_cache
346 .borrow_mut()
347 .entry(file_id)
348 .or_insert_with(|| file_id.expansion_info(self.db.upcast()))
349 .as_ref()?
350 .map_token_down(token.as_ref())?;
351
352 self.cache(find_root(&token.value.parent()), token.file_id);
353
354 Some(token)
355 })
356 .last()
357 .unwrap();
358
359 token.value
360 }
361
362 fn descend_node_at_offset(
363 &self,
364 node: &SyntaxNode,
365 offset: TextSize,
366 ) -> impl Iterator<Item = SyntaxNode> + '_ {
367 // Handle macro token cases
368 node.token_at_offset(offset)
369 .map(|token| self.descend_into_macros(token))
370 .map(|it| self.ancestors_with_macros(it.parent()))
371 .flatten()
372 }
373
374 fn original_range(&self, node: &SyntaxNode) -> FileRange {
375 let node = self.find_file(node.clone());
376 original_range(self.db, node.as_ref())
377 }
378
379 fn diagnostics_range(&self, diagnostics: &dyn Diagnostic) -> FileRange {
380 let src = diagnostics.source();
381 let root = self.db.parse_or_expand(src.file_id).unwrap();
382 let node = src.value.to_node(&root);
383 original_range(self.db, src.with_value(&node))
384 }
385
386 fn ancestors_with_macros(&self, node: SyntaxNode) -> impl Iterator<Item = SyntaxNode> + '_ {
387 let node = self.find_file(node);
388 node.ancestors_with_macros(self.db.upcast()).map(|it| it.value)
389 }
390
391 fn ancestors_at_offset_with_macros(
392 &self,
393 node: &SyntaxNode,
394 offset: TextSize,
395 ) -> impl Iterator<Item = SyntaxNode> + '_ {
396 node.token_at_offset(offset)
397 .map(|token| self.ancestors_with_macros(token.parent()))
398 .kmerge_by(|node1, node2| node1.text_range().len() < node2.text_range().len())
399 }
400
401 fn type_of_expr(&self, expr: &ast::Expr) -> Option<Type> {
402 self.analyze(expr.syntax()).type_of_expr(self.db, &expr)
403 }
404
405 fn type_of_pat(&self, pat: &ast::Pat) -> Option<Type> {
406 self.analyze(pat.syntax()).type_of_pat(self.db, &pat)
407 }
408
409 fn type_of_self(&self, param: &ast::SelfParam) -> Option<Type> {
410 self.analyze(param.syntax()).type_of_self(self.db, &param)
411 }
412
413 fn resolve_method_call(&self, call: &ast::MethodCallExpr) -> Option<FunctionId> {
414 self.analyze(call.syntax()).resolve_method_call(self.db, call)
415 }
416
417 fn resolve_method_call_as_callable(&self, call: &ast::MethodCallExpr) -> Option<Callable> {
418 // FIXME: this erases Substs
419 let func = self.resolve_method_call(call)?;
420 let ty = self.db.value_ty(func.into());
421 let resolver = self.analyze(call.syntax()).resolver;
422 let ty = Type::new_with_resolver(self.db, &resolver, ty.value)?;
423 let mut res = ty.as_callable(self.db)?;
424 res.is_bound_method = true;
425 Some(res)
426 }
427
428 fn resolve_field(&self, field: &ast::FieldExpr) -> Option<Field> {
429 self.analyze(field.syntax()).resolve_field(self.db, field)
430 }
431
432 fn resolve_record_field(&self, field: &ast::RecordExprField) -> Option<(Field, Option<Local>)> {
433 self.analyze(field.syntax()).resolve_record_field(self.db, field)
434 }
435
436 fn resolve_record_field_pat(&self, field: &ast::RecordPatField) -> Option<Field> {
437 self.analyze(field.syntax()).resolve_record_field_pat(self.db, field)
438 }
439
440 fn resolve_macro_call(&self, macro_call: &ast::MacroCall) -> Option<MacroDef> {
441 let sa = self.analyze(macro_call.syntax());
442 let macro_call = self.find_file(macro_call.syntax().clone()).with_value(macro_call);
443 sa.resolve_macro_call(self.db, macro_call)
444 }
445
446 fn resolve_path(&self, path: &ast::Path) -> Option<PathResolution> {
447 self.analyze(path.syntax()).resolve_path(self.db, path)
448 }
449
450 fn resolve_extern_crate(&self, extern_crate: &ast::ExternCrate) -> Option<Crate> {
451 let krate = self.scope(extern_crate.syntax()).krate()?;
452 krate.dependencies(self.db).into_iter().find_map(|dep| {
453 if dep.name == extern_crate.name_ref()?.as_name() {
454 Some(dep.krate)
455 } else {
456 None
457 }
458 })
459 }
460
461 fn resolve_variant(&self, record_lit: ast::RecordExpr) -> Option<VariantId> {
462 self.analyze(record_lit.syntax()).resolve_variant(self.db, record_lit)
463 }
464
465 fn lower_path(&self, path: &ast::Path) -> Option<Path> {
466 let src = self.find_file(path.syntax().clone());
467 Path::from_src(path.clone(), &Hygiene::new(self.db.upcast(), src.file_id.into()))
468 }
469
470 fn resolve_bind_pat_to_const(&self, pat: &ast::IdentPat) -> Option<ModuleDef> {
471 self.analyze(pat.syntax()).resolve_bind_pat_to_const(self.db, pat)
472 }
473
474 fn record_literal_missing_fields(&self, literal: &ast::RecordExpr) -> Vec<(Field, Type)> {
475 self.analyze(literal.syntax())
476 .record_literal_missing_fields(self.db, literal)
477 .unwrap_or_default()
478 }
479
480 fn record_pattern_missing_fields(&self, pattern: &ast::RecordPat) -> Vec<(Field, Type)> {
481 self.analyze(pattern.syntax())
482 .record_pattern_missing_fields(self.db, pattern)
483 .unwrap_or_default()
484 }
485
486 fn with_ctx<F: FnOnce(&mut SourceToDefCtx) -> T, T>(&self, f: F) -> T {
487 let mut cache = self.s2d_cache.borrow_mut();
488 let mut ctx = SourceToDefCtx { db: self.db, cache: &mut *cache };
489 f(&mut ctx)
490 }
491
492 fn to_module_def(&self, file: FileId) -> Option<Module> {
493 self.with_ctx(|ctx| ctx.file_to_def(file)).map(Module::from)
494 }
495
496 fn scope(&self, node: &SyntaxNode) -> SemanticsScope<'db> {
497 let node = self.find_file(node.clone());
498 let resolver = self.analyze2(node.as_ref(), None).resolver;
499 SemanticsScope { db: self.db, resolver }
500 }
501
502 fn scope_at_offset(&self, node: &SyntaxNode, offset: TextSize) -> SemanticsScope<'db> {
503 let node = self.find_file(node.clone());
504 let resolver = self.analyze2(node.as_ref(), Some(offset)).resolver;
505 SemanticsScope { db: self.db, resolver }
506 }
507
508 fn scope_for_def(&self, def: Trait) -> SemanticsScope<'db> {
509 let resolver = def.id.resolver(self.db.upcast());
510 SemanticsScope { db: self.db, resolver }
511 }
512
513 fn analyze(&self, node: &SyntaxNode) -> SourceAnalyzer {
514 let src = self.find_file(node.clone());
515 self.analyze2(src.as_ref(), None)
516 }
517
518 fn analyze2(&self, src: InFile<&SyntaxNode>, offset: Option<TextSize>) -> SourceAnalyzer {
519 let _p = profile("Semantics::analyze2");
520
521 let container = match self.with_ctx(|ctx| ctx.find_container(src)) {
522 Some(it) => it,
523 None => return SourceAnalyzer::new_for_resolver(Resolver::default(), src),
524 };
525
526 let resolver = match container {
527 ChildContainer::DefWithBodyId(def) => {
528 return SourceAnalyzer::new_for_body(self.db, def, src, offset)
529 }
530 ChildContainer::TraitId(it) => it.resolver(self.db.upcast()),
531 ChildContainer::ImplId(it) => it.resolver(self.db.upcast()),
532 ChildContainer::ModuleId(it) => it.resolver(self.db.upcast()),
533 ChildContainer::EnumId(it) => it.resolver(self.db.upcast()),
534 ChildContainer::VariantId(it) => it.resolver(self.db.upcast()),
535 ChildContainer::TypeAliasId(it) => it.resolver(self.db.upcast()),
536 ChildContainer::GenericDefId(it) => it.resolver(self.db.upcast()),
537 };
538 SourceAnalyzer::new_for_resolver(resolver, src)
539 }
540
541 fn cache(&self, root_node: SyntaxNode, file_id: HirFileId) {
542 assert!(root_node.parent().is_none());
543 let mut cache = self.cache.borrow_mut();
544 let prev = cache.insert(root_node, file_id);
545 assert!(prev == None || prev == Some(file_id))
546 }
547
548 fn assert_contains_node(&self, node: &SyntaxNode) {
549 self.find_file(node.clone());
550 }
551
552 fn lookup(&self, root_node: &SyntaxNode) -> Option<HirFileId> {
553 let cache = self.cache.borrow();
554 cache.get(root_node).copied()
555 }
556
557 fn find_file(&self, node: SyntaxNode) -> InFile<SyntaxNode> {
558 let root_node = find_root(&node);
559 let file_id = self.lookup(&root_node).unwrap_or_else(|| {
560 panic!(
561 "\n\nFailed to lookup {:?} in this Semantics.\n\
562 Make sure to use only query nodes, derived from this instance of Semantics.\n\
563 root node: {:?}\n\
564 known nodes: {}\n\n",
565 node,
566 root_node,
567 self.cache
568 .borrow()
569 .keys()
570 .map(|it| format!("{:?}", it))
571 .collect::<Vec<_>>()
572 .join(", ")
573 )
574 });
575 InFile::new(file_id, node)
576 }
577}
578
579pub trait ToDef: AstNode + Clone {
580 type Def;
581
582 fn to_def(sema: &SemanticsImpl, src: InFile<Self>) -> Option<Self::Def>;
583}
584
585macro_rules! to_def_impls {
586 ($(($def:path, $ast:path, $meth:ident)),* ,) => {$(
587 impl ToDef for $ast {
588 type Def = $def;
589 fn to_def(sema: &SemanticsImpl, src: InFile<Self>) -> Option<Self::Def> {
590 sema.with_ctx(|ctx| ctx.$meth(src)).map(<$def>::from)
591 }
592 }
593 )*}
594}
595
596to_def_impls![
597 (crate::Module, ast::Module, module_to_def),
598 (crate::Struct, ast::Struct, struct_to_def),
599 (crate::Enum, ast::Enum, enum_to_def),
600 (crate::Union, ast::Union, union_to_def),
601 (crate::Trait, ast::Trait, trait_to_def),
602 (crate::ImplDef, ast::Impl, impl_to_def),
603 (crate::TypeAlias, ast::TypeAlias, type_alias_to_def),
604 (crate::Const, ast::Const, const_to_def),
605 (crate::Static, ast::Static, static_to_def),
606 (crate::Function, ast::Fn, fn_to_def),
607 (crate::Field, ast::RecordField, record_field_to_def),
608 (crate::Field, ast::TupleField, tuple_field_to_def),
609 (crate::EnumVariant, ast::Variant, enum_variant_to_def),
610 (crate::TypeParam, ast::TypeParam, type_param_to_def),
611 (crate::MacroDef, ast::MacroCall, macro_call_to_def), // this one is dubious, not all calls are macros
612 (crate::Local, ast::IdentPat, bind_pat_to_def),
613];
614
615fn find_root(node: &SyntaxNode) -> SyntaxNode {
616 node.ancestors().last().unwrap()
617}
618
619#[derive(Debug)]
620pub struct SemanticsScope<'a> {
621 pub db: &'a dyn HirDatabase,
622 resolver: Resolver,
623}
624
625impl<'a> SemanticsScope<'a> {
626 pub fn module(&self) -> Option<Module> {
627 Some(Module { id: self.resolver.module()? })
628 }
629
630 pub fn krate(&self) -> Option<Crate> {
631 Some(Crate { id: self.resolver.krate()? })
632 }
633
634 /// Note: `FxHashSet<TraitId>` should be treated as an opaque type, passed into `Type
635 // FIXME: rename to visible_traits to not repeat scope?
636 pub fn traits_in_scope(&self) -> FxHashSet<TraitId> {
637 let resolver = &self.resolver;
638 resolver.traits_in_scope(self.db.upcast())
639 }
640
641 pub fn process_all_names(&self, f: &mut dyn FnMut(Name, ScopeDef)) {
642 let resolver = &self.resolver;
643
644 resolver.process_all_names(self.db.upcast(), &mut |name, def| {
645 let def = match def {
646 resolver::ScopeDef::PerNs(it) => {
647 let items = ScopeDef::all_items(it);
648 for item in items {
649 f(name.clone(), item);
650 }
651 return;
652 }
653 resolver::ScopeDef::ImplSelfType(it) => ScopeDef::ImplSelfType(it.into()),
654 resolver::ScopeDef::AdtSelfType(it) => ScopeDef::AdtSelfType(it.into()),
655 resolver::ScopeDef::GenericParam(id) => ScopeDef::GenericParam(TypeParam { id }),
656 resolver::ScopeDef::Local(pat_id) => {
657 let parent = resolver.body_owner().unwrap().into();
658 ScopeDef::Local(Local { parent, pat_id })
659 }
660 };
661 f(name, def)
662 })
663 }
664
665 pub fn resolve_hir_path(&self, path: &Path) -> Option<PathResolution> {
666 resolve_hir_path(self.db, &self.resolver, path)
667 }
668
669 /// Resolves a path where we know it is a qualifier of another path.
670 ///
671 /// For example, if we have:
672 /// ```
673 /// mod my {
674 /// pub mod foo {
675 /// struct Bar;
676 /// }
677 ///
678 /// pub fn foo() {}
679 /// }
680 /// ```
681 /// then we know that `foo` in `my::foo::Bar` refers to the module, not the function.
682 pub fn resolve_hir_path_qualifier(&self, path: &Path) -> Option<PathResolution> {
683 resolve_hir_path_qualifier(self.db, &self.resolver, path)
684 }
685}
686
687// FIXME: Change `HasSource` trait to work with `Semantics` and remove this?
688pub fn original_range(db: &dyn HirDatabase, node: InFile<&SyntaxNode>) -> FileRange {
689 if let Some(range) = original_range_opt(db, node) {
690 let original_file = range.file_id.original_file(db.upcast());
691 if range.file_id == original_file.into() {
692 return FileRange { file_id: original_file, range: range.value };
693 }
694
695 log::error!("Fail to mapping up more for {:?}", range);
696 return FileRange { file_id: range.file_id.original_file(db.upcast()), range: range.value };
697 }
698
699 // Fall back to whole macro call
700 if let Some(expansion) = node.file_id.expansion_info(db.upcast()) {
701 if let Some(call_node) = expansion.call_node() {
702 return FileRange {
703 file_id: call_node.file_id.original_file(db.upcast()),
704 range: call_node.value.text_range(),
705 };
706 }
707 }
708
709 FileRange { file_id: node.file_id.original_file(db.upcast()), range: node.value.text_range() }
710}
711
712fn original_range_opt(
713 db: &dyn HirDatabase,
714 node: InFile<&SyntaxNode>,
715) -> Option<InFile<TextRange>> {
716 let expansion = node.file_id.expansion_info(db.upcast())?;
717
718 // the input node has only one token ?
719 let single = skip_trivia_token(node.value.first_token()?, Direction::Next)?
720 == skip_trivia_token(node.value.last_token()?, Direction::Prev)?;
721
722 Some(node.value.descendants().find_map(|it| {
723 let first = skip_trivia_token(it.first_token()?, Direction::Next)?;
724 let first = ascend_call_token(db, &expansion, node.with_value(first))?;
725
726 let last = skip_trivia_token(it.last_token()?, Direction::Prev)?;
727 let last = ascend_call_token(db, &expansion, node.with_value(last))?;
728
729 if (!single && first == last) || (first.file_id != last.file_id) {
730 return None;
731 }
732
733 Some(first.with_value(first.value.text_range().cover(last.value.text_range())))
734 })?)
735}
736
737fn ascend_call_token(
738 db: &dyn HirDatabase,
739 expansion: &ExpansionInfo,
740 token: InFile<SyntaxToken>,
741) -> Option<InFile<SyntaxToken>> {
742 let (mapped, origin) = expansion.map_token_up(token.as_ref())?;
743 if origin != Origin::Call {
744 return None;
745 }
746 if let Some(info) = mapped.file_id.expansion_info(db.upcast()) {
747 return ascend_call_token(db, &info, mapped);
748 }
749 Some(mapped)
750}