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, LoopBodyOwner},
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, ConstParam, Crate, Field, Function, HirFileId, Impl, InFile, Label,
29 LifetimeParam, Local, MacroDef, Module, ModuleDef, Name, Path, ScopeDef, Trait, Type,
30 TypeAlias, TypeParam, VariantDef,
33 #[derive(Debug, Clone, PartialEq, Eq)]
34 pub enum PathResolution {
37 /// A local binding (only value namespace)
39 /// A generic parameter
41 ConstParam(ConstParam),
48 fn in_type_ns(&self) -> Option<TypeNs> {
50 PathResolution::Def(ModuleDef::Adt(adt)) => Some(TypeNs::AdtId((*adt).into())),
51 PathResolution::Def(ModuleDef::BuiltinType(builtin)) => {
52 Some(TypeNs::BuiltinType(*builtin))
54 PathResolution::Def(ModuleDef::Const(_))
55 | PathResolution::Def(ModuleDef::Variant(_))
56 | PathResolution::Def(ModuleDef::Function(_))
57 | PathResolution::Def(ModuleDef::Module(_))
58 | PathResolution::Def(ModuleDef::Static(_))
59 | PathResolution::Def(ModuleDef::Trait(_)) => None,
60 PathResolution::Def(ModuleDef::TypeAlias(alias)) => {
61 Some(TypeNs::TypeAliasId((*alias).into()))
63 PathResolution::Local(_) | PathResolution::Macro(_) | PathResolution::ConstParam(_) => {
66 PathResolution::TypeParam(param) => Some(TypeNs::GenericParam((*param).into())),
67 PathResolution::SelfType(impl_def) => Some(TypeNs::SelfType((*impl_def).into())),
68 PathResolution::AssocItem(AssocItem::Const(_))
69 | PathResolution::AssocItem(AssocItem::Function(_)) => None,
70 PathResolution::AssocItem(AssocItem::TypeAlias(alias)) => {
71 Some(TypeNs::TypeAliasId((*alias).into()))
76 /// Returns an iterator over associated types that may be specified after this path (using
77 /// `Ty::Assoc` syntax).
78 pub fn assoc_type_shorthand_candidates<R>(
81 mut cb: impl FnMut(TypeAlias) -> Option<R>,
83 associated_type_shorthand_candidates(db, self.in_type_ns()?, |_, _, id| cb(id.into()))
87 /// Primary API to get semantic information, like types, from syntax trees.
88 pub struct Semantics<'db, DB> {
90 imp: SemanticsImpl<'db>,
93 pub struct SemanticsImpl<'db> {
94 pub db: &'db dyn HirDatabase,
95 s2d_cache: RefCell<SourceToDefCache>,
96 expansion_info_cache: RefCell<FxHashMap<HirFileId, Option<ExpansionInfo>>>,
97 cache: RefCell<FxHashMap<SyntaxNode, HirFileId>>,
100 impl<DB> fmt::Debug for Semantics<'_, DB> {
101 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
102 write!(f, "Semantics {{ ... }}")
106 impl<'db, DB: HirDatabase> Semantics<'db, DB> {
107 pub fn new(db: &DB) -> Semantics<DB> {
108 let impl_ = SemanticsImpl::new(db);
109 Semantics { db, imp: impl_ }
112 pub fn parse(&self, file_id: FileId) -> ast::SourceFile {
113 self.imp.parse(file_id)
116 pub fn expand(&self, macro_call: &ast::MacroCall) -> Option<SyntaxNode> {
117 self.imp.expand(macro_call)
119 pub fn speculative_expand(
121 actual_macro_call: &ast::MacroCall,
122 hypothetical_args: &ast::TokenTree,
123 token_to_map: SyntaxToken,
124 ) -> Option<(SyntaxNode, SyntaxToken)> {
125 self.imp.speculative_expand(actual_macro_call, hypothetical_args, token_to_map)
128 pub fn descend_into_macros(&self, token: SyntaxToken) -> SyntaxToken {
129 self.imp.descend_into_macros(token)
132 pub fn descend_node_at_offset<N: ast::AstNode>(
137 self.imp.descend_node_at_offset(node, offset).find_map(N::cast)
140 pub fn original_range(&self, node: &SyntaxNode) -> FileRange {
141 self.imp.original_range(node)
144 pub fn diagnostics_display_range(&self, diagnostics: &dyn Diagnostic) -> FileRange {
145 self.imp.diagnostics_display_range(diagnostics)
148 pub fn ancestors_with_macros(&self, node: SyntaxNode) -> impl Iterator<Item = SyntaxNode> + '_ {
149 self.imp.ancestors_with_macros(node)
152 pub fn ancestors_at_offset_with_macros(
156 ) -> impl Iterator<Item = SyntaxNode> + '_ {
157 self.imp.ancestors_at_offset_with_macros(node, offset)
160 /// Find a AstNode by offset inside SyntaxNode, if it is inside *Macrofile*,
161 /// search up until it is of the target AstNode type
162 pub fn find_node_at_offset_with_macros<N: AstNode>(
167 self.imp.ancestors_at_offset_with_macros(node, offset).find_map(N::cast)
170 /// Find a AstNode by offset inside SyntaxNode, if it is inside *MacroCall*,
171 /// descend it and find again
172 pub fn find_node_at_offset_with_descend<N: AstNode>(
177 if let Some(it) = find_node_at_offset(&node, offset) {
181 self.imp.descend_node_at_offset(node, offset).find_map(N::cast)
184 pub fn resolve_lifetime_param(&self, lifetime: &ast::Lifetime) -> Option<LifetimeParam> {
185 self.imp.resolve_lifetime_param(lifetime)
188 pub fn resolve_label(&self, lifetime: &ast::Lifetime) -> Option<Label> {
189 self.imp.resolve_label(lifetime)
192 pub fn type_of_expr(&self, expr: &ast::Expr) -> Option<Type> {
193 self.imp.type_of_expr(expr)
196 pub fn type_of_pat(&self, pat: &ast::Pat) -> Option<Type> {
197 self.imp.type_of_pat(pat)
200 pub fn type_of_self(&self, param: &ast::SelfParam) -> Option<Type> {
201 self.imp.type_of_self(param)
204 pub fn resolve_method_call(&self, call: &ast::MethodCallExpr) -> Option<Function> {
205 self.imp.resolve_method_call(call).map(Function::from)
208 pub fn resolve_method_call_as_callable(&self, call: &ast::MethodCallExpr) -> Option<Callable> {
209 self.imp.resolve_method_call_as_callable(call)
212 pub fn resolve_field(&self, field: &ast::FieldExpr) -> Option<Field> {
213 self.imp.resolve_field(field)
216 pub fn resolve_record_field(
218 field: &ast::RecordExprField,
219 ) -> Option<(Field, Option<Local>)> {
220 self.imp.resolve_record_field(field)
223 pub fn resolve_record_pat_field(&self, field: &ast::RecordPatField) -> Option<Field> {
224 self.imp.resolve_record_pat_field(field)
227 pub fn resolve_macro_call(&self, macro_call: &ast::MacroCall) -> Option<MacroDef> {
228 self.imp.resolve_macro_call(macro_call)
231 pub fn resolve_path(&self, path: &ast::Path) -> Option<PathResolution> {
232 self.imp.resolve_path(path)
235 pub fn resolve_extern_crate(&self, extern_crate: &ast::ExternCrate) -> Option<Crate> {
236 self.imp.resolve_extern_crate(extern_crate)
239 pub fn resolve_variant(&self, record_lit: ast::RecordExpr) -> Option<VariantDef> {
240 self.imp.resolve_variant(record_lit).map(VariantDef::from)
243 pub fn resolve_bind_pat_to_const(&self, pat: &ast::IdentPat) -> Option<ModuleDef> {
244 self.imp.resolve_bind_pat_to_const(pat)
247 // FIXME: use this instead?
248 // pub fn resolve_name_ref(&self, name_ref: &ast::NameRef) -> Option<???>;
250 pub fn record_literal_missing_fields(&self, literal: &ast::RecordExpr) -> Vec<(Field, Type)> {
251 self.imp.record_literal_missing_fields(literal)
254 pub fn record_pattern_missing_fields(&self, pattern: &ast::RecordPat) -> Vec<(Field, Type)> {
255 self.imp.record_pattern_missing_fields(pattern)
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)
263 pub fn to_module_def(&self, file: FileId) -> Option<Module> {
264 self.imp.to_module_def(file)
267 pub fn scope(&self, node: &SyntaxNode) -> SemanticsScope<'db> {
271 pub fn scope_at_offset(&self, node: &SyntaxNode, offset: TextSize) -> SemanticsScope<'db> {
272 self.imp.scope_at_offset(node, offset)
275 pub fn scope_for_def(&self, def: Trait) -> SemanticsScope<'db> {
276 self.imp.scope_for_def(def)
279 pub fn assert_contains_node(&self, node: &SyntaxNode) {
280 self.imp.assert_contains_node(node)
283 pub fn is_unsafe_method_call(&self, method_call_expr: &ast::MethodCallExpr) -> bool {
284 self.imp.is_unsafe_method_call(method_call_expr)
287 pub fn is_unsafe_ref_expr(&self, ref_expr: &ast::RefExpr) -> bool {
288 self.imp.is_unsafe_ref_expr(ref_expr)
291 pub fn is_unsafe_ident_pat(&self, ident_pat: &ast::IdentPat) -> bool {
292 self.imp.is_unsafe_ident_pat(ident_pat)
296 impl<'db> SemanticsImpl<'db> {
297 fn new(db: &'db dyn HirDatabase) -> Self {
300 s2d_cache: Default::default(),
301 cache: Default::default(),
302 expansion_info_cache: Default::default(),
306 fn parse(&self, file_id: FileId) -> ast::SourceFile {
307 let tree = self.db.parse(file_id).tree();
308 self.cache(tree.syntax().clone(), file_id.into());
312 fn expand(&self, macro_call: &ast::MacroCall) -> Option<SyntaxNode> {
313 let sa = self.analyze(macro_call.syntax());
314 let file_id = sa.expand(self.db, InFile::new(sa.file_id, macro_call))?;
315 let node = self.db.parse_or_expand(file_id)?;
316 self.cache(node.clone(), file_id);
320 fn speculative_expand(
322 actual_macro_call: &ast::MacroCall,
323 hypothetical_args: &ast::TokenTree,
324 token_to_map: SyntaxToken,
325 ) -> Option<(SyntaxNode, SyntaxToken)> {
326 let sa = self.analyze(actual_macro_call.syntax());
327 let macro_call = InFile::new(sa.file_id, actual_macro_call);
328 let krate = sa.resolver.krate()?;
329 let macro_call_id = macro_call.as_call_id(self.db.upcast(), krate, |path| {
330 sa.resolver.resolve_path_as_macro(self.db.upcast(), &path)
332 hir_expand::db::expand_hypothetical(
340 fn descend_into_macros(&self, token: SyntaxToken) -> SyntaxToken {
341 let _p = profile::span("descend_into_macros");
342 let parent = token.parent();
343 let sa = self.analyze(&parent);
345 let token = successors(Some(InFile::new(sa.file_id, token)), |token| {
346 self.db.check_canceled();
347 let macro_call = token.value.ancestors().find_map(ast::MacroCall::cast)?;
348 let tt = macro_call.token_tree()?;
349 if !tt.syntax().text_range().contains_range(token.value.text_range()) {
352 let file_id = sa.expand(self.db, token.with_value(¯o_call))?;
354 .expansion_info_cache
357 .or_insert_with(|| file_id.expansion_info(self.db.upcast()))
359 .map_token_down(token.as_ref())?;
361 self.cache(find_root(&token.value.parent()), token.file_id);
371 fn descend_node_at_offset(
375 ) -> impl Iterator<Item = SyntaxNode> + '_ {
376 // Handle macro token cases
377 node.token_at_offset(offset)
378 .map(|token| self.descend_into_macros(token))
379 .map(|it| self.ancestors_with_macros(it.parent()))
383 fn original_range(&self, node: &SyntaxNode) -> FileRange {
384 let node = self.find_file(node.clone());
385 node.as_ref().original_file_range(self.db.upcast())
388 fn diagnostics_display_range(&self, diagnostics: &dyn Diagnostic) -> FileRange {
389 let src = diagnostics.display_source();
390 let root = self.db.parse_or_expand(src.file_id).unwrap();
391 let node = src.value.to_node(&root);
392 self.cache(root, src.file_id);
393 src.with_value(&node).original_file_range(self.db.upcast())
396 fn ancestors_with_macros(&self, node: SyntaxNode) -> impl Iterator<Item = SyntaxNode> + '_ {
397 let node = self.find_file(node);
398 node.ancestors_with_macros(self.db.upcast()).map(|it| it.value)
401 fn ancestors_at_offset_with_macros(
405 ) -> impl Iterator<Item = SyntaxNode> + '_ {
406 node.token_at_offset(offset)
407 .map(|token| self.ancestors_with_macros(token.parent()))
408 .kmerge_by(|node1, node2| node1.text_range().len() < node2.text_range().len())
411 fn resolve_lifetime_param(&self, lifetime: &ast::Lifetime) -> Option<LifetimeParam> {
412 let text = lifetime.text();
413 let lifetime_param = lifetime.syntax().ancestors().find_map(|syn| {
414 let gpl = match_ast! {
416 ast::Fn(it) => it.generic_param_list()?,
417 ast::TypeAlias(it) => it.generic_param_list()?,
418 ast::Struct(it) => it.generic_param_list()?,
419 ast::Enum(it) => it.generic_param_list()?,
420 ast::Union(it) => it.generic_param_list()?,
421 ast::Trait(it) => it.generic_param_list()?,
422 ast::Impl(it) => it.generic_param_list()?,
423 ast::WherePred(it) => it.generic_param_list()?,
424 ast::ForType(it) => it.generic_param_list()?,
428 gpl.lifetime_params()
429 .find(|tp| tp.lifetime().as_ref().map(|lt| lt.text()) == Some(text))
431 let src = self.find_file(lifetime_param.syntax().clone()).with_value(lifetime_param);
432 ToDef::to_def(self, src)
435 fn resolve_label(&self, lifetime: &ast::Lifetime) -> Option<Label> {
436 let text = lifetime.text();
437 let label = lifetime.syntax().ancestors().find_map(|syn| {
438 let label = match_ast! {
440 ast::ForExpr(it) => it.label(),
441 ast::WhileExpr(it) => it.label(),
442 ast::LoopExpr(it) => it.label(),
443 ast::EffectExpr(it) => it.label(),
449 .and_then(|lt| lt.lifetime_ident_token())
450 .map_or(false, |lt| lt.text() == text)
453 let src = self.find_file(label.syntax().clone()).with_value(label);
454 ToDef::to_def(self, src)
457 fn type_of_expr(&self, expr: &ast::Expr) -> Option<Type> {
458 self.analyze(expr.syntax()).type_of_expr(self.db, expr)
461 fn type_of_pat(&self, pat: &ast::Pat) -> Option<Type> {
462 self.analyze(pat.syntax()).type_of_pat(self.db, pat)
465 fn type_of_self(&self, param: &ast::SelfParam) -> Option<Type> {
466 self.analyze(param.syntax()).type_of_self(self.db, param)
469 fn resolve_method_call(&self, call: &ast::MethodCallExpr) -> Option<FunctionId> {
470 self.analyze(call.syntax()).resolve_method_call(self.db, call)
473 fn resolve_method_call_as_callable(&self, call: &ast::MethodCallExpr) -> Option<Callable> {
474 // FIXME: this erases Substs
475 let func = self.resolve_method_call(call)?;
476 let ty = self.db.value_ty(func.into());
477 let resolver = self.analyze(call.syntax()).resolver;
478 let ty = Type::new_with_resolver(self.db, &resolver, ty.value)?;
479 let mut res = ty.as_callable(self.db)?;
480 res.is_bound_method = true;
484 fn resolve_field(&self, field: &ast::FieldExpr) -> Option<Field> {
485 self.analyze(field.syntax()).resolve_field(self.db, field)
488 fn resolve_record_field(&self, field: &ast::RecordExprField) -> Option<(Field, Option<Local>)> {
489 self.analyze(field.syntax()).resolve_record_field(self.db, field)
492 fn resolve_record_pat_field(&self, field: &ast::RecordPatField) -> Option<Field> {
493 self.analyze(field.syntax()).resolve_record_pat_field(self.db, field)
496 fn resolve_macro_call(&self, macro_call: &ast::MacroCall) -> Option<MacroDef> {
497 let sa = self.analyze(macro_call.syntax());
498 let macro_call = self.find_file(macro_call.syntax().clone()).with_value(macro_call);
499 sa.resolve_macro_call(self.db, macro_call)
502 fn resolve_path(&self, path: &ast::Path) -> Option<PathResolution> {
503 self.analyze(path.syntax()).resolve_path(self.db, path)
506 fn resolve_extern_crate(&self, extern_crate: &ast::ExternCrate) -> Option<Crate> {
507 let krate = self.scope(extern_crate.syntax()).krate()?;
508 krate.dependencies(self.db).into_iter().find_map(|dep| {
509 if dep.name == extern_crate.name_ref()?.as_name() {
517 fn resolve_variant(&self, record_lit: ast::RecordExpr) -> Option<VariantId> {
518 self.analyze(record_lit.syntax()).resolve_variant(self.db, record_lit)
521 fn resolve_bind_pat_to_const(&self, pat: &ast::IdentPat) -> Option<ModuleDef> {
522 self.analyze(pat.syntax()).resolve_bind_pat_to_const(self.db, pat)
525 fn record_literal_missing_fields(&self, literal: &ast::RecordExpr) -> Vec<(Field, Type)> {
526 self.analyze(literal.syntax())
527 .record_literal_missing_fields(self.db, literal)
531 fn record_pattern_missing_fields(&self, pattern: &ast::RecordPat) -> Vec<(Field, Type)> {
532 self.analyze(pattern.syntax())
533 .record_pattern_missing_fields(self.db, pattern)
537 fn with_ctx<F: FnOnce(&mut SourceToDefCtx) -> T, T>(&self, f: F) -> T {
538 let mut cache = self.s2d_cache.borrow_mut();
539 let mut ctx = SourceToDefCtx { db: self.db, cache: &mut *cache };
543 fn to_module_def(&self, file: FileId) -> Option<Module> {
544 self.with_ctx(|ctx| ctx.file_to_def(file)).map(Module::from)
547 fn scope(&self, node: &SyntaxNode) -> SemanticsScope<'db> {
548 let sa = self.analyze(node);
549 SemanticsScope { db: self.db, file_id: sa.file_id, resolver: sa.resolver }
552 fn scope_at_offset(&self, node: &SyntaxNode, offset: TextSize) -> SemanticsScope<'db> {
553 let sa = self.analyze_with_offset(node, offset);
554 SemanticsScope { db: self.db, file_id: sa.file_id, resolver: sa.resolver }
557 fn scope_for_def(&self, def: Trait) -> SemanticsScope<'db> {
558 let file_id = self.db.lookup_intern_trait(def.id).id.file_id;
559 let resolver = def.id.resolver(self.db.upcast());
560 SemanticsScope { db: self.db, file_id, resolver }
563 fn analyze(&self, node: &SyntaxNode) -> SourceAnalyzer {
564 self.analyze_impl(node, None)
566 fn analyze_with_offset(&self, node: &SyntaxNode, offset: TextSize) -> SourceAnalyzer {
567 self.analyze_impl(node, Some(offset))
569 fn analyze_impl(&self, node: &SyntaxNode, offset: Option<TextSize>) -> SourceAnalyzer {
570 let _p = profile::span("Semantics::analyze_impl");
571 let node = self.find_file(node.clone());
572 let node = node.as_ref();
574 let container = match self.with_ctx(|ctx| ctx.find_container(node)) {
576 None => return SourceAnalyzer::new_for_resolver(Resolver::default(), node),
579 let resolver = match container {
580 ChildContainer::DefWithBodyId(def) => {
581 return SourceAnalyzer::new_for_body(self.db, def, node, offset)
583 ChildContainer::TraitId(it) => it.resolver(self.db.upcast()),
584 ChildContainer::ImplId(it) => it.resolver(self.db.upcast()),
585 ChildContainer::ModuleId(it) => it.resolver(self.db.upcast()),
586 ChildContainer::EnumId(it) => it.resolver(self.db.upcast()),
587 ChildContainer::VariantId(it) => it.resolver(self.db.upcast()),
588 ChildContainer::TypeAliasId(it) => it.resolver(self.db.upcast()),
589 ChildContainer::GenericDefId(it) => it.resolver(self.db.upcast()),
591 SourceAnalyzer::new_for_resolver(resolver, node)
594 fn cache(&self, root_node: SyntaxNode, file_id: HirFileId) {
595 assert!(root_node.parent().is_none());
596 let mut cache = self.cache.borrow_mut();
597 let prev = cache.insert(root_node, file_id);
598 assert!(prev == None || prev == Some(file_id))
601 fn assert_contains_node(&self, node: &SyntaxNode) {
602 self.find_file(node.clone());
605 fn lookup(&self, root_node: &SyntaxNode) -> Option<HirFileId> {
606 let cache = self.cache.borrow();
607 cache.get(root_node).copied()
610 fn find_file(&self, node: SyntaxNode) -> InFile<SyntaxNode> {
611 let root_node = find_root(&node);
612 let file_id = self.lookup(&root_node).unwrap_or_else(|| {
614 "\n\nFailed to lookup {:?} in this Semantics.\n\
615 Make sure to use only query nodes, derived from this instance of Semantics.\n\
617 known nodes: {}\n\n",
623 .map(|it| format!("{:?}", it))
628 InFile::new(file_id, node)
631 fn is_unsafe_method_call(&self, method_call_expr: &ast::MethodCallExpr) -> bool {
635 let field_expr = match expr {
636 ast::Expr::FieldExpr(field_expr) => field_expr,
639 let ty = self.type_of_expr(&field_expr.expr()?)?;
640 if !ty.is_packed(self.db) {
644 let func = self.resolve_method_call(&method_call_expr).map(Function::from)?;
645 let res = match func.self_param(self.db)?.access(self.db) {
646 Access::Shared | Access::Exclusive => true,
647 Access::Owned => false,
654 fn is_unsafe_ref_expr(&self, ref_expr: &ast::RefExpr) -> bool {
658 let field_expr = match expr {
659 ast::Expr::FieldExpr(field_expr) => field_expr,
662 let expr = field_expr.expr()?;
663 self.type_of_expr(&expr)
665 // Binding a reference to a packed type is possibly unsafe.
666 .map(|ty| ty.is_packed(self.db))
669 // FIXME This needs layout computation to be correct. It will highlight
670 // more than it should with the current implementation.
673 fn is_unsafe_ident_pat(&self, ident_pat: &ast::IdentPat) -> bool {
674 if !ident_pat.ref_token().is_some() {
682 // `IdentPat` can live under `RecordPat` directly under `RecordPatField` or
683 // `RecordPatFieldList`. `RecordPatField` also lives under `RecordPatFieldList`,
684 // so this tries to lookup the `IdentPat` anywhere along that structure to the
685 // `RecordPat` so we can get the containing type.
686 let record_pat = ast::RecordPatField::cast(parent.clone())
687 .and_then(|record_pat| record_pat.syntax().parent())
688 .or_else(|| Some(parent.clone()))
690 ast::RecordPatFieldList::cast(parent)?
693 .and_then(ast::RecordPat::cast)
696 // If this doesn't match a `RecordPat`, fallback to a `LetStmt` to see if
697 // this is initialized from a `FieldExpr`.
698 if let Some(record_pat) = record_pat {
699 self.type_of_pat(&ast::Pat::RecordPat(record_pat))
700 } else if let Some(let_stmt) = ast::LetStmt::cast(parent) {
701 let field_expr = match let_stmt.initializer()? {
702 ast::Expr::FieldExpr(field_expr) => field_expr,
706 self.type_of_expr(&field_expr.expr()?)
711 // Binding a reference to a packed type is possibly unsafe.
712 .map(|ty| ty.is_packed(self.db))
717 pub trait ToDef: AstNode + Clone {
720 fn to_def(sema: &SemanticsImpl, src: InFile<Self>) -> Option<Self::Def>;
723 macro_rules! to_def_impls {
724 ($(($def:path, $ast:path, $meth:ident)),* ,) => {$(
725 impl ToDef for $ast {
727 fn to_def(sema: &SemanticsImpl, src: InFile<Self>) -> Option<Self::Def> {
728 sema.with_ctx(|ctx| ctx.$meth(src)).map(<$def>::from)
735 (crate::Module, ast::Module, module_to_def),
736 (crate::Struct, ast::Struct, struct_to_def),
737 (crate::Enum, ast::Enum, enum_to_def),
738 (crate::Union, ast::Union, union_to_def),
739 (crate::Trait, ast::Trait, trait_to_def),
740 (crate::Impl, ast::Impl, impl_to_def),
741 (crate::TypeAlias, ast::TypeAlias, type_alias_to_def),
742 (crate::Const, ast::Const, const_to_def),
743 (crate::Static, ast::Static, static_to_def),
744 (crate::Function, ast::Fn, fn_to_def),
745 (crate::Field, ast::RecordField, record_field_to_def),
746 (crate::Field, ast::TupleField, tuple_field_to_def),
747 (crate::Variant, ast::Variant, enum_variant_to_def),
748 (crate::TypeParam, ast::TypeParam, type_param_to_def),
749 (crate::LifetimeParam, ast::LifetimeParam, lifetime_param_to_def),
750 (crate::ConstParam, ast::ConstParam, const_param_to_def),
751 (crate::MacroDef, ast::MacroRules, macro_rules_to_def),
752 (crate::Local, ast::IdentPat, bind_pat_to_def),
753 (crate::Label, ast::Label, label_to_def),
756 fn find_root(node: &SyntaxNode) -> SyntaxNode {
757 node.ancestors().last().unwrap()
760 /// `SemanticScope` encapsulates the notion of a scope (the set of visible
761 /// names) at a particular program point.
763 /// It is a bit tricky, as scopes do not really exist inside the compiler.
764 /// Rather, the compiler directly computes for each reference the definition it
765 /// refers to. It might transiently compute the explicit scope map while doing
766 /// so, but, generally, this is not something left after the analysis.
768 /// However, we do very much need explicit scopes for IDE purposes --
769 /// completion, at its core, lists the contents of the current scope. The notion
770 /// of scope is also useful to answer questions like "what would be the meaning
771 /// of this piece of code if we inserted it into this position?".
773 /// So `SemanticsScope` is constructed from a specific program point (a syntax
774 /// node or just a raw offset) and provides access to the set of visible names
775 /// on a somewhat best-effort basis.
777 /// Note that if you are wondering "what does this specific existing name mean?",
778 /// you'd better use the `resolve_` family of methods.
780 pub struct SemanticsScope<'a> {
781 pub db: &'a dyn HirDatabase,
786 impl<'a> SemanticsScope<'a> {
787 pub fn module(&self) -> Option<Module> {
788 Some(Module { id: self.resolver.module()? })
791 pub fn krate(&self) -> Option<Crate> {
792 Some(Crate { id: self.resolver.krate()? })
795 /// Note: `FxHashSet<TraitId>` should be treated as an opaque type, passed into `Type
796 // FIXME: rename to visible_traits to not repeat scope?
797 pub fn traits_in_scope(&self) -> FxHashSet<TraitId> {
798 let resolver = &self.resolver;
799 resolver.traits_in_scope(self.db.upcast())
802 pub fn process_all_names(&self, f: &mut dyn FnMut(Name, ScopeDef)) {
803 let resolver = &self.resolver;
805 resolver.process_all_names(self.db.upcast(), &mut |name, def| {
806 let def = match def {
807 resolver::ScopeDef::PerNs(it) => {
808 let items = ScopeDef::all_items(it);
810 f(name.clone(), item);
814 resolver::ScopeDef::ImplSelfType(it) => ScopeDef::ImplSelfType(it.into()),
815 resolver::ScopeDef::AdtSelfType(it) => ScopeDef::AdtSelfType(it.into()),
816 resolver::ScopeDef::GenericParam(id) => ScopeDef::GenericParam(TypeParam { id }),
817 resolver::ScopeDef::Local(pat_id) => {
818 let parent = resolver.body_owner().unwrap().into();
819 ScopeDef::Local(Local { parent, pat_id })
826 /// Resolve a path as-if it was written at the given scope. This is
827 /// necessary a heuristic, as it doesn't take hygiene into account.
828 pub fn speculative_resolve(&self, path: &ast::Path) -> Option<PathResolution> {
829 let hygiene = Hygiene::new(self.db.upcast(), self.file_id);
830 let path = Path::from_src(path.clone(), &hygiene)?;
831 resolve_hir_path(self.db, &self.resolver, &path)