aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_hir/src/semantics.rs
diff options
context:
space:
mode:
authorDmitry <[email protected]>2020-08-14 19:32:05 +0100
committerDmitry <[email protected]>2020-08-14 19:32:05 +0100
commit178c3e135a2a249692f7784712492e7884ae0c00 (patch)
treeac6b769dbf7162150caa0c1624786a4dd79ff3be /crates/ra_hir/src/semantics.rs
parent06ff8e6c760ff05f10e868b5d1f9d79e42fbb49c (diff)
parentc2594daf2974dbd4ce3d9b7ec72481764abaceb5 (diff)
Merge remote-tracking branch 'origin/master'
Diffstat (limited to 'crates/ra_hir/src/semantics.rs')
-rw-r--r--crates/ra_hir/src/semantics.rs731
1 files changed, 0 insertions, 731 deletions
diff --git a/crates/ra_hir/src/semantics.rs b/crates/ra_hir/src/semantics.rs
deleted file mode 100644
index 307b336f2..000000000
--- a/crates/ra_hir/src/semantics.rs
+++ /dev/null
@@ -1,731 +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, 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, Field, Function, HirFileId, ImplDef, InFile, Local, MacroDef, Module,
28 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_variant(&self, record_lit: ast::RecordExpr) -> Option<VariantDef> {
232 self.imp.resolve_variant(record_lit).map(VariantDef::from)
233 }
234
235 pub fn lower_path(&self, path: &ast::Path) -> Option<Path> {
236 self.imp.lower_path(path)
237 }
238
239 pub fn resolve_bind_pat_to_const(&self, pat: &ast::IdentPat) -> Option<ModuleDef> {
240 self.imp.resolve_bind_pat_to_const(pat)
241 }
242
243 // FIXME: use this instead?
244 // pub fn resolve_name_ref(&self, name_ref: &ast::NameRef) -> Option<???>;
245
246 pub fn record_literal_missing_fields(&self, literal: &ast::RecordExpr) -> Vec<(Field, Type)> {
247 self.imp.record_literal_missing_fields(literal)
248 }
249
250 pub fn record_pattern_missing_fields(&self, pattern: &ast::RecordPat) -> Vec<(Field, Type)> {
251 self.imp.record_pattern_missing_fields(pattern)
252 }
253
254 pub fn to_def<T: ToDef>(&self, src: &T) -> Option<T::Def> {
255 let src = self.imp.find_file(src.syntax().clone()).with_value(src).cloned();
256 T::to_def(&self.imp, src)
257 }
258
259 pub fn to_module_def(&self, file: FileId) -> Option<Module> {
260 self.imp.to_module_def(file)
261 }
262
263 pub fn scope(&self, node: &SyntaxNode) -> SemanticsScope<'db> {
264 self.imp.scope(node)
265 }
266
267 pub fn scope_at_offset(&self, node: &SyntaxNode, offset: TextSize) -> SemanticsScope<'db> {
268 self.imp.scope_at_offset(node, offset)
269 }
270
271 pub fn scope_for_def(&self, def: Trait) -> SemanticsScope<'db> {
272 self.imp.scope_for_def(def)
273 }
274
275 pub fn assert_contains_node(&self, node: &SyntaxNode) {
276 self.imp.assert_contains_node(node)
277 }
278}
279
280impl<'db> SemanticsImpl<'db> {
281 fn new(db: &'db dyn HirDatabase) -> Self {
282 SemanticsImpl {
283 db,
284 s2d_cache: Default::default(),
285 cache: Default::default(),
286 expansion_info_cache: Default::default(),
287 }
288 }
289
290 fn parse(&self, file_id: FileId) -> ast::SourceFile {
291 let tree = self.db.parse(file_id).tree();
292 self.cache(tree.syntax().clone(), file_id.into());
293 tree
294 }
295
296 fn expand(&self, macro_call: &ast::MacroCall) -> Option<SyntaxNode> {
297 let macro_call = self.find_file(macro_call.syntax().clone()).with_value(macro_call);
298 let sa = self.analyze2(macro_call.map(|it| it.syntax()), None);
299 let file_id = sa.expand(self.db, macro_call)?;
300 let node = self.db.parse_or_expand(file_id)?;
301 self.cache(node.clone(), file_id);
302 Some(node)
303 }
304
305 fn expand_hypothetical(
306 &self,
307 actual_macro_call: &ast::MacroCall,
308 hypothetical_args: &ast::TokenTree,
309 token_to_map: SyntaxToken,
310 ) -> Option<(SyntaxNode, SyntaxToken)> {
311 let macro_call =
312 self.find_file(actual_macro_call.syntax().clone()).with_value(actual_macro_call);
313 let sa = self.analyze2(macro_call.map(|it| it.syntax()), None);
314 let krate = sa.resolver.krate()?;
315 let macro_call_id = macro_call.as_call_id(self.db.upcast(), krate, |path| {
316 sa.resolver.resolve_path_as_macro(self.db.upcast(), &path)
317 })?;
318 hir_expand::db::expand_hypothetical(
319 self.db.upcast(),
320 macro_call_id,
321 hypothetical_args,
322 token_to_map,
323 )
324 }
325
326 fn descend_into_macros(&self, token: SyntaxToken) -> SyntaxToken {
327 let _p = profile("descend_into_macros");
328 let parent = token.parent();
329 let parent = self.find_file(parent);
330 let sa = self.analyze2(parent.as_ref(), None);
331
332 let token = successors(Some(parent.with_value(token)), |token| {
333 self.db.check_canceled();
334 let macro_call = token.value.ancestors().find_map(ast::MacroCall::cast)?;
335 let tt = macro_call.token_tree()?;
336 if !tt.syntax().text_range().contains_range(token.value.text_range()) {
337 return None;
338 }
339 let file_id = sa.expand(self.db, token.with_value(&macro_call))?;
340 let token = self
341 .expansion_info_cache
342 .borrow_mut()
343 .entry(file_id)
344 .or_insert_with(|| file_id.expansion_info(self.db.upcast()))
345 .as_ref()?
346 .map_token_down(token.as_ref())?;
347
348 self.cache(find_root(&token.value.parent()), token.file_id);
349
350 Some(token)
351 })
352 .last()
353 .unwrap();
354
355 token.value
356 }
357
358 fn descend_node_at_offset(
359 &self,
360 node: &SyntaxNode,
361 offset: TextSize,
362 ) -> impl Iterator<Item = SyntaxNode> + '_ {
363 // Handle macro token cases
364 node.token_at_offset(offset)
365 .map(|token| self.descend_into_macros(token))
366 .map(|it| self.ancestors_with_macros(it.parent()))
367 .flatten()
368 }
369
370 fn original_range(&self, node: &SyntaxNode) -> FileRange {
371 let node = self.find_file(node.clone());
372 original_range(self.db, node.as_ref())
373 }
374
375 fn diagnostics_range(&self, diagnostics: &dyn Diagnostic) -> FileRange {
376 let src = diagnostics.source();
377 let root = self.db.parse_or_expand(src.file_id).unwrap();
378 let node = src.value.to_node(&root);
379 original_range(self.db, src.with_value(&node))
380 }
381
382 fn ancestors_with_macros(&self, node: SyntaxNode) -> impl Iterator<Item = SyntaxNode> + '_ {
383 let node = self.find_file(node);
384 node.ancestors_with_macros(self.db.upcast()).map(|it| it.value)
385 }
386
387 fn ancestors_at_offset_with_macros(
388 &self,
389 node: &SyntaxNode,
390 offset: TextSize,
391 ) -> impl Iterator<Item = SyntaxNode> + '_ {
392 node.token_at_offset(offset)
393 .map(|token| self.ancestors_with_macros(token.parent()))
394 .kmerge_by(|node1, node2| node1.text_range().len() < node2.text_range().len())
395 }
396
397 fn type_of_expr(&self, expr: &ast::Expr) -> Option<Type> {
398 self.analyze(expr.syntax()).type_of_expr(self.db, &expr)
399 }
400
401 fn type_of_pat(&self, pat: &ast::Pat) -> Option<Type> {
402 self.analyze(pat.syntax()).type_of_pat(self.db, &pat)
403 }
404
405 fn type_of_self(&self, param: &ast::SelfParam) -> Option<Type> {
406 self.analyze(param.syntax()).type_of_self(self.db, &param)
407 }
408
409 fn resolve_method_call(&self, call: &ast::MethodCallExpr) -> Option<FunctionId> {
410 self.analyze(call.syntax()).resolve_method_call(self.db, call)
411 }
412
413 fn resolve_method_call_as_callable(&self, call: &ast::MethodCallExpr) -> Option<Callable> {
414 // FIXME: this erases Substs
415 let func = self.resolve_method_call(call)?;
416 let ty = self.db.value_ty(func.into());
417 let resolver = self.analyze(call.syntax()).resolver;
418 let ty = Type::new_with_resolver(self.db, &resolver, ty.value)?;
419 let mut res = ty.as_callable(self.db)?;
420 res.is_bound_method = true;
421 Some(res)
422 }
423
424 fn resolve_field(&self, field: &ast::FieldExpr) -> Option<Field> {
425 self.analyze(field.syntax()).resolve_field(self.db, field)
426 }
427
428 fn resolve_record_field(&self, field: &ast::RecordExprField) -> Option<(Field, Option<Local>)> {
429 self.analyze(field.syntax()).resolve_record_field(self.db, field)
430 }
431
432 fn resolve_record_field_pat(&self, field: &ast::RecordPatField) -> Option<Field> {
433 self.analyze(field.syntax()).resolve_record_field_pat(self.db, field)
434 }
435
436 fn resolve_macro_call(&self, macro_call: &ast::MacroCall) -> Option<MacroDef> {
437 let sa = self.analyze(macro_call.syntax());
438 let macro_call = self.find_file(macro_call.syntax().clone()).with_value(macro_call);
439 sa.resolve_macro_call(self.db, macro_call)
440 }
441
442 fn resolve_path(&self, path: &ast::Path) -> Option<PathResolution> {
443 self.analyze(path.syntax()).resolve_path(self.db, path)
444 }
445
446 fn resolve_variant(&self, record_lit: ast::RecordExpr) -> Option<VariantId> {
447 self.analyze(record_lit.syntax()).resolve_variant(self.db, record_lit)
448 }
449
450 fn lower_path(&self, path: &ast::Path) -> Option<Path> {
451 let src = self.find_file(path.syntax().clone());
452 Path::from_src(path.clone(), &Hygiene::new(self.db.upcast(), src.file_id.into()))
453 }
454
455 fn resolve_bind_pat_to_const(&self, pat: &ast::IdentPat) -> Option<ModuleDef> {
456 self.analyze(pat.syntax()).resolve_bind_pat_to_const(self.db, pat)
457 }
458
459 fn record_literal_missing_fields(&self, literal: &ast::RecordExpr) -> Vec<(Field, Type)> {
460 self.analyze(literal.syntax())
461 .record_literal_missing_fields(self.db, literal)
462 .unwrap_or_default()
463 }
464
465 fn record_pattern_missing_fields(&self, pattern: &ast::RecordPat) -> Vec<(Field, Type)> {
466 self.analyze(pattern.syntax())
467 .record_pattern_missing_fields(self.db, pattern)
468 .unwrap_or_default()
469 }
470
471 fn with_ctx<F: FnOnce(&mut SourceToDefCtx) -> T, T>(&self, f: F) -> T {
472 let mut cache = self.s2d_cache.borrow_mut();
473 let mut ctx = SourceToDefCtx { db: self.db, cache: &mut *cache };
474 f(&mut ctx)
475 }
476
477 fn to_module_def(&self, file: FileId) -> Option<Module> {
478 self.with_ctx(|ctx| ctx.file_to_def(file)).map(Module::from)
479 }
480
481 fn scope(&self, node: &SyntaxNode) -> SemanticsScope<'db> {
482 let node = self.find_file(node.clone());
483 let resolver = self.analyze2(node.as_ref(), None).resolver;
484 SemanticsScope { db: self.db, resolver }
485 }
486
487 fn scope_at_offset(&self, node: &SyntaxNode, offset: TextSize) -> SemanticsScope<'db> {
488 let node = self.find_file(node.clone());
489 let resolver = self.analyze2(node.as_ref(), Some(offset)).resolver;
490 SemanticsScope { db: self.db, resolver }
491 }
492
493 fn scope_for_def(&self, def: Trait) -> SemanticsScope<'db> {
494 let resolver = def.id.resolver(self.db.upcast());
495 SemanticsScope { db: self.db, resolver }
496 }
497
498 fn analyze(&self, node: &SyntaxNode) -> SourceAnalyzer {
499 let src = self.find_file(node.clone());
500 self.analyze2(src.as_ref(), None)
501 }
502
503 fn analyze2(&self, src: InFile<&SyntaxNode>, offset: Option<TextSize>) -> SourceAnalyzer {
504 let _p = profile("Semantics::analyze2");
505
506 let container = match self.with_ctx(|ctx| ctx.find_container(src)) {
507 Some(it) => it,
508 None => return SourceAnalyzer::new_for_resolver(Resolver::default(), src),
509 };
510
511 let resolver = match container {
512 ChildContainer::DefWithBodyId(def) => {
513 return SourceAnalyzer::new_for_body(self.db, def, src, offset)
514 }
515 ChildContainer::TraitId(it) => it.resolver(self.db.upcast()),
516 ChildContainer::ImplId(it) => it.resolver(self.db.upcast()),
517 ChildContainer::ModuleId(it) => it.resolver(self.db.upcast()),
518 ChildContainer::EnumId(it) => it.resolver(self.db.upcast()),
519 ChildContainer::VariantId(it) => it.resolver(self.db.upcast()),
520 ChildContainer::TypeAliasId(it) => it.resolver(self.db.upcast()),
521 ChildContainer::GenericDefId(it) => it.resolver(self.db.upcast()),
522 };
523 SourceAnalyzer::new_for_resolver(resolver, src)
524 }
525
526 fn cache(&self, root_node: SyntaxNode, file_id: HirFileId) {
527 assert!(root_node.parent().is_none());
528 let mut cache = self.cache.borrow_mut();
529 let prev = cache.insert(root_node, file_id);
530 assert!(prev == None || prev == Some(file_id))
531 }
532
533 fn assert_contains_node(&self, node: &SyntaxNode) {
534 self.find_file(node.clone());
535 }
536
537 fn lookup(&self, root_node: &SyntaxNode) -> Option<HirFileId> {
538 let cache = self.cache.borrow();
539 cache.get(root_node).copied()
540 }
541
542 fn find_file(&self, node: SyntaxNode) -> InFile<SyntaxNode> {
543 let root_node = find_root(&node);
544 let file_id = self.lookup(&root_node).unwrap_or_else(|| {
545 panic!(
546 "\n\nFailed to lookup {:?} in this Semantics.\n\
547 Make sure to use only query nodes, derived from this instance of Semantics.\n\
548 root node: {:?}\n\
549 known nodes: {}\n\n",
550 node,
551 root_node,
552 self.cache
553 .borrow()
554 .keys()
555 .map(|it| format!("{:?}", it))
556 .collect::<Vec<_>>()
557 .join(", ")
558 )
559 });
560 InFile::new(file_id, node)
561 }
562}
563
564pub trait ToDef: AstNode + Clone {
565 type Def;
566
567 fn to_def(sema: &SemanticsImpl, src: InFile<Self>) -> Option<Self::Def>;
568}
569
570macro_rules! to_def_impls {
571 ($(($def:path, $ast:path, $meth:ident)),* ,) => {$(
572 impl ToDef for $ast {
573 type Def = $def;
574 fn to_def(sema: &SemanticsImpl, src: InFile<Self>) -> Option<Self::Def> {
575 sema.with_ctx(|ctx| ctx.$meth(src)).map(<$def>::from)
576 }
577 }
578 )*}
579}
580
581to_def_impls![
582 (crate::Module, ast::Module, module_to_def),
583 (crate::Struct, ast::Struct, struct_to_def),
584 (crate::Enum, ast::Enum, enum_to_def),
585 (crate::Union, ast::Union, union_to_def),
586 (crate::Trait, ast::Trait, trait_to_def),
587 (crate::ImplDef, ast::Impl, impl_to_def),
588 (crate::TypeAlias, ast::TypeAlias, type_alias_to_def),
589 (crate::Const, ast::Const, const_to_def),
590 (crate::Static, ast::Static, static_to_def),
591 (crate::Function, ast::Fn, fn_to_def),
592 (crate::Field, ast::RecordField, record_field_to_def),
593 (crate::Field, ast::TupleField, tuple_field_to_def),
594 (crate::EnumVariant, ast::Variant, enum_variant_to_def),
595 (crate::TypeParam, ast::TypeParam, type_param_to_def),
596 (crate::MacroDef, ast::MacroCall, macro_call_to_def), // this one is dubious, not all calls are macros
597 (crate::Local, ast::IdentPat, bind_pat_to_def),
598];
599
600fn find_root(node: &SyntaxNode) -> SyntaxNode {
601 node.ancestors().last().unwrap()
602}
603
604#[derive(Debug)]
605pub struct SemanticsScope<'a> {
606 pub db: &'a dyn HirDatabase,
607 resolver: Resolver,
608}
609
610impl<'a> SemanticsScope<'a> {
611 pub fn module(&self) -> Option<Module> {
612 Some(Module { id: self.resolver.module()? })
613 }
614
615 /// Note: `FxHashSet<TraitId>` should be treated as an opaque type, passed into `Type
616 // FIXME: rename to visible_traits to not repeat scope?
617 pub fn traits_in_scope(&self) -> FxHashSet<TraitId> {
618 let resolver = &self.resolver;
619 resolver.traits_in_scope(self.db.upcast())
620 }
621
622 pub fn process_all_names(&self, f: &mut dyn FnMut(Name, ScopeDef)) {
623 let resolver = &self.resolver;
624
625 resolver.process_all_names(self.db.upcast(), &mut |name, def| {
626 let def = match def {
627 resolver::ScopeDef::PerNs(it) => {
628 let items = ScopeDef::all_items(it);
629 for item in items {
630 f(name.clone(), item);
631 }
632 return;
633 }
634 resolver::ScopeDef::ImplSelfType(it) => ScopeDef::ImplSelfType(it.into()),
635 resolver::ScopeDef::AdtSelfType(it) => ScopeDef::AdtSelfType(it.into()),
636 resolver::ScopeDef::GenericParam(id) => ScopeDef::GenericParam(TypeParam { id }),
637 resolver::ScopeDef::Local(pat_id) => {
638 let parent = resolver.body_owner().unwrap().into();
639 ScopeDef::Local(Local { parent, pat_id })
640 }
641 };
642 f(name, def)
643 })
644 }
645
646 pub fn resolve_hir_path(&self, path: &Path) -> Option<PathResolution> {
647 resolve_hir_path(self.db, &self.resolver, path)
648 }
649
650 /// Resolves a path where we know it is a qualifier of another path.
651 ///
652 /// For example, if we have:
653 /// ```
654 /// mod my {
655 /// pub mod foo {
656 /// struct Bar;
657 /// }
658 ///
659 /// pub fn foo() {}
660 /// }
661 /// ```
662 /// then we know that `foo` in `my::foo::Bar` refers to the module, not the function.
663 pub fn resolve_hir_path_qualifier(&self, path: &Path) -> Option<PathResolution> {
664 resolve_hir_path_qualifier(self.db, &self.resolver, path)
665 }
666}
667
668// FIXME: Change `HasSource` trait to work with `Semantics` and remove this?
669pub fn original_range(db: &dyn HirDatabase, node: InFile<&SyntaxNode>) -> FileRange {
670 if let Some(range) = original_range_opt(db, node) {
671 let original_file = range.file_id.original_file(db.upcast());
672 if range.file_id == original_file.into() {
673 return FileRange { file_id: original_file, range: range.value };
674 }
675
676 log::error!("Fail to mapping up more for {:?}", range);
677 return FileRange { file_id: range.file_id.original_file(db.upcast()), range: range.value };
678 }
679
680 // Fall back to whole macro call
681 if let Some(expansion) = node.file_id.expansion_info(db.upcast()) {
682 if let Some(call_node) = expansion.call_node() {
683 return FileRange {
684 file_id: call_node.file_id.original_file(db.upcast()),
685 range: call_node.value.text_range(),
686 };
687 }
688 }
689
690 FileRange { file_id: node.file_id.original_file(db.upcast()), range: node.value.text_range() }
691}
692
693fn original_range_opt(
694 db: &dyn HirDatabase,
695 node: InFile<&SyntaxNode>,
696) -> Option<InFile<TextRange>> {
697 let expansion = node.file_id.expansion_info(db.upcast())?;
698
699 // the input node has only one token ?
700 let single = skip_trivia_token(node.value.first_token()?, Direction::Next)?
701 == skip_trivia_token(node.value.last_token()?, Direction::Prev)?;
702
703 Some(node.value.descendants().find_map(|it| {
704 let first = skip_trivia_token(it.first_token()?, Direction::Next)?;
705 let first = ascend_call_token(db, &expansion, node.with_value(first))?;
706
707 let last = skip_trivia_token(it.last_token()?, Direction::Prev)?;
708 let last = ascend_call_token(db, &expansion, node.with_value(last))?;
709
710 if (!single && first == last) || (first.file_id != last.file_id) {
711 return None;
712 }
713
714 Some(first.with_value(first.value.text_range().cover(last.value.text_range())))
715 })?)
716}
717
718fn ascend_call_token(
719 db: &dyn HirDatabase,
720 expansion: &ExpansionInfo,
721 token: InFile<SyntaxToken>,
722) -> Option<InFile<SyntaxToken>> {
723 let (mapped, origin) = expansion.map_token_up(token.as_ref())?;
724 if origin != Origin::Call {
725 return None;
726 }
727 if let Some(info) = mapped.file_id.expansion_info(db.upcast()) {
728 return ascend_call_token(db, &info, mapped);
729 }
730 Some(mapped)
731}