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, ImplDef, 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::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()))
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 // FIXME: Replace the SyntaxToken with a typed ast Node/Token
182 pub fn resolve_lifetime_param(&self, lifetime_token: &SyntaxToken) -> Option<LifetimeParam> {
183 self.imp.resolve_lifetime_param(lifetime_token)
186 pub fn type_of_expr(&self, expr: &ast::Expr) -> Option<Type> {
187 self.imp.type_of_expr(expr)
190 pub fn type_of_pat(&self, pat: &ast::Pat) -> Option<Type> {
191 self.imp.type_of_pat(pat)
194 pub fn type_of_self(&self, param: &ast::SelfParam) -> Option<Type> {
195 self.imp.type_of_self(param)
198 pub fn resolve_method_call(&self, call: &ast::MethodCallExpr) -> Option<Function> {
199 self.imp.resolve_method_call(call).map(Function::from)
202 pub fn resolve_method_call_as_callable(&self, call: &ast::MethodCallExpr) -> Option<Callable> {
203 self.imp.resolve_method_call_as_callable(call)
206 pub fn resolve_field(&self, field: &ast::FieldExpr) -> Option<Field> {
207 self.imp.resolve_field(field)
210 pub fn resolve_record_field(
212 field: &ast::RecordExprField,
213 ) -> Option<(Field, Option<Local>)> {
214 self.imp.resolve_record_field(field)
217 pub fn resolve_record_pat_field(&self, field: &ast::RecordPatField) -> Option<Field> {
218 self.imp.resolve_record_pat_field(field)
221 pub fn resolve_macro_call(&self, macro_call: &ast::MacroCall) -> Option<MacroDef> {
222 self.imp.resolve_macro_call(macro_call)
225 pub fn resolve_path(&self, path: &ast::Path) -> Option<PathResolution> {
226 self.imp.resolve_path(path)
229 pub fn resolve_extern_crate(&self, extern_crate: &ast::ExternCrate) -> Option<Crate> {
230 self.imp.resolve_extern_crate(extern_crate)
233 pub fn resolve_variant(&self, record_lit: ast::RecordExpr) -> Option<VariantDef> {
234 self.imp.resolve_variant(record_lit).map(VariantDef::from)
237 pub fn resolve_bind_pat_to_const(&self, pat: &ast::IdentPat) -> Option<ModuleDef> {
238 self.imp.resolve_bind_pat_to_const(pat)
241 // FIXME: use this instead?
242 // pub fn resolve_name_ref(&self, name_ref: &ast::NameRef) -> Option<???>;
244 pub fn record_literal_missing_fields(&self, literal: &ast::RecordExpr) -> Vec<(Field, Type)> {
245 self.imp.record_literal_missing_fields(literal)
248 pub fn record_pattern_missing_fields(&self, pattern: &ast::RecordPat) -> Vec<(Field, Type)> {
249 self.imp.record_pattern_missing_fields(pattern)
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)
257 pub fn to_module_def(&self, file: FileId) -> Option<Module> {
258 self.imp.to_module_def(file)
261 pub fn scope(&self, node: &SyntaxNode) -> SemanticsScope<'db> {
265 pub fn scope_at_offset(&self, node: &SyntaxNode, offset: TextSize) -> SemanticsScope<'db> {
266 self.imp.scope_at_offset(node, offset)
269 pub fn scope_for_def(&self, def: Trait) -> SemanticsScope<'db> {
270 self.imp.scope_for_def(def)
273 pub fn assert_contains_node(&self, node: &SyntaxNode) {
274 self.imp.assert_contains_node(node)
277 pub fn is_unsafe_method_call(&self, method_call_expr: &ast::MethodCallExpr) -> bool {
278 self.imp.is_unsafe_method_call(method_call_expr)
281 pub fn is_unsafe_ref_expr(&self, ref_expr: &ast::RefExpr) -> bool {
282 self.imp.is_unsafe_ref_expr(ref_expr)
285 pub fn is_unsafe_ident_pat(&self, ident_pat: &ast::IdentPat) -> bool {
286 self.imp.is_unsafe_ident_pat(ident_pat)
290 impl<'db> SemanticsImpl<'db> {
291 fn new(db: &'db dyn HirDatabase) -> Self {
294 s2d_cache: Default::default(),
295 cache: Default::default(),
296 expansion_info_cache: Default::default(),
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());
306 fn expand(&self, macro_call: &ast::MacroCall) -> Option<SyntaxNode> {
307 let sa = self.analyze(macro_call.syntax());
308 let file_id = sa.expand(self.db, InFile::new(sa.file_id, macro_call))?;
309 let node = self.db.parse_or_expand(file_id)?;
310 self.cache(node.clone(), file_id);
314 fn speculative_expand(
316 actual_macro_call: &ast::MacroCall,
317 hypothetical_args: &ast::TokenTree,
318 token_to_map: SyntaxToken,
319 ) -> Option<(SyntaxNode, SyntaxToken)> {
320 let sa = self.analyze(actual_macro_call.syntax());
321 let macro_call = InFile::new(sa.file_id, actual_macro_call);
322 let krate = sa.resolver.krate()?;
323 let macro_call_id = macro_call.as_call_id(self.db.upcast(), krate, |path| {
324 sa.resolver.resolve_path_as_macro(self.db.upcast(), &path)
326 hir_expand::db::expand_hypothetical(
334 fn descend_into_macros(&self, token: SyntaxToken) -> SyntaxToken {
335 let _p = profile::span("descend_into_macros");
336 let parent = token.parent();
337 let sa = self.analyze(&parent);
339 let token = successors(Some(InFile::new(sa.file_id, token)), |token| {
340 self.db.check_canceled();
341 let macro_call = token.value.ancestors().find_map(ast::MacroCall::cast)?;
342 let tt = macro_call.token_tree()?;
343 if !tt.syntax().text_range().contains_range(token.value.text_range()) {
346 let file_id = sa.expand(self.db, token.with_value(¯o_call))?;
348 .expansion_info_cache
351 .or_insert_with(|| file_id.expansion_info(self.db.upcast()))
353 .map_token_down(token.as_ref())?;
355 self.cache(find_root(&token.value.parent()), token.file_id);
365 fn descend_node_at_offset(
369 ) -> impl Iterator<Item = SyntaxNode> + '_ {
370 // Handle macro token cases
371 node.token_at_offset(offset)
372 .map(|token| self.descend_into_macros(token))
373 .map(|it| self.ancestors_with_macros(it.parent()))
377 fn original_range(&self, node: &SyntaxNode) -> FileRange {
378 let node = self.find_file(node.clone());
379 node.as_ref().original_file_range(self.db.upcast())
382 fn diagnostics_display_range(&self, diagnostics: &dyn Diagnostic) -> FileRange {
383 let src = diagnostics.display_source();
384 let root = self.db.parse_or_expand(src.file_id).unwrap();
385 let node = src.value.to_node(&root);
386 self.cache(root, src.file_id);
387 src.with_value(&node).original_file_range(self.db.upcast())
390 fn ancestors_with_macros(&self, node: SyntaxNode) -> impl Iterator<Item = SyntaxNode> + '_ {
391 let node = self.find_file(node);
392 node.ancestors_with_macros(self.db.upcast()).map(|it| it.value)
395 fn ancestors_at_offset_with_macros(
399 ) -> impl Iterator<Item = SyntaxNode> + '_ {
400 node.token_at_offset(offset)
401 .map(|token| self.ancestors_with_macros(token.parent()))
402 .kmerge_by(|node1, node2| node1.text_range().len() < node2.text_range().len())
405 // FIXME: Replace the SyntaxToken with a typed ast Node/Token
406 fn resolve_lifetime_param(&self, lifetime_token: &SyntaxToken) -> Option<LifetimeParam> {
407 if lifetime_token.kind() != syntax::SyntaxKind::LIFETIME {
410 let lifetime_text = lifetime_token.text();
411 let lifetime_param = lifetime_token.parent().ancestors().find_map(|syn| {
412 let gpl = match_ast! {
414 ast::Fn(it) => it.generic_param_list()?,
415 ast::TypeAlias(it) => it.generic_param_list()?,
416 ast::Struct(it) => it.generic_param_list()?,
417 ast::Enum(it) => it.generic_param_list()?,
418 ast::Union(it) => it.generic_param_list()?,
419 ast::Trait(it) => it.generic_param_list()?,
420 ast::Impl(it) => it.generic_param_list()?,
421 ast::WherePred(it) => it.generic_param_list()?,
422 ast::ForType(it) => it.generic_param_list()?,
426 gpl.lifetime_params()
427 .find(|tp| tp.lifetime_token().as_ref().map(|lt| lt.text()) == Some(lifetime_text))
429 let src = self.find_file(lifetime_param.syntax().clone()).with_value(lifetime_param);
430 ToDef::to_def(self, src)
433 fn type_of_expr(&self, expr: &ast::Expr) -> Option<Type> {
434 self.analyze(expr.syntax()).type_of_expr(self.db, expr)
437 fn type_of_pat(&self, pat: &ast::Pat) -> Option<Type> {
438 self.analyze(pat.syntax()).type_of_pat(self.db, pat)
441 fn type_of_self(&self, param: &ast::SelfParam) -> Option<Type> {
442 self.analyze(param.syntax()).type_of_self(self.db, param)
445 fn resolve_method_call(&self, call: &ast::MethodCallExpr) -> Option<FunctionId> {
446 self.analyze(call.syntax()).resolve_method_call(self.db, call)
449 fn resolve_method_call_as_callable(&self, call: &ast::MethodCallExpr) -> Option<Callable> {
450 // FIXME: this erases Substs
451 let func = self.resolve_method_call(call)?;
452 let ty = self.db.value_ty(func.into());
453 let resolver = self.analyze(call.syntax()).resolver;
454 let ty = Type::new_with_resolver(self.db, &resolver, ty.value)?;
455 let mut res = ty.as_callable(self.db)?;
456 res.is_bound_method = true;
460 fn resolve_field(&self, field: &ast::FieldExpr) -> Option<Field> {
461 self.analyze(field.syntax()).resolve_field(self.db, field)
464 fn resolve_record_field(&self, field: &ast::RecordExprField) -> Option<(Field, Option<Local>)> {
465 self.analyze(field.syntax()).resolve_record_field(self.db, field)
468 fn resolve_record_pat_field(&self, field: &ast::RecordPatField) -> Option<Field> {
469 self.analyze(field.syntax()).resolve_record_pat_field(self.db, field)
472 fn resolve_macro_call(&self, macro_call: &ast::MacroCall) -> Option<MacroDef> {
473 let sa = self.analyze(macro_call.syntax());
474 let macro_call = self.find_file(macro_call.syntax().clone()).with_value(macro_call);
475 sa.resolve_macro_call(self.db, macro_call)
478 fn resolve_path(&self, path: &ast::Path) -> Option<PathResolution> {
479 self.analyze(path.syntax()).resolve_path(self.db, path)
482 fn resolve_extern_crate(&self, extern_crate: &ast::ExternCrate) -> Option<Crate> {
483 let krate = self.scope(extern_crate.syntax()).krate()?;
484 krate.dependencies(self.db).into_iter().find_map(|dep| {
485 if dep.name == extern_crate.name_ref()?.as_name() {
493 fn resolve_variant(&self, record_lit: ast::RecordExpr) -> Option<VariantId> {
494 self.analyze(record_lit.syntax()).resolve_variant(self.db, record_lit)
497 fn resolve_bind_pat_to_const(&self, pat: &ast::IdentPat) -> Option<ModuleDef> {
498 self.analyze(pat.syntax()).resolve_bind_pat_to_const(self.db, pat)
501 fn record_literal_missing_fields(&self, literal: &ast::RecordExpr) -> Vec<(Field, Type)> {
502 self.analyze(literal.syntax())
503 .record_literal_missing_fields(self.db, literal)
507 fn record_pattern_missing_fields(&self, pattern: &ast::RecordPat) -> Vec<(Field, Type)> {
508 self.analyze(pattern.syntax())
509 .record_pattern_missing_fields(self.db, pattern)
513 fn with_ctx<F: FnOnce(&mut SourceToDefCtx) -> T, T>(&self, f: F) -> T {
514 let mut cache = self.s2d_cache.borrow_mut();
515 let mut ctx = SourceToDefCtx { db: self.db, cache: &mut *cache };
519 fn to_module_def(&self, file: FileId) -> Option<Module> {
520 self.with_ctx(|ctx| ctx.file_to_def(file)).map(Module::from)
523 fn scope(&self, node: &SyntaxNode) -> SemanticsScope<'db> {
524 let sa = self.analyze(node);
525 SemanticsScope { db: self.db, file_id: sa.file_id, resolver: sa.resolver }
528 fn scope_at_offset(&self, node: &SyntaxNode, offset: TextSize) -> SemanticsScope<'db> {
529 let sa = self.analyze_with_offset(node, offset);
530 SemanticsScope { db: self.db, file_id: sa.file_id, resolver: sa.resolver }
533 fn scope_for_def(&self, def: Trait) -> SemanticsScope<'db> {
534 let file_id = self.db.lookup_intern_trait(def.id).id.file_id;
535 let resolver = def.id.resolver(self.db.upcast());
536 SemanticsScope { db: self.db, file_id, resolver }
539 fn analyze(&self, node: &SyntaxNode) -> SourceAnalyzer {
540 self.analyze_impl(node, None)
542 fn analyze_with_offset(&self, node: &SyntaxNode, offset: TextSize) -> SourceAnalyzer {
543 self.analyze_impl(node, Some(offset))
545 fn analyze_impl(&self, node: &SyntaxNode, offset: Option<TextSize>) -> SourceAnalyzer {
546 let _p = profile::span("Semantics::analyze_impl");
547 let node = self.find_file(node.clone());
548 let node = node.as_ref();
550 let container = match self.with_ctx(|ctx| ctx.find_container(node)) {
552 None => return SourceAnalyzer::new_for_resolver(Resolver::default(), node),
555 let resolver = match container {
556 ChildContainer::DefWithBodyId(def) => {
557 return SourceAnalyzer::new_for_body(self.db, def, node, offset)
559 ChildContainer::TraitId(it) => it.resolver(self.db.upcast()),
560 ChildContainer::ImplId(it) => it.resolver(self.db.upcast()),
561 ChildContainer::ModuleId(it) => it.resolver(self.db.upcast()),
562 ChildContainer::EnumId(it) => it.resolver(self.db.upcast()),
563 ChildContainer::VariantId(it) => it.resolver(self.db.upcast()),
564 ChildContainer::TypeAliasId(it) => it.resolver(self.db.upcast()),
565 ChildContainer::GenericDefId(it) => it.resolver(self.db.upcast()),
567 SourceAnalyzer::new_for_resolver(resolver, node)
570 fn cache(&self, root_node: SyntaxNode, file_id: HirFileId) {
571 assert!(root_node.parent().is_none());
572 let mut cache = self.cache.borrow_mut();
573 let prev = cache.insert(root_node, file_id);
574 assert!(prev == None || prev == Some(file_id))
577 fn assert_contains_node(&self, node: &SyntaxNode) {
578 self.find_file(node.clone());
581 fn lookup(&self, root_node: &SyntaxNode) -> Option<HirFileId> {
582 let cache = self.cache.borrow();
583 cache.get(root_node).copied()
586 fn find_file(&self, node: SyntaxNode) -> InFile<SyntaxNode> {
587 let root_node = find_root(&node);
588 let file_id = self.lookup(&root_node).unwrap_or_else(|| {
590 "\n\nFailed to lookup {:?} in this Semantics.\n\
591 Make sure to use only query nodes, derived from this instance of Semantics.\n\
593 known nodes: {}\n\n",
599 .map(|it| format!("{:?}", it))
604 InFile::new(file_id, node)
607 fn is_unsafe_method_call(&self, method_call_expr: &ast::MethodCallExpr) -> bool {
611 let field_expr = match expr {
612 ast::Expr::FieldExpr(field_expr) => field_expr,
615 let ty = self.type_of_expr(&field_expr.expr()?)?;
616 if !ty.is_packed(self.db) {
620 let func = self.resolve_method_call(&method_call_expr).map(Function::from)?;
621 let res = match func.self_param(self.db)?.access(self.db) {
622 Access::Shared | Access::Exclusive => true,
623 Access::Owned => false,
630 fn is_unsafe_ref_expr(&self, ref_expr: &ast::RefExpr) -> bool {
634 let field_expr = match expr {
635 ast::Expr::FieldExpr(field_expr) => field_expr,
638 let expr = field_expr.expr()?;
639 self.type_of_expr(&expr)
641 // Binding a reference to a packed type is possibly unsafe.
642 .map(|ty| ty.is_packed(self.db))
645 // FIXME This needs layout computation to be correct. It will highlight
646 // more than it should with the current implementation.
649 fn is_unsafe_ident_pat(&self, ident_pat: &ast::IdentPat) -> bool {
650 if !ident_pat.ref_token().is_some() {
658 // `IdentPat` can live under `RecordPat` directly under `RecordPatField` or
659 // `RecordPatFieldList`. `RecordPatField` also lives under `RecordPatFieldList`,
660 // so this tries to lookup the `IdentPat` anywhere along that structure to the
661 // `RecordPat` so we can get the containing type.
662 let record_pat = ast::RecordPatField::cast(parent.clone())
663 .and_then(|record_pat| record_pat.syntax().parent())
664 .or_else(|| Some(parent.clone()))
666 ast::RecordPatFieldList::cast(parent)?
669 .and_then(ast::RecordPat::cast)
672 // If this doesn't match a `RecordPat`, fallback to a `LetStmt` to see if
673 // this is initialized from a `FieldExpr`.
674 if let Some(record_pat) = record_pat {
675 self.type_of_pat(&ast::Pat::RecordPat(record_pat))
676 } else if let Some(let_stmt) = ast::LetStmt::cast(parent) {
677 let field_expr = match let_stmt.initializer()? {
678 ast::Expr::FieldExpr(field_expr) => field_expr,
682 self.type_of_expr(&field_expr.expr()?)
687 // Binding a reference to a packed type is possibly unsafe.
688 .map(|ty| ty.is_packed(self.db))
693 pub trait ToDef: AstNode + Clone {
696 fn to_def(sema: &SemanticsImpl, src: InFile<Self>) -> Option<Self::Def>;
699 macro_rules! to_def_impls {
700 ($(($def:path, $ast:path, $meth:ident)),* ,) => {$(
701 impl ToDef for $ast {
703 fn to_def(sema: &SemanticsImpl, src: InFile<Self>) -> Option<Self::Def> {
704 sema.with_ctx(|ctx| ctx.$meth(src)).map(<$def>::from)
711 (crate::Module, ast::Module, module_to_def),
712 (crate::Struct, ast::Struct, struct_to_def),
713 (crate::Enum, ast::Enum, enum_to_def),
714 (crate::Union, ast::Union, union_to_def),
715 (crate::Trait, ast::Trait, trait_to_def),
716 (crate::ImplDef, ast::Impl, impl_to_def),
717 (crate::TypeAlias, ast::TypeAlias, type_alias_to_def),
718 (crate::Const, ast::Const, const_to_def),
719 (crate::Static, ast::Static, static_to_def),
720 (crate::Function, ast::Fn, fn_to_def),
721 (crate::Field, ast::RecordField, record_field_to_def),
722 (crate::Field, ast::TupleField, tuple_field_to_def),
723 (crate::EnumVariant, ast::Variant, enum_variant_to_def),
724 (crate::TypeParam, ast::TypeParam, type_param_to_def),
725 (crate::LifetimeParam, ast::LifetimeParam, lifetime_param_to_def),
726 (crate::MacroDef, ast::MacroRules, macro_rules_to_def),
727 (crate::Local, ast::IdentPat, bind_pat_to_def),
730 fn find_root(node: &SyntaxNode) -> SyntaxNode {
731 node.ancestors().last().unwrap()
734 /// `SemanticScope` encapsulates the notion of a scope (the set of visible
735 /// names) at a particular program point.
737 /// It is a bit tricky, as scopes do not really exist inside the compiler.
738 /// Rather, the compiler directly computes for each reference the definition it
739 /// refers to. It might transiently compute the explicit scope map while doing
740 /// so, but, generally, this is not something left after the analysis.
742 /// However, we do very much need explicit scopes for IDE purposes --
743 /// completion, at its core, lists the contents of the current scope. The notion
744 /// of scope is also useful to answer questions like "what would be the meaning
745 /// of this piece of code if we inserted it into this position?".
747 /// So `SemanticsScope` is constructed from a specific program point (a syntax
748 /// node or just a raw offset) and provides access to the set of visible names
749 /// on a somewhat best-effort basis.
751 /// Note that if you are wondering "what does this specific existing name mean?",
752 /// you'd better use the `resolve_` family of methods.
754 pub struct SemanticsScope<'a> {
755 pub db: &'a dyn HirDatabase,
760 impl<'a> SemanticsScope<'a> {
761 pub fn module(&self) -> Option<Module> {
762 Some(Module { id: self.resolver.module()? })
765 pub fn krate(&self) -> Option<Crate> {
766 Some(Crate { id: self.resolver.krate()? })
769 /// Note: `FxHashSet<TraitId>` should be treated as an opaque type, passed into `Type
770 // FIXME: rename to visible_traits to not repeat scope?
771 pub fn traits_in_scope(&self) -> FxHashSet<TraitId> {
772 let resolver = &self.resolver;
773 resolver.traits_in_scope(self.db.upcast())
776 pub fn process_all_names(&self, f: &mut dyn FnMut(Name, ScopeDef)) {
777 let resolver = &self.resolver;
779 resolver.process_all_names(self.db.upcast(), &mut |name, def| {
780 let def = match def {
781 resolver::ScopeDef::PerNs(it) => {
782 let items = ScopeDef::all_items(it);
784 f(name.clone(), item);
788 resolver::ScopeDef::ImplSelfType(it) => ScopeDef::ImplSelfType(it.into()),
789 resolver::ScopeDef::AdtSelfType(it) => ScopeDef::AdtSelfType(it.into()),
790 resolver::ScopeDef::GenericParam(id) => ScopeDef::GenericParam(TypeParam { id }),
791 resolver::ScopeDef::Local(pat_id) => {
792 let parent = resolver.body_owner().unwrap().into();
793 ScopeDef::Local(Local { parent, pat_id })
800 /// Resolve a path as-if it was written at the given scope. This is
801 /// necessary a heuristic, as it doesn't take hygiene into account.
802 pub fn speculative_resolve(&self, path: &ast::Path) -> Option<PathResolution> {
803 let hygiene = Hygiene::new(self.db.upcast(), self.file_id);
804 let path = Path::from_src(path.clone(), &hygiene)?;
805 resolve_hir_path(self.db, &self.resolver, &path)