5 use std::{cell::RefCell, fmt};
7 use base_db::{FileId, FileRange};
10 resolver::{self, HasResolver, Resolver, TypeNs},
11 AsMacroCall, FunctionId, TraitId, VariantId,
13 use hir_expand::{name::AsName, ExpansionInfo};
14 use hir_ty::{associated_type_shorthand_candidates, Interner};
15 use itertools::Itertools;
16 use rustc_hash::{FxHashMap, FxHashSet};
17 use smallvec::{smallvec, SmallVec};
19 ast::{self, GenericParamsOwner, LoopBodyOwner},
20 match_ast, AstNode, SyntaxNode, SyntaxNodePtr, SyntaxToken, TextRange, TextSize,
25 semantics::source_to_def::{ChildContainer, SourceToDefCache, SourceToDefCtx},
26 source_analyzer::{resolve_hir_path, SourceAnalyzer},
27 Access, AssocItem, Callable, ConstParam, Crate, Field, Function, HirFileId, Impl, InFile,
28 Label, LifetimeParam, Local, MacroDef, Module, ModuleDef, Name, Path, ScopeDef, Trait, Type,
29 TypeAlias, TypeParam, VariantDef,
32 #[derive(Debug, Clone, PartialEq, Eq)]
33 pub enum PathResolution {
36 /// A local binding (only value namespace)
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).into()))
56 | ModuleDef::Variant(_)
57 | ModuleDef::Function(_)
58 | ModuleDef::Module(_)
59 | ModuleDef::Static(_)
60 | ModuleDef::Trait(_),
62 PathResolution::Def(ModuleDef::TypeAlias(alias)) => {
63 Some(TypeNs::TypeAliasId((*alias).into()))
65 PathResolution::Local(_) | PathResolution::Macro(_) | PathResolution::ConstParam(_) => {
68 PathResolution::TypeParam(param) => Some(TypeNs::GenericParam((*param).into())),
69 PathResolution::SelfType(impl_def) => Some(TypeNs::SelfType((*impl_def).into())),
70 PathResolution::AssocItem(AssocItem::Const(_) | AssocItem::Function(_)) => None,
71 PathResolution::AssocItem(AssocItem::TypeAlias(alias)) => {
72 Some(TypeNs::TypeAliasId((*alias).into()))
77 /// Returns an iterator over associated types that may be specified after this path (using
78 /// `Ty::Assoc` syntax).
79 pub fn assoc_type_shorthand_candidates<R>(
82 mut cb: impl FnMut(&Name, TypeAlias) -> Option<R>,
84 associated_type_shorthand_candidates(db, self.in_type_ns()?, |name, _, id| {
92 /// The original type of the expression or pattern.
94 /// The adjusted type, if an adjustment happened.
95 pub adjusted: Option<Type>,
99 pub fn original(self) -> Type {
103 pub fn has_adjustment(&self) -> bool {
104 self.adjusted.is_some()
107 /// The adjusted type, or the original in case no adjustments occurred.
108 pub fn adjusted(self) -> Type {
109 self.adjusted.unwrap_or(self.original)
113 /// Primary API to get semantic information, like types, from syntax trees.
114 pub struct Semantics<'db, DB> {
116 imp: SemanticsImpl<'db>,
119 pub struct SemanticsImpl<'db> {
120 pub db: &'db dyn HirDatabase,
121 s2d_cache: RefCell<SourceToDefCache>,
122 expansion_info_cache: RefCell<FxHashMap<HirFileId, Option<ExpansionInfo>>>,
123 cache: RefCell<FxHashMap<SyntaxNode, HirFileId>>,
126 impl<DB> fmt::Debug for Semantics<'_, DB> {
127 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
128 write!(f, "Semantics {{ ... }}")
132 impl<'db, DB: HirDatabase> Semantics<'db, DB> {
133 pub fn new(db: &DB) -> Semantics<DB> {
134 let impl_ = SemanticsImpl::new(db);
135 Semantics { db, imp: impl_ }
138 pub fn parse(&self, file_id: FileId) -> ast::SourceFile {
139 self.imp.parse(file_id)
142 pub fn expand(&self, macro_call: &ast::MacroCall) -> Option<SyntaxNode> {
143 self.imp.expand(macro_call)
146 /// If `item` has an attribute macro attached to it, expands it.
147 pub fn expand_attr_macro(&self, item: &ast::Item) -> Option<SyntaxNode> {
148 self.imp.expand_attr_macro(item)
151 pub fn expand_derive_macro(&self, derive: &ast::Attr) -> Option<Vec<SyntaxNode>> {
152 self.imp.expand_derive_macro(derive)
155 pub fn is_attr_macro_call(&self, item: &ast::Item) -> bool {
156 self.imp.is_attr_macro_call(item)
159 pub fn speculative_expand(
161 actual_macro_call: &ast::MacroCall,
162 speculative_args: &ast::TokenTree,
163 token_to_map: SyntaxToken,
164 ) -> Option<(SyntaxNode, SyntaxToken)> {
165 self.imp.speculative_expand(actual_macro_call, speculative_args, token_to_map)
168 pub fn speculative_expand_attr_macro(
170 actual_macro_call: &ast::Item,
171 speculative_args: &ast::Item,
172 token_to_map: SyntaxToken,
173 ) -> Option<(SyntaxNode, SyntaxToken)> {
174 self.imp.speculative_expand_attr(actual_macro_call, speculative_args, token_to_map)
177 // FIXME: Rename to descend_into_macros_single
178 pub fn descend_into_macros(&self, token: SyntaxToken) -> SyntaxToken {
179 self.imp.descend_into_macros(token).pop().unwrap()
182 // FIXME: Rename to descend_into_macros
183 pub fn descend_into_macros_many(&self, token: SyntaxToken) -> SmallVec<[SyntaxToken; 1]> {
184 self.imp.descend_into_macros(token)
187 pub fn hir_file_for(&self, syntax_node: &SyntaxNode) -> HirFileId {
188 self.imp.find_file(syntax_node.clone()).file_id
191 pub fn original_range(&self, node: &SyntaxNode) -> FileRange {
192 self.imp.original_range(node)
195 pub fn diagnostics_display_range(&self, diagnostics: InFile<SyntaxNodePtr>) -> FileRange {
196 self.imp.diagnostics_display_range(diagnostics)
199 pub fn token_ancestors_with_macros(
202 ) -> impl Iterator<Item = SyntaxNode> + '_ {
203 token.parent().into_iter().flat_map(move |it| self.ancestors_with_macros(it))
206 pub fn ancestors_with_macros(&self, node: SyntaxNode) -> impl Iterator<Item = SyntaxNode> + '_ {
207 self.imp.ancestors_with_macros(node)
210 pub fn ancestors_at_offset_with_macros(
214 ) -> impl Iterator<Item = SyntaxNode> + '_ {
215 self.imp.ancestors_at_offset_with_macros(node, offset)
218 /// Find an AstNode by offset inside SyntaxNode, if it is inside *Macrofile*,
219 /// search up until it is of the target AstNode type
220 pub fn find_node_at_offset_with_macros<N: AstNode>(
225 self.imp.ancestors_at_offset_with_macros(node, offset).find_map(N::cast)
228 /// Find an AstNode by offset inside SyntaxNode, if it is inside *MacroCall*,
229 /// descend it and find again
230 pub fn find_node_at_offset_with_descend<N: AstNode>(
235 self.imp.descend_node_at_offset(node, offset).flatten().find_map(N::cast)
238 /// Find an AstNode by offset inside SyntaxNode, if it is inside *MacroCall*,
239 /// descend it and find again
240 pub fn find_nodes_at_offset_with_descend<'slf, N: AstNode + 'slf>(
244 ) -> impl Iterator<Item = N> + 'slf {
245 self.imp.descend_node_at_offset(node, offset).filter_map(|mut it| it.find_map(N::cast))
248 pub fn resolve_lifetime_param(&self, lifetime: &ast::Lifetime) -> Option<LifetimeParam> {
249 self.imp.resolve_lifetime_param(lifetime)
252 pub fn resolve_label(&self, lifetime: &ast::Lifetime) -> Option<Label> {
253 self.imp.resolve_label(lifetime)
256 pub fn resolve_type(&self, ty: &ast::Type) -> Option<Type> {
257 self.imp.resolve_type(ty)
260 pub fn type_of_expr(&self, expr: &ast::Expr) -> Option<TypeInfo> {
261 self.imp.type_of_expr(expr)
264 pub fn type_of_pat(&self, pat: &ast::Pat) -> Option<TypeInfo> {
265 self.imp.type_of_pat(pat)
268 pub fn type_of_self(&self, param: &ast::SelfParam) -> Option<Type> {
269 self.imp.type_of_self(param)
272 pub fn resolve_method_call(&self, call: &ast::MethodCallExpr) -> Option<Function> {
273 self.imp.resolve_method_call(call).map(Function::from)
276 pub fn resolve_method_call_as_callable(&self, call: &ast::MethodCallExpr) -> Option<Callable> {
277 self.imp.resolve_method_call_as_callable(call)
280 pub fn resolve_field(&self, field: &ast::FieldExpr) -> Option<Field> {
281 self.imp.resolve_field(field)
284 pub fn resolve_record_field(
286 field: &ast::RecordExprField,
287 ) -> Option<(Field, Option<Local>, Type)> {
288 self.imp.resolve_record_field(field)
291 pub fn resolve_record_pat_field(&self, field: &ast::RecordPatField) -> Option<Field> {
292 self.imp.resolve_record_pat_field(field)
295 pub fn resolve_macro_call(&self, macro_call: &ast::MacroCall) -> Option<MacroDef> {
296 self.imp.resolve_macro_call(macro_call)
299 pub fn resolve_attr_macro_call(&self, item: &ast::Item) -> Option<MacroDef> {
300 self.imp.resolve_attr_macro_call(item)
303 pub fn resolve_path(&self, path: &ast::Path) -> Option<PathResolution> {
304 self.imp.resolve_path(path)
307 pub fn resolve_extern_crate(&self, extern_crate: &ast::ExternCrate) -> Option<Crate> {
308 self.imp.resolve_extern_crate(extern_crate)
311 pub fn resolve_variant(&self, record_lit: ast::RecordExpr) -> Option<VariantDef> {
312 self.imp.resolve_variant(record_lit).map(VariantDef::from)
315 pub fn resolve_bind_pat_to_const(&self, pat: &ast::IdentPat) -> Option<ModuleDef> {
316 self.imp.resolve_bind_pat_to_const(pat)
319 // FIXME: use this instead?
320 // pub fn resolve_name_ref(&self, name_ref: &ast::NameRef) -> Option<???>;
322 pub fn record_literal_missing_fields(&self, literal: &ast::RecordExpr) -> Vec<(Field, Type)> {
323 self.imp.record_literal_missing_fields(literal)
326 pub fn record_pattern_missing_fields(&self, pattern: &ast::RecordPat) -> Vec<(Field, Type)> {
327 self.imp.record_pattern_missing_fields(pattern)
330 pub fn to_def<T: ToDef>(&self, src: &T) -> Option<T::Def> {
331 let src = self.imp.find_file(src.syntax().clone()).with_value(src).cloned();
332 T::to_def(&self.imp, src)
335 pub fn to_module_def(&self, file: FileId) -> Option<Module> {
336 self.imp.to_module_def(file).next()
339 pub fn to_module_defs(&self, file: FileId) -> impl Iterator<Item = Module> {
340 self.imp.to_module_def(file)
343 pub fn scope(&self, node: &SyntaxNode) -> SemanticsScope<'db> {
347 pub fn scope_at_offset(&self, token: &SyntaxToken, offset: TextSize) -> SemanticsScope<'db> {
348 self.imp.scope_at_offset(&token.parent().unwrap(), offset)
351 pub fn scope_for_def(&self, def: Trait) -> SemanticsScope<'db> {
352 self.imp.scope_for_def(def)
355 pub fn assert_contains_node(&self, node: &SyntaxNode) {
356 self.imp.assert_contains_node(node)
359 pub fn is_unsafe_method_call(&self, method_call_expr: &ast::MethodCallExpr) -> bool {
360 self.imp.is_unsafe_method_call(method_call_expr)
363 pub fn is_unsafe_ref_expr(&self, ref_expr: &ast::RefExpr) -> bool {
364 self.imp.is_unsafe_ref_expr(ref_expr)
367 pub fn is_unsafe_ident_pat(&self, ident_pat: &ast::IdentPat) -> bool {
368 self.imp.is_unsafe_ident_pat(ident_pat)
372 impl<'db> SemanticsImpl<'db> {
373 fn new(db: &'db dyn HirDatabase) -> Self {
376 s2d_cache: Default::default(),
377 cache: Default::default(),
378 expansion_info_cache: Default::default(),
382 fn parse(&self, file_id: FileId) -> ast::SourceFile {
383 let tree = self.db.parse(file_id).tree();
384 self.cache(tree.syntax().clone(), file_id.into());
388 fn expand(&self, macro_call: &ast::MacroCall) -> Option<SyntaxNode> {
389 let sa = self.analyze(macro_call.syntax());
390 let file_id = sa.expand(self.db, InFile::new(sa.file_id, macro_call))?;
391 let node = self.db.parse_or_expand(file_id)?;
392 self.cache(node.clone(), file_id);
396 fn expand_attr_macro(&self, item: &ast::Item) -> Option<SyntaxNode> {
397 let sa = self.analyze(item.syntax());
398 let src = InFile::new(sa.file_id, item.clone());
399 let macro_call_id = self.with_ctx(|ctx| ctx.item_to_macro_call(src))?;
400 let file_id = macro_call_id.as_file();
401 let node = self.db.parse_or_expand(file_id)?;
402 self.cache(node.clone(), file_id);
406 fn expand_derive_macro(&self, attr: &ast::Attr) -> Option<Vec<SyntaxNode>> {
407 let item = attr.syntax().parent().and_then(ast::Item::cast)?;
408 let sa = self.analyze(item.syntax());
409 let item = InFile::new(sa.file_id, &item);
410 let src = InFile::new(sa.file_id, attr.clone());
411 self.with_ctx(|ctx| {
412 let macro_call_ids = ctx.attr_to_derive_macro_call(item, src)?;
414 let expansions: Vec<_> = macro_call_ids
416 .map(|call| call.as_file())
417 .flat_map(|file_id| {
418 let node = self.db.parse_or_expand(file_id)?;
419 self.cache(node.clone(), file_id);
423 if expansions.is_empty() {
431 fn is_attr_macro_call(&self, item: &ast::Item) -> bool {
432 let sa = self.analyze(item.syntax());
433 let src = InFile::new(sa.file_id, item.clone());
434 self.with_ctx(|ctx| ctx.item_to_macro_call(src).is_some())
437 fn speculative_expand(
439 actual_macro_call: &ast::MacroCall,
440 speculative_args: &ast::TokenTree,
441 token_to_map: SyntaxToken,
442 ) -> Option<(SyntaxNode, SyntaxToken)> {
443 let sa = self.analyze(actual_macro_call.syntax());
444 let macro_call = InFile::new(sa.file_id, actual_macro_call);
445 let krate = sa.resolver.krate()?;
446 let macro_call_id = macro_call.as_call_id(self.db.upcast(), krate, |path| {
447 sa.resolver.resolve_path_as_macro(self.db.upcast(), &path)
449 hir_expand::db::expand_speculative(
452 speculative_args.syntax(),
457 fn speculative_expand_attr(
459 actual_macro_call: &ast::Item,
460 speculative_args: &ast::Item,
461 token_to_map: SyntaxToken,
462 ) -> Option<(SyntaxNode, SyntaxToken)> {
463 let sa = self.analyze(actual_macro_call.syntax());
464 let macro_call = InFile::new(sa.file_id, actual_macro_call.clone());
465 let macro_call_id = self.with_ctx(|ctx| ctx.item_to_macro_call(macro_call))?;
466 hir_expand::db::expand_speculative(
469 speculative_args.syntax(),
474 fn descend_into_macros(&self, token: SyntaxToken) -> SmallVec<[SyntaxToken; 1]> {
475 let _p = profile::span("descend_into_macros");
476 let parent = match token.parent() {
478 None => return smallvec![token],
480 let sa = self.analyze(&parent);
481 let mut queue = vec![InFile::new(sa.file_id, token)];
482 let mut cache = self.expansion_info_cache.borrow_mut();
483 let mut res = smallvec![];
484 // Remap the next token in the queue into a macro call its in, if it is not being remapped
485 // either due to not being in a macro-call or because its unused push it into the result vec,
486 // otherwise push the remapped tokens back into the queue as they can potentially be remapped again.
487 while let Some(token) = queue.pop() {
488 self.db.unwind_if_cancelled();
489 let was_not_remapped = (|| {
490 if let Some((call_id, item)) = token
493 .filter_map(ast::Item::cast)
495 self.with_ctx(|ctx| ctx.item_to_macro_call(token.with_value(item.clone())))
500 let file_id = call_id.as_file();
503 .or_insert_with(|| file_id.expansion_info(self.db.upcast()))
505 .map_token_down(self.db.upcast(), Some(item), token.as_ref())?;
507 let len = queue.len();
508 queue.extend(tokens.inspect(|token| {
509 if let Some(parent) = token.value.parent() {
510 self.cache(find_root(&parent), token.file_id);
513 return (queue.len() != len).then(|| ());
516 if let Some(macro_call) = token.value.ancestors().find_map(ast::MacroCall::cast) {
517 let tt = macro_call.token_tree()?;
518 let l_delim = match tt.left_delimiter_token() {
519 Some(it) => it.text_range().end(),
520 None => tt.syntax().text_range().start(),
522 let r_delim = match tt.right_delimiter_token() {
523 Some(it) => it.text_range().start(),
524 None => tt.syntax().text_range().end(),
526 if !TextRange::new(l_delim, r_delim).contains_range(token.value.text_range()) {
529 let file_id = sa.expand(self.db, token.with_value(¯o_call))?;
532 .or_insert_with(|| file_id.expansion_info(self.db.upcast()))
534 .map_token_down(self.db.upcast(), None, token.as_ref())?;
536 let len = queue.len();
537 queue.extend(tokens.inspect(|token| {
538 if let Some(parent) = token.value.parent() {
539 self.cache(find_root(&parent), token.file_id);
542 return (queue.len() != len).then(|| ());
548 if was_not_remapped {
549 res.push(token.value)
555 // Note this return type is deliberate as [`find_nodes_at_offset_with_descend`] wants to stop
556 // traversing the inner iterator when it finds a node.
557 // The outer iterator is over the tokens descendants
558 // The inner iterator is the ancestors of a descendant
559 fn descend_node_at_offset(
563 ) -> impl Iterator<Item = impl Iterator<Item = SyntaxNode> + '_> + '_ {
564 node.token_at_offset(offset)
565 .map(move |token| self.descend_into_macros(token))
567 descendants.into_iter().map(move |it| self.token_ancestors_with_macros(it))
569 // re-order the tokens from token_at_offset by returning the ancestors with the smaller first nodes first
570 // See algo::ancestors_at_offset, which uses the same approach
571 .kmerge_by(|left, right| {
573 .map(|node| node.text_range().len())
574 .lt(right.clone().map(|node| node.text_range().len()))
578 fn original_range(&self, node: &SyntaxNode) -> FileRange {
579 let node = self.find_file(node.clone());
580 node.as_ref().original_file_range(self.db.upcast())
583 fn diagnostics_display_range(&self, src: InFile<SyntaxNodePtr>) -> FileRange {
584 let root = self.db.parse_or_expand(src.file_id).unwrap();
585 let node = src.value.to_node(&root);
586 self.cache(root, src.file_id);
587 src.with_value(&node).original_file_range(self.db.upcast())
590 fn token_ancestors_with_macros(
593 ) -> impl Iterator<Item = SyntaxNode> + Clone + '_ {
594 token.parent().into_iter().flat_map(move |parent| self.ancestors_with_macros(parent))
597 fn ancestors_with_macros(
600 ) -> impl Iterator<Item = SyntaxNode> + Clone + '_ {
601 let node = self.find_file(node);
602 node.ancestors_with_macros(self.db.upcast()).map(|it| it.value)
605 fn ancestors_at_offset_with_macros(
609 ) -> impl Iterator<Item = SyntaxNode> + '_ {
610 node.token_at_offset(offset)
611 .map(|token| self.token_ancestors_with_macros(token))
612 .kmerge_by(|node1, node2| node1.text_range().len() < node2.text_range().len())
615 fn resolve_lifetime_param(&self, lifetime: &ast::Lifetime) -> Option<LifetimeParam> {
616 let text = lifetime.text();
617 let lifetime_param = lifetime.syntax().ancestors().find_map(|syn| {
618 let gpl = match_ast! {
620 ast::Fn(it) => it.generic_param_list()?,
621 ast::TypeAlias(it) => it.generic_param_list()?,
622 ast::Struct(it) => it.generic_param_list()?,
623 ast::Enum(it) => it.generic_param_list()?,
624 ast::Union(it) => it.generic_param_list()?,
625 ast::Trait(it) => it.generic_param_list()?,
626 ast::Impl(it) => it.generic_param_list()?,
627 ast::WherePred(it) => it.generic_param_list()?,
628 ast::ForType(it) => it.generic_param_list()?,
632 gpl.lifetime_params()
633 .find(|tp| tp.lifetime().as_ref().map(|lt| lt.text()).as_ref() == Some(&text))
635 let src = self.find_file(lifetime_param.syntax().clone()).with_value(lifetime_param);
636 ToDef::to_def(self, src)
639 fn resolve_label(&self, lifetime: &ast::Lifetime) -> Option<Label> {
640 let text = lifetime.text();
641 let label = lifetime.syntax().ancestors().find_map(|syn| {
642 let label = match_ast! {
644 ast::ForExpr(it) => it.label(),
645 ast::WhileExpr(it) => it.label(),
646 ast::LoopExpr(it) => it.label(),
647 ast::EffectExpr(it) => it.label(),
653 .and_then(|lt| lt.lifetime_ident_token())
654 .map_or(false, |lt| lt.text() == text)
657 let src = self.find_file(label.syntax().clone()).with_value(label);
658 ToDef::to_def(self, src)
661 fn resolve_type(&self, ty: &ast::Type) -> Option<Type> {
662 let scope = self.scope(ty.syntax());
663 let ctx = body::LowerCtx::new(self.db.upcast(), scope.file_id);
664 let ty = hir_ty::TyLoweringContext::new(self.db, &scope.resolver)
665 .lower_ty(&crate::TypeRef::from_ast(&ctx, ty.clone()));
666 Type::new_with_resolver(self.db, &scope.resolver, ty)
669 fn type_of_expr(&self, expr: &ast::Expr) -> Option<TypeInfo> {
670 self.analyze(expr.syntax())
671 .type_of_expr(self.db, expr)
672 .map(|(ty, coerced)| TypeInfo { original: ty, adjusted: coerced })
675 fn type_of_pat(&self, pat: &ast::Pat) -> Option<TypeInfo> {
676 self.analyze(pat.syntax())
677 .type_of_pat(self.db, pat)
678 .map(|(ty, coerced)| TypeInfo { original: ty, adjusted: coerced })
681 fn type_of_self(&self, param: &ast::SelfParam) -> Option<Type> {
682 self.analyze(param.syntax()).type_of_self(self.db, param)
685 fn resolve_method_call(&self, call: &ast::MethodCallExpr) -> Option<FunctionId> {
686 self.analyze(call.syntax()).resolve_method_call(self.db, call).map(|(id, _)| id)
689 fn resolve_method_call_as_callable(&self, call: &ast::MethodCallExpr) -> Option<Callable> {
690 let (func, subst) = self.analyze(call.syntax()).resolve_method_call(self.db, call)?;
691 let ty = self.db.value_ty(func.into()).substitute(&Interner, &subst);
692 let resolver = self.analyze(call.syntax()).resolver;
693 let ty = Type::new_with_resolver(self.db, &resolver, ty)?;
694 let mut res = ty.as_callable(self.db)?;
695 res.is_bound_method = true;
699 fn resolve_field(&self, field: &ast::FieldExpr) -> Option<Field> {
700 self.analyze(field.syntax()).resolve_field(self.db, field)
703 fn resolve_record_field(
705 field: &ast::RecordExprField,
706 ) -> Option<(Field, Option<Local>, Type)> {
707 self.analyze(field.syntax()).resolve_record_field(self.db, field)
710 fn resolve_record_pat_field(&self, field: &ast::RecordPatField) -> Option<Field> {
711 self.analyze(field.syntax()).resolve_record_pat_field(self.db, field)
714 fn resolve_macro_call(&self, macro_call: &ast::MacroCall) -> Option<MacroDef> {
715 let sa = self.analyze(macro_call.syntax());
716 let macro_call = self.find_file(macro_call.syntax().clone()).with_value(macro_call);
717 sa.resolve_macro_call(self.db, macro_call)
720 fn resolve_attr_macro_call(&self, item: &ast::Item) -> Option<MacroDef> {
721 let item_in_file = self.find_file(item.syntax().clone()).with_value(item.clone());
722 let macro_call_id = self.with_ctx(|ctx| ctx.item_to_macro_call(item_in_file))?;
723 Some(MacroDef { id: self.db.lookup_intern_macro(macro_call_id).def })
726 fn resolve_path(&self, path: &ast::Path) -> Option<PathResolution> {
727 self.analyze(path.syntax()).resolve_path(self.db, path)
730 fn resolve_extern_crate(&self, extern_crate: &ast::ExternCrate) -> Option<Crate> {
731 let krate = self.scope(extern_crate.syntax()).krate()?;
732 krate.dependencies(self.db).into_iter().find_map(|dep| {
733 if dep.name == extern_crate.name_ref()?.as_name() {
741 fn resolve_variant(&self, record_lit: ast::RecordExpr) -> Option<VariantId> {
742 self.analyze(record_lit.syntax()).resolve_variant(self.db, record_lit)
745 fn resolve_bind_pat_to_const(&self, pat: &ast::IdentPat) -> Option<ModuleDef> {
746 self.analyze(pat.syntax()).resolve_bind_pat_to_const(self.db, pat)
749 fn record_literal_missing_fields(&self, literal: &ast::RecordExpr) -> Vec<(Field, Type)> {
750 self.analyze(literal.syntax())
751 .record_literal_missing_fields(self.db, literal)
755 fn record_pattern_missing_fields(&self, pattern: &ast::RecordPat) -> Vec<(Field, Type)> {
756 self.analyze(pattern.syntax())
757 .record_pattern_missing_fields(self.db, pattern)
761 fn with_ctx<F: FnOnce(&mut SourceToDefCtx) -> T, T>(&self, f: F) -> T {
762 let mut cache = self.s2d_cache.borrow_mut();
763 let mut ctx = SourceToDefCtx { db: self.db, cache: &mut *cache };
767 fn to_module_def(&self, file: FileId) -> impl Iterator<Item = Module> {
768 self.with_ctx(|ctx| ctx.file_to_def(file)).into_iter().map(Module::from)
771 fn scope(&self, node: &SyntaxNode) -> SemanticsScope<'db> {
772 let sa = self.analyze(node);
773 SemanticsScope { db: self.db, file_id: sa.file_id, resolver: sa.resolver }
776 fn scope_at_offset(&self, node: &SyntaxNode, offset: TextSize) -> SemanticsScope<'db> {
777 let sa = self.analyze_with_offset(node, offset);
778 SemanticsScope { db: self.db, file_id: sa.file_id, resolver: sa.resolver }
781 fn scope_for_def(&self, def: Trait) -> SemanticsScope<'db> {
782 let file_id = self.db.lookup_intern_trait(def.id).id.file_id();
783 let resolver = def.id.resolver(self.db.upcast());
784 SemanticsScope { db: self.db, file_id, resolver }
787 fn analyze(&self, node: &SyntaxNode) -> SourceAnalyzer {
788 self.analyze_impl(node, None)
790 fn analyze_with_offset(&self, node: &SyntaxNode, offset: TextSize) -> SourceAnalyzer {
791 self.analyze_impl(node, Some(offset))
793 fn analyze_impl(&self, node: &SyntaxNode, offset: Option<TextSize>) -> SourceAnalyzer {
794 let _p = profile::span("Semantics::analyze_impl");
795 let node = self.find_file(node.clone());
796 let node = node.as_ref();
798 let container = match self.with_ctx(|ctx| ctx.find_container(node)) {
800 None => return SourceAnalyzer::new_for_resolver(Resolver::default(), node),
803 let resolver = match container {
804 ChildContainer::DefWithBodyId(def) => {
805 return SourceAnalyzer::new_for_body(self.db, def, node, offset)
807 ChildContainer::TraitId(it) => it.resolver(self.db.upcast()),
808 ChildContainer::ImplId(it) => it.resolver(self.db.upcast()),
809 ChildContainer::ModuleId(it) => it.resolver(self.db.upcast()),
810 ChildContainer::EnumId(it) => it.resolver(self.db.upcast()),
811 ChildContainer::VariantId(it) => it.resolver(self.db.upcast()),
812 ChildContainer::TypeAliasId(it) => it.resolver(self.db.upcast()),
813 ChildContainer::GenericDefId(it) => it.resolver(self.db.upcast()),
815 SourceAnalyzer::new_for_resolver(resolver, node)
818 fn cache(&self, root_node: SyntaxNode, file_id: HirFileId) {
819 assert!(root_node.parent().is_none());
820 let mut cache = self.cache.borrow_mut();
821 let prev = cache.insert(root_node, file_id);
822 assert!(prev == None || prev == Some(file_id))
825 fn assert_contains_node(&self, node: &SyntaxNode) {
826 self.find_file(node.clone());
829 fn lookup(&self, root_node: &SyntaxNode) -> Option<HirFileId> {
830 let cache = self.cache.borrow();
831 cache.get(root_node).copied()
834 fn find_file(&self, node: SyntaxNode) -> InFile<SyntaxNode> {
835 let root_node = find_root(&node);
836 let file_id = self.lookup(&root_node).unwrap_or_else(|| {
838 "\n\nFailed to lookup {:?} in this Semantics.\n\
839 Make sure to use only query nodes, derived from this instance of Semantics.\n\
841 known nodes: {}\n\n",
847 .map(|it| format!("{:?}", it))
852 InFile::new(file_id, node)
855 fn is_unsafe_method_call(&self, method_call_expr: &ast::MethodCallExpr) -> bool {
859 let field_expr = match expr {
860 ast::Expr::FieldExpr(field_expr) => field_expr,
863 let ty = self.type_of_expr(&field_expr.expr()?)?.original;
864 if !ty.is_packed(self.db) {
868 let func = self.resolve_method_call(method_call_expr).map(Function::from)?;
869 let res = match func.self_param(self.db)?.access(self.db) {
870 Access::Shared | Access::Exclusive => true,
871 Access::Owned => false,
878 fn is_unsafe_ref_expr(&self, ref_expr: &ast::RefExpr) -> bool {
882 let field_expr = match expr {
883 ast::Expr::FieldExpr(field_expr) => field_expr,
886 let expr = field_expr.expr()?;
887 self.type_of_expr(&expr)
889 // Binding a reference to a packed type is possibly unsafe.
890 .map(|ty| ty.original.is_packed(self.db))
893 // FIXME This needs layout computation to be correct. It will highlight
894 // more than it should with the current implementation.
897 fn is_unsafe_ident_pat(&self, ident_pat: &ast::IdentPat) -> bool {
898 if ident_pat.ref_token().is_none() {
906 // `IdentPat` can live under `RecordPat` directly under `RecordPatField` or
907 // `RecordPatFieldList`. `RecordPatField` also lives under `RecordPatFieldList`,
908 // so this tries to lookup the `IdentPat` anywhere along that structure to the
909 // `RecordPat` so we can get the containing type.
910 let record_pat = ast::RecordPatField::cast(parent.clone())
911 .and_then(|record_pat| record_pat.syntax().parent())
912 .or_else(|| Some(parent.clone()))
914 ast::RecordPatFieldList::cast(parent)?
917 .and_then(ast::RecordPat::cast)
920 // If this doesn't match a `RecordPat`, fallback to a `LetStmt` to see if
921 // this is initialized from a `FieldExpr`.
922 if let Some(record_pat) = record_pat {
923 self.type_of_pat(&ast::Pat::RecordPat(record_pat))
924 } else if let Some(let_stmt) = ast::LetStmt::cast(parent) {
925 let field_expr = match let_stmt.initializer()? {
926 ast::Expr::FieldExpr(field_expr) => field_expr,
930 self.type_of_expr(&field_expr.expr()?)
935 // Binding a reference to a packed type is possibly unsafe.
936 .map(|ty| ty.original.is_packed(self.db))
941 pub trait ToDef: AstNode + Clone {
944 fn to_def(sema: &SemanticsImpl, src: InFile<Self>) -> Option<Self::Def>;
947 macro_rules! to_def_impls {
948 ($(($def:path, $ast:path, $meth:ident)),* ,) => {$(
949 impl ToDef for $ast {
951 fn to_def(sema: &SemanticsImpl, src: InFile<Self>) -> Option<Self::Def> {
952 sema.with_ctx(|ctx| ctx.$meth(src)).map(<$def>::from)
959 (crate::Module, ast::Module, module_to_def),
960 (crate::Module, ast::SourceFile, source_file_to_def),
961 (crate::Struct, ast::Struct, struct_to_def),
962 (crate::Enum, ast::Enum, enum_to_def),
963 (crate::Union, ast::Union, union_to_def),
964 (crate::Trait, ast::Trait, trait_to_def),
965 (crate::Impl, ast::Impl, impl_to_def),
966 (crate::TypeAlias, ast::TypeAlias, type_alias_to_def),
967 (crate::Const, ast::Const, const_to_def),
968 (crate::Static, ast::Static, static_to_def),
969 (crate::Function, ast::Fn, fn_to_def),
970 (crate::Field, ast::RecordField, record_field_to_def),
971 (crate::Field, ast::TupleField, tuple_field_to_def),
972 (crate::Variant, ast::Variant, enum_variant_to_def),
973 (crate::TypeParam, ast::TypeParam, type_param_to_def),
974 (crate::LifetimeParam, ast::LifetimeParam, lifetime_param_to_def),
975 (crate::ConstParam, ast::ConstParam, const_param_to_def),
976 (crate::MacroDef, ast::Macro, macro_to_def),
977 (crate::Local, ast::IdentPat, bind_pat_to_def),
978 (crate::Local, ast::SelfParam, self_param_to_def),
979 (crate::Label, ast::Label, label_to_def),
980 (crate::Adt, ast::Adt, adt_to_def),
983 fn find_root(node: &SyntaxNode) -> SyntaxNode {
984 node.ancestors().last().unwrap()
987 /// `SemanticScope` encapsulates the notion of a scope (the set of visible
988 /// names) at a particular program point.
990 /// It is a bit tricky, as scopes do not really exist inside the compiler.
991 /// Rather, the compiler directly computes for each reference the definition it
992 /// refers to. It might transiently compute the explicit scope map while doing
993 /// so, but, generally, this is not something left after the analysis.
995 /// However, we do very much need explicit scopes for IDE purposes --
996 /// completion, at its core, lists the contents of the current scope. The notion
997 /// of scope is also useful to answer questions like "what would be the meaning
998 /// of this piece of code if we inserted it into this position?".
1000 /// So `SemanticsScope` is constructed from a specific program point (a syntax
1001 /// node or just a raw offset) and provides access to the set of visible names
1002 /// on a somewhat best-effort basis.
1004 /// Note that if you are wondering "what does this specific existing name mean?",
1005 /// you'd better use the `resolve_` family of methods.
1007 pub struct SemanticsScope<'a> {
1008 pub db: &'a dyn HirDatabase,
1013 impl<'a> SemanticsScope<'a> {
1014 pub fn module(&self) -> Option<Module> {
1015 Some(Module { id: self.resolver.module()? })
1018 pub fn krate(&self) -> Option<Crate> {
1019 Some(Crate { id: self.resolver.krate()? })
1022 /// Note: `FxHashSet<TraitId>` should be treated as an opaque type, passed into `Type
1023 // FIXME: rename to visible_traits to not repeat scope?
1024 pub fn traits_in_scope(&self) -> FxHashSet<TraitId> {
1025 let resolver = &self.resolver;
1026 resolver.traits_in_scope(self.db.upcast())
1029 pub fn process_all_names(&self, f: &mut dyn FnMut(Name, ScopeDef)) {
1030 let scope = self.resolver.names_in_scope(self.db.upcast());
1031 for (name, entries) in scope {
1032 for entry in entries {
1033 let def = match entry {
1034 resolver::ScopeDef::ModuleDef(it) => ScopeDef::ModuleDef(it.into()),
1035 resolver::ScopeDef::MacroDef(it) => ScopeDef::MacroDef(it.into()),
1036 resolver::ScopeDef::Unknown => ScopeDef::Unknown,
1037 resolver::ScopeDef::ImplSelfType(it) => ScopeDef::ImplSelfType(it.into()),
1038 resolver::ScopeDef::AdtSelfType(it) => ScopeDef::AdtSelfType(it.into()),
1039 resolver::ScopeDef::GenericParam(id) => ScopeDef::GenericParam(id.into()),
1040 resolver::ScopeDef::Local(pat_id) => {
1041 let parent = self.resolver.body_owner().unwrap();
1042 ScopeDef::Local(Local { parent, pat_id })
1044 resolver::ScopeDef::Label(label_id) => {
1045 let parent = self.resolver.body_owner().unwrap();
1046 ScopeDef::Label(Label { parent, label_id })
1049 f(name.clone(), def)
1054 /// Resolve a path as-if it was written at the given scope. This is
1055 /// necessary a heuristic, as it doesn't take hygiene into account.
1056 pub fn speculative_resolve(&self, path: &ast::Path) -> Option<PathResolution> {
1057 let ctx = body::LowerCtx::new(self.db.upcast(), self.file_id);
1058 let path = Path::from_src(path.clone(), &ctx)?;
1059 resolve_hir_path(self.db, &self.resolver, &path)