5 use std::{cell::RefCell, fmt, iter::successors};
7 use base_db::{FileId, FileRange};
9 resolver::{self, HasResolver, Resolver, TypeNs},
10 AsMacroCall, FunctionId, TraitId, VariantId,
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};
17 algo::find_node_at_offset,
18 ast::{self, GenericParamsOwner},
19 match_ast, AstNode, SyntaxNode, SyntaxToken, TextSize,
25 diagnostics::Diagnostic,
26 semantics::source_to_def::{ChildContainer, SourceToDefCache, SourceToDefCtx},
27 source_analyzer::{resolve_hir_path, SourceAnalyzer},
28 AssocItem, Callable, Crate, Field, Function, HirFileId, Impl, InFile, LifetimeParam, Local,
29 MacroDef, Module, ModuleDef, Name, Path, ScopeDef, Trait, Type, TypeAlias, TypeParam,
33 #[derive(Debug, Clone, PartialEq, Eq)]
34 pub enum PathResolution {
37 /// A local binding (only value namespace)
39 /// A generic parameter
47 fn in_type_ns(&self) -> Option<TypeNs> {
49 PathResolution::Def(ModuleDef::Adt(adt)) => Some(TypeNs::AdtId((*adt).into())),
50 PathResolution::Def(ModuleDef::BuiltinType(builtin)) => {
51 Some(TypeNs::BuiltinType(*builtin))
53 PathResolution::Def(ModuleDef::Const(_))
54 | PathResolution::Def(ModuleDef::Variant(_))
55 | PathResolution::Def(ModuleDef::Function(_))
56 | PathResolution::Def(ModuleDef::Module(_))
57 | PathResolution::Def(ModuleDef::Static(_))
58 | PathResolution::Def(ModuleDef::Trait(_)) => None,
59 PathResolution::Def(ModuleDef::TypeAlias(alias)) => {
60 Some(TypeNs::TypeAliasId((*alias).into()))
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()))
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>(
78 mut cb: impl FnMut(TypeAlias) -> Option<R>,
80 associated_type_shorthand_candidates(db, self.in_type_ns()?, |_, _, id| cb(id.into()))
84 /// Primary API to get semantic information, like types, from syntax trees.
85 pub struct Semantics<'db, DB> {
87 imp: SemanticsImpl<'db>,
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>>,
97 impl<DB> fmt::Debug for Semantics<'_, DB> {
98 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99 write!(f, "Semantics {{ ... }}")
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_ }
109 pub fn parse(&self, file_id: FileId) -> ast::SourceFile {
110 self.imp.parse(file_id)
113 pub fn expand(&self, macro_call: &ast::MacroCall) -> Option<SyntaxNode> {
114 self.imp.expand(macro_call)
116 pub fn speculative_expand(
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)
125 pub fn descend_into_macros(&self, token: SyntaxToken) -> SyntaxToken {
126 self.imp.descend_into_macros(token)
129 pub fn descend_node_at_offset<N: ast::AstNode>(
134 self.imp.descend_node_at_offset(node, offset).find_map(N::cast)
137 pub fn original_range(&self, node: &SyntaxNode) -> FileRange {
138 self.imp.original_range(node)
141 pub fn diagnostics_display_range(&self, diagnostics: &dyn Diagnostic) -> FileRange {
142 self.imp.diagnostics_display_range(diagnostics)
145 pub fn ancestors_with_macros(&self, node: SyntaxNode) -> impl Iterator<Item = SyntaxNode> + '_ {
146 self.imp.ancestors_with_macros(node)
149 pub fn ancestors_at_offset_with_macros(
153 ) -> impl Iterator<Item = SyntaxNode> + '_ {
154 self.imp.ancestors_at_offset_with_macros(node, offset)
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>(
164 self.imp.ancestors_at_offset_with_macros(node, offset).find_map(N::cast)
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>(
174 if let Some(it) = find_node_at_offset(&node, offset) {
178 self.imp.descend_node_at_offset(node, offset).find_map(N::cast)
181 pub fn resolve_lifetime_param(&self, lifetime: &ast::Lifetime) -> Option<LifetimeParam> {
182 self.imp.resolve_lifetime_param(lifetime)
185 pub fn type_of_expr(&self, expr: &ast::Expr) -> Option<Type> {
186 self.imp.type_of_expr(expr)
189 pub fn type_of_pat(&self, pat: &ast::Pat) -> Option<Type> {
190 self.imp.type_of_pat(pat)
193 pub fn type_of_self(&self, param: &ast::SelfParam) -> Option<Type> {
194 self.imp.type_of_self(param)
197 pub fn resolve_method_call(&self, call: &ast::MethodCallExpr) -> Option<Function> {
198 self.imp.resolve_method_call(call).map(Function::from)
201 pub fn resolve_method_call_as_callable(&self, call: &ast::MethodCallExpr) -> Option<Callable> {
202 self.imp.resolve_method_call_as_callable(call)
205 pub fn resolve_field(&self, field: &ast::FieldExpr) -> Option<Field> {
206 self.imp.resolve_field(field)
209 pub fn resolve_record_field(
211 field: &ast::RecordExprField,
212 ) -> Option<(Field, Option<Local>)> {
213 self.imp.resolve_record_field(field)
216 pub fn resolve_record_pat_field(&self, field: &ast::RecordPatField) -> Option<Field> {
217 self.imp.resolve_record_pat_field(field)
220 pub fn resolve_macro_call(&self, macro_call: &ast::MacroCall) -> Option<MacroDef> {
221 self.imp.resolve_macro_call(macro_call)
224 pub fn resolve_path(&self, path: &ast::Path) -> Option<PathResolution> {
225 self.imp.resolve_path(path)
228 pub fn resolve_extern_crate(&self, extern_crate: &ast::ExternCrate) -> Option<Crate> {
229 self.imp.resolve_extern_crate(extern_crate)
232 pub fn resolve_variant(&self, record_lit: ast::RecordExpr) -> Option<VariantDef> {
233 self.imp.resolve_variant(record_lit).map(VariantDef::from)
236 pub fn resolve_bind_pat_to_const(&self, pat: &ast::IdentPat) -> Option<ModuleDef> {
237 self.imp.resolve_bind_pat_to_const(pat)
240 // FIXME: use this instead?
241 // pub fn resolve_name_ref(&self, name_ref: &ast::NameRef) -> Option<???>;
243 pub fn record_literal_missing_fields(&self, literal: &ast::RecordExpr) -> Vec<(Field, Type)> {
244 self.imp.record_literal_missing_fields(literal)
247 pub fn record_pattern_missing_fields(&self, pattern: &ast::RecordPat) -> Vec<(Field, Type)> {
248 self.imp.record_pattern_missing_fields(pattern)
251 pub fn to_def<T: ToDef>(&self, src: &T) -> Option<T::Def> {
252 let src = self.imp.find_file(src.syntax().clone()).with_value(src).cloned();
253 T::to_def(&self.imp, src)
256 pub fn to_module_def(&self, file: FileId) -> Option<Module> {
257 self.imp.to_module_def(file)
260 pub fn scope(&self, node: &SyntaxNode) -> SemanticsScope<'db> {
264 pub fn scope_at_offset(&self, node: &SyntaxNode, offset: TextSize) -> SemanticsScope<'db> {
265 self.imp.scope_at_offset(node, offset)
268 pub fn scope_for_def(&self, def: Trait) -> SemanticsScope<'db> {
269 self.imp.scope_for_def(def)
272 pub fn assert_contains_node(&self, node: &SyntaxNode) {
273 self.imp.assert_contains_node(node)
276 pub fn is_unsafe_method_call(&self, method_call_expr: &ast::MethodCallExpr) -> bool {
277 self.imp.is_unsafe_method_call(method_call_expr)
280 pub fn is_unsafe_ref_expr(&self, ref_expr: &ast::RefExpr) -> bool {
281 self.imp.is_unsafe_ref_expr(ref_expr)
284 pub fn is_unsafe_ident_pat(&self, ident_pat: &ast::IdentPat) -> bool {
285 self.imp.is_unsafe_ident_pat(ident_pat)
289 impl<'db> SemanticsImpl<'db> {
290 fn new(db: &'db dyn HirDatabase) -> Self {
293 s2d_cache: Default::default(),
294 cache: Default::default(),
295 expansion_info_cache: Default::default(),
299 fn parse(&self, file_id: FileId) -> ast::SourceFile {
300 let tree = self.db.parse(file_id).tree();
301 self.cache(tree.syntax().clone(), file_id.into());
305 fn expand(&self, macro_call: &ast::MacroCall) -> Option<SyntaxNode> {
306 let sa = self.analyze(macro_call.syntax());
307 let file_id = sa.expand(self.db, InFile::new(sa.file_id, macro_call))?;
308 let node = self.db.parse_or_expand(file_id)?;
309 self.cache(node.clone(), file_id);
313 fn speculative_expand(
315 actual_macro_call: &ast::MacroCall,
316 hypothetical_args: &ast::TokenTree,
317 token_to_map: SyntaxToken,
318 ) -> Option<(SyntaxNode, SyntaxToken)> {
319 let sa = self.analyze(actual_macro_call.syntax());
320 let macro_call = InFile::new(sa.file_id, actual_macro_call);
321 let krate = sa.resolver.krate()?;
322 let macro_call_id = macro_call.as_call_id(self.db.upcast(), krate, |path| {
323 sa.resolver.resolve_path_as_macro(self.db.upcast(), &path)
325 hir_expand::db::expand_hypothetical(
333 fn descend_into_macros(&self, token: SyntaxToken) -> SyntaxToken {
334 let _p = profile::span("descend_into_macros");
335 let parent = token.parent();
336 let sa = self.analyze(&parent);
338 let token = successors(Some(InFile::new(sa.file_id, token)), |token| {
339 self.db.check_canceled();
340 let macro_call = token.value.ancestors().find_map(ast::MacroCall::cast)?;
341 let tt = macro_call.token_tree()?;
342 if !tt.syntax().text_range().contains_range(token.value.text_range()) {
345 let file_id = sa.expand(self.db, token.with_value(¯o_call))?;
347 .expansion_info_cache
350 .or_insert_with(|| file_id.expansion_info(self.db.upcast()))
352 .map_token_down(token.as_ref())?;
354 self.cache(find_root(&token.value.parent()), token.file_id);
364 fn descend_node_at_offset(
368 ) -> impl Iterator<Item = SyntaxNode> + '_ {
369 // Handle macro token cases
370 node.token_at_offset(offset)
371 .map(|token| self.descend_into_macros(token))
372 .map(|it| self.ancestors_with_macros(it.parent()))
376 fn original_range(&self, node: &SyntaxNode) -> FileRange {
377 let node = self.find_file(node.clone());
378 node.as_ref().original_file_range(self.db.upcast())
381 fn diagnostics_display_range(&self, diagnostics: &dyn Diagnostic) -> FileRange {
382 let src = diagnostics.display_source();
383 let root = self.db.parse_or_expand(src.file_id).unwrap();
384 let node = src.value.to_node(&root);
385 self.cache(root, src.file_id);
386 src.with_value(&node).original_file_range(self.db.upcast())
389 fn ancestors_with_macros(&self, node: SyntaxNode) -> impl Iterator<Item = SyntaxNode> + '_ {
390 let node = self.find_file(node);
391 node.ancestors_with_macros(self.db.upcast()).map(|it| it.value)
394 fn ancestors_at_offset_with_macros(
398 ) -> impl Iterator<Item = SyntaxNode> + '_ {
399 node.token_at_offset(offset)
400 .map(|token| self.ancestors_with_macros(token.parent()))
401 .kmerge_by(|node1, node2| node1.text_range().len() < node2.text_range().len())
404 fn resolve_lifetime_param(&self, lifetime: &ast::Lifetime) -> Option<LifetimeParam> {
405 let text = lifetime.text();
406 let lifetime_param = lifetime.syntax().ancestors().find_map(|syn| {
407 let gpl = match_ast! {
409 ast::Fn(it) => it.generic_param_list()?,
410 ast::TypeAlias(it) => it.generic_param_list()?,
411 ast::Struct(it) => it.generic_param_list()?,
412 ast::Enum(it) => it.generic_param_list()?,
413 ast::Union(it) => it.generic_param_list()?,
414 ast::Trait(it) => it.generic_param_list()?,
415 ast::Impl(it) => it.generic_param_list()?,
416 ast::WherePred(it) => it.generic_param_list()?,
417 ast::ForType(it) => it.generic_param_list()?,
421 gpl.lifetime_params()
422 .find(|tp| tp.lifetime().as_ref().map(|lt| lt.text()) == Some(text))
424 let src = self.find_file(lifetime_param.syntax().clone()).with_value(lifetime_param);
425 ToDef::to_def(self, src)
428 fn type_of_expr(&self, expr: &ast::Expr) -> Option<Type> {
429 self.analyze(expr.syntax()).type_of_expr(self.db, expr)
432 fn type_of_pat(&self, pat: &ast::Pat) -> Option<Type> {
433 self.analyze(pat.syntax()).type_of_pat(self.db, pat)
436 fn type_of_self(&self, param: &ast::SelfParam) -> Option<Type> {
437 self.analyze(param.syntax()).type_of_self(self.db, param)
440 fn resolve_method_call(&self, call: &ast::MethodCallExpr) -> Option<FunctionId> {
441 self.analyze(call.syntax()).resolve_method_call(self.db, call)
444 fn resolve_method_call_as_callable(&self, call: &ast::MethodCallExpr) -> Option<Callable> {
445 // FIXME: this erases Substs
446 let func = self.resolve_method_call(call)?;
447 let ty = self.db.value_ty(func.into());
448 let resolver = self.analyze(call.syntax()).resolver;
449 let ty = Type::new_with_resolver(self.db, &resolver, ty.value)?;
450 let mut res = ty.as_callable(self.db)?;
451 res.is_bound_method = true;
455 fn resolve_field(&self, field: &ast::FieldExpr) -> Option<Field> {
456 self.analyze(field.syntax()).resolve_field(self.db, field)
459 fn resolve_record_field(&self, field: &ast::RecordExprField) -> Option<(Field, Option<Local>)> {
460 self.analyze(field.syntax()).resolve_record_field(self.db, field)
463 fn resolve_record_pat_field(&self, field: &ast::RecordPatField) -> Option<Field> {
464 self.analyze(field.syntax()).resolve_record_pat_field(self.db, field)
467 fn resolve_macro_call(&self, macro_call: &ast::MacroCall) -> Option<MacroDef> {
468 let sa = self.analyze(macro_call.syntax());
469 let macro_call = self.find_file(macro_call.syntax().clone()).with_value(macro_call);
470 sa.resolve_macro_call(self.db, macro_call)
473 fn resolve_path(&self, path: &ast::Path) -> Option<PathResolution> {
474 self.analyze(path.syntax()).resolve_path(self.db, path)
477 fn resolve_extern_crate(&self, extern_crate: &ast::ExternCrate) -> Option<Crate> {
478 let krate = self.scope(extern_crate.syntax()).krate()?;
479 krate.dependencies(self.db).into_iter().find_map(|dep| {
480 if dep.name == extern_crate.name_ref()?.as_name() {
488 fn resolve_variant(&self, record_lit: ast::RecordExpr) -> Option<VariantId> {
489 self.analyze(record_lit.syntax()).resolve_variant(self.db, record_lit)
492 fn resolve_bind_pat_to_const(&self, pat: &ast::IdentPat) -> Option<ModuleDef> {
493 self.analyze(pat.syntax()).resolve_bind_pat_to_const(self.db, pat)
496 fn record_literal_missing_fields(&self, literal: &ast::RecordExpr) -> Vec<(Field, Type)> {
497 self.analyze(literal.syntax())
498 .record_literal_missing_fields(self.db, literal)
502 fn record_pattern_missing_fields(&self, pattern: &ast::RecordPat) -> Vec<(Field, Type)> {
503 self.analyze(pattern.syntax())
504 .record_pattern_missing_fields(self.db, pattern)
508 fn with_ctx<F: FnOnce(&mut SourceToDefCtx) -> T, T>(&self, f: F) -> T {
509 let mut cache = self.s2d_cache.borrow_mut();
510 let mut ctx = SourceToDefCtx { db: self.db, cache: &mut *cache };
514 fn to_module_def(&self, file: FileId) -> Option<Module> {
515 self.with_ctx(|ctx| ctx.file_to_def(file)).map(Module::from)
518 fn scope(&self, node: &SyntaxNode) -> SemanticsScope<'db> {
519 let sa = self.analyze(node);
520 SemanticsScope { db: self.db, file_id: sa.file_id, resolver: sa.resolver }
523 fn scope_at_offset(&self, node: &SyntaxNode, offset: TextSize) -> SemanticsScope<'db> {
524 let sa = self.analyze_with_offset(node, offset);
525 SemanticsScope { db: self.db, file_id: sa.file_id, resolver: sa.resolver }
528 fn scope_for_def(&self, def: Trait) -> SemanticsScope<'db> {
529 let file_id = self.db.lookup_intern_trait(def.id).id.file_id;
530 let resolver = def.id.resolver(self.db.upcast());
531 SemanticsScope { db: self.db, file_id, resolver }
534 fn analyze(&self, node: &SyntaxNode) -> SourceAnalyzer {
535 self.analyze_impl(node, None)
537 fn analyze_with_offset(&self, node: &SyntaxNode, offset: TextSize) -> SourceAnalyzer {
538 self.analyze_impl(node, Some(offset))
540 fn analyze_impl(&self, node: &SyntaxNode, offset: Option<TextSize>) -> SourceAnalyzer {
541 let _p = profile::span("Semantics::analyze_impl");
542 let node = self.find_file(node.clone());
543 let node = node.as_ref();
545 let container = match self.with_ctx(|ctx| ctx.find_container(node)) {
547 None => return SourceAnalyzer::new_for_resolver(Resolver::default(), node),
550 let resolver = match container {
551 ChildContainer::DefWithBodyId(def) => {
552 return SourceAnalyzer::new_for_body(self.db, def, node, offset)
554 ChildContainer::TraitId(it) => it.resolver(self.db.upcast()),
555 ChildContainer::ImplId(it) => it.resolver(self.db.upcast()),
556 ChildContainer::ModuleId(it) => it.resolver(self.db.upcast()),
557 ChildContainer::EnumId(it) => it.resolver(self.db.upcast()),
558 ChildContainer::VariantId(it) => it.resolver(self.db.upcast()),
559 ChildContainer::TypeAliasId(it) => it.resolver(self.db.upcast()),
560 ChildContainer::GenericDefId(it) => it.resolver(self.db.upcast()),
562 SourceAnalyzer::new_for_resolver(resolver, node)
565 fn cache(&self, root_node: SyntaxNode, file_id: HirFileId) {
566 assert!(root_node.parent().is_none());
567 let mut cache = self.cache.borrow_mut();
568 let prev = cache.insert(root_node, file_id);
569 assert!(prev == None || prev == Some(file_id))
572 fn assert_contains_node(&self, node: &SyntaxNode) {
573 self.find_file(node.clone());
576 fn lookup(&self, root_node: &SyntaxNode) -> Option<HirFileId> {
577 let cache = self.cache.borrow();
578 cache.get(root_node).copied()
581 fn find_file(&self, node: SyntaxNode) -> InFile<SyntaxNode> {
582 let root_node = find_root(&node);
583 let file_id = self.lookup(&root_node).unwrap_or_else(|| {
585 "\n\nFailed to lookup {:?} in this Semantics.\n\
586 Make sure to use only query nodes, derived from this instance of Semantics.\n\
588 known nodes: {}\n\n",
594 .map(|it| format!("{:?}", it))
599 InFile::new(file_id, node)
602 fn is_unsafe_method_call(&self, method_call_expr: &ast::MethodCallExpr) -> bool {
606 let field_expr = match expr {
607 ast::Expr::FieldExpr(field_expr) => field_expr,
610 let ty = self.type_of_expr(&field_expr.expr()?)?;
611 if !ty.is_packed(self.db) {
615 let func = self.resolve_method_call(&method_call_expr).map(Function::from)?;
616 let res = match func.self_param(self.db)?.access(self.db) {
617 Access::Shared | Access::Exclusive => true,
618 Access::Owned => false,
625 fn is_unsafe_ref_expr(&self, ref_expr: &ast::RefExpr) -> bool {
629 let field_expr = match expr {
630 ast::Expr::FieldExpr(field_expr) => field_expr,
633 let expr = field_expr.expr()?;
634 self.type_of_expr(&expr)
636 // Binding a reference to a packed type is possibly unsafe.
637 .map(|ty| ty.is_packed(self.db))
640 // FIXME This needs layout computation to be correct. It will highlight
641 // more than it should with the current implementation.
644 fn is_unsafe_ident_pat(&self, ident_pat: &ast::IdentPat) -> bool {
645 if !ident_pat.ref_token().is_some() {
653 // `IdentPat` can live under `RecordPat` directly under `RecordPatField` or
654 // `RecordPatFieldList`. `RecordPatField` also lives under `RecordPatFieldList`,
655 // so this tries to lookup the `IdentPat` anywhere along that structure to the
656 // `RecordPat` so we can get the containing type.
657 let record_pat = ast::RecordPatField::cast(parent.clone())
658 .and_then(|record_pat| record_pat.syntax().parent())
659 .or_else(|| Some(parent.clone()))
661 ast::RecordPatFieldList::cast(parent)?
664 .and_then(ast::RecordPat::cast)
667 // If this doesn't match a `RecordPat`, fallback to a `LetStmt` to see if
668 // this is initialized from a `FieldExpr`.
669 if let Some(record_pat) = record_pat {
670 self.type_of_pat(&ast::Pat::RecordPat(record_pat))
671 } else if let Some(let_stmt) = ast::LetStmt::cast(parent) {
672 let field_expr = match let_stmt.initializer()? {
673 ast::Expr::FieldExpr(field_expr) => field_expr,
677 self.type_of_expr(&field_expr.expr()?)
682 // Binding a reference to a packed type is possibly unsafe.
683 .map(|ty| ty.is_packed(self.db))
688 pub trait ToDef: AstNode + Clone {
691 fn to_def(sema: &SemanticsImpl, src: InFile<Self>) -> Option<Self::Def>;
694 macro_rules! to_def_impls {
695 ($(($def:path, $ast:path, $meth:ident)),* ,) => {$(
696 impl ToDef for $ast {
698 fn to_def(sema: &SemanticsImpl, src: InFile<Self>) -> Option<Self::Def> {
699 sema.with_ctx(|ctx| ctx.$meth(src)).map(<$def>::from)
706 (crate::Module, ast::Module, module_to_def),
707 (crate::Struct, ast::Struct, struct_to_def),
708 (crate::Enum, ast::Enum, enum_to_def),
709 (crate::Union, ast::Union, union_to_def),
710 (crate::Trait, ast::Trait, trait_to_def),
711 (crate::Impl, ast::Impl, impl_to_def),
712 (crate::TypeAlias, ast::TypeAlias, type_alias_to_def),
713 (crate::Const, ast::Const, const_to_def),
714 (crate::Static, ast::Static, static_to_def),
715 (crate::Function, ast::Fn, fn_to_def),
716 (crate::Field, ast::RecordField, record_field_to_def),
717 (crate::Field, ast::TupleField, tuple_field_to_def),
718 (crate::Variant, ast::Variant, enum_variant_to_def),
719 (crate::TypeParam, ast::TypeParam, type_param_to_def),
720 (crate::LifetimeParam, ast::LifetimeParam, lifetime_param_to_def),
721 (crate::MacroDef, ast::MacroRules, macro_rules_to_def),
722 (crate::Local, ast::IdentPat, bind_pat_to_def),
725 fn find_root(node: &SyntaxNode) -> SyntaxNode {
726 node.ancestors().last().unwrap()
729 /// `SemanticScope` encapsulates the notion of a scope (the set of visible
730 /// names) at a particular program point.
732 /// It is a bit tricky, as scopes do not really exist inside the compiler.
733 /// Rather, the compiler directly computes for each reference the definition it
734 /// refers to. It might transiently compute the explicit scope map while doing
735 /// so, but, generally, this is not something left after the analysis.
737 /// However, we do very much need explicit scopes for IDE purposes --
738 /// completion, at its core, lists the contents of the current scope. The notion
739 /// of scope is also useful to answer questions like "what would be the meaning
740 /// of this piece of code if we inserted it into this position?".
742 /// So `SemanticsScope` is constructed from a specific program point (a syntax
743 /// node or just a raw offset) and provides access to the set of visible names
744 /// on a somewhat best-effort basis.
746 /// Note that if you are wondering "what does this specific existing name mean?",
747 /// you'd better use the `resolve_` family of methods.
749 pub struct SemanticsScope<'a> {
750 pub db: &'a dyn HirDatabase,
755 impl<'a> SemanticsScope<'a> {
756 pub fn module(&self) -> Option<Module> {
757 Some(Module { id: self.resolver.module()? })
760 pub fn krate(&self) -> Option<Crate> {
761 Some(Crate { id: self.resolver.krate()? })
764 /// Note: `FxHashSet<TraitId>` should be treated as an opaque type, passed into `Type
765 // FIXME: rename to visible_traits to not repeat scope?
766 pub fn traits_in_scope(&self) -> FxHashSet<TraitId> {
767 let resolver = &self.resolver;
768 resolver.traits_in_scope(self.db.upcast())
771 pub fn process_all_names(&self, f: &mut dyn FnMut(Name, ScopeDef)) {
772 let resolver = &self.resolver;
774 resolver.process_all_names(self.db.upcast(), &mut |name, def| {
775 let def = match def {
776 resolver::ScopeDef::PerNs(it) => {
777 let items = ScopeDef::all_items(it);
779 f(name.clone(), item);
783 resolver::ScopeDef::ImplSelfType(it) => ScopeDef::ImplSelfType(it.into()),
784 resolver::ScopeDef::AdtSelfType(it) => ScopeDef::AdtSelfType(it.into()),
785 resolver::ScopeDef::GenericParam(id) => ScopeDef::GenericParam(TypeParam { id }),
786 resolver::ScopeDef::Local(pat_id) => {
787 let parent = resolver.body_owner().unwrap().into();
788 ScopeDef::Local(Local { parent, pat_id })
795 /// Resolve a path as-if it was written at the given scope. This is
796 /// necessary a heuristic, as it doesn't take hygiene into account.
797 pub fn speculative_resolve(&self, path: &ast::Path) -> Option<PathResolution> {
798 let hygiene = Hygiene::new(self.db.upcast(), self.file_id);
799 let path = Path::from_src(path.clone(), &hygiene)?;
800 resolve_hir_path(self.db, &self.resolver, &path)