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 descend_node_at_offset<N: ast::AstNode>(
192 self.imp.descend_node_at_offset(node, offset).flatten().find_map(N::cast)
195 pub fn hir_file_for(&self, syntax_node: &SyntaxNode) -> HirFileId {
196 self.imp.find_file(syntax_node.clone()).file_id
199 pub fn original_range(&self, node: &SyntaxNode) -> FileRange {
200 self.imp.original_range(node)
203 pub fn diagnostics_display_range(&self, diagnostics: InFile<SyntaxNodePtr>) -> FileRange {
204 self.imp.diagnostics_display_range(diagnostics)
207 pub fn token_ancestors_with_macros(
210 ) -> impl Iterator<Item = SyntaxNode> + '_ {
211 token.parent().into_iter().flat_map(move |it| self.ancestors_with_macros(it))
214 pub fn ancestors_with_macros(&self, node: SyntaxNode) -> impl Iterator<Item = SyntaxNode> + '_ {
215 self.imp.ancestors_with_macros(node)
218 pub fn ancestors_at_offset_with_macros(
222 ) -> impl Iterator<Item = SyntaxNode> + '_ {
223 self.imp.ancestors_at_offset_with_macros(node, offset)
226 /// Find an AstNode by offset inside SyntaxNode, if it is inside *Macrofile*,
227 /// search up until it is of the target AstNode type
228 pub fn find_node_at_offset_with_macros<N: AstNode>(
233 self.imp.ancestors_at_offset_with_macros(node, offset).find_map(N::cast)
236 /// Find an AstNode by offset inside SyntaxNode, if it is inside *MacroCall*,
237 /// descend it and find again
238 pub fn find_node_at_offset_with_descend<N: AstNode>(
243 self.imp.descend_node_at_offset(node, offset).flatten().find_map(N::cast)
246 /// Find an AstNode by offset inside SyntaxNode, if it is inside *MacroCall*,
247 /// descend it and find again
248 pub fn find_nodes_at_offset_with_descend<'slf, N: AstNode + 'slf>(
252 ) -> impl Iterator<Item = N> + 'slf {
253 self.imp.descend_node_at_offset(node, offset).filter_map(|mut it| it.find_map(N::cast))
256 pub fn resolve_lifetime_param(&self, lifetime: &ast::Lifetime) -> Option<LifetimeParam> {
257 self.imp.resolve_lifetime_param(lifetime)
260 pub fn resolve_label(&self, lifetime: &ast::Lifetime) -> Option<Label> {
261 self.imp.resolve_label(lifetime)
264 pub fn resolve_type(&self, ty: &ast::Type) -> Option<Type> {
265 self.imp.resolve_type(ty)
268 pub fn type_of_expr(&self, expr: &ast::Expr) -> Option<TypeInfo> {
269 self.imp.type_of_expr(expr)
272 pub fn type_of_pat(&self, pat: &ast::Pat) -> Option<TypeInfo> {
273 self.imp.type_of_pat(pat)
276 pub fn type_of_self(&self, param: &ast::SelfParam) -> Option<Type> {
277 self.imp.type_of_self(param)
280 pub fn resolve_method_call(&self, call: &ast::MethodCallExpr) -> Option<Function> {
281 self.imp.resolve_method_call(call).map(Function::from)
284 pub fn resolve_method_call_as_callable(&self, call: &ast::MethodCallExpr) -> Option<Callable> {
285 self.imp.resolve_method_call_as_callable(call)
288 pub fn resolve_field(&self, field: &ast::FieldExpr) -> Option<Field> {
289 self.imp.resolve_field(field)
292 pub fn resolve_record_field(
294 field: &ast::RecordExprField,
295 ) -> Option<(Field, Option<Local>, Type)> {
296 self.imp.resolve_record_field(field)
299 pub fn resolve_record_pat_field(&self, field: &ast::RecordPatField) -> Option<Field> {
300 self.imp.resolve_record_pat_field(field)
303 pub fn resolve_macro_call(&self, macro_call: &ast::MacroCall) -> Option<MacroDef> {
304 self.imp.resolve_macro_call(macro_call)
307 pub fn resolve_attr_macro_call(&self, item: &ast::Item) -> Option<MacroDef> {
308 self.imp.resolve_attr_macro_call(item)
311 pub fn resolve_path(&self, path: &ast::Path) -> Option<PathResolution> {
312 self.imp.resolve_path(path)
315 pub fn resolve_extern_crate(&self, extern_crate: &ast::ExternCrate) -> Option<Crate> {
316 self.imp.resolve_extern_crate(extern_crate)
319 pub fn resolve_variant(&self, record_lit: ast::RecordExpr) -> Option<VariantDef> {
320 self.imp.resolve_variant(record_lit).map(VariantDef::from)
323 pub fn resolve_bind_pat_to_const(&self, pat: &ast::IdentPat) -> Option<ModuleDef> {
324 self.imp.resolve_bind_pat_to_const(pat)
327 // FIXME: use this instead?
328 // pub fn resolve_name_ref(&self, name_ref: &ast::NameRef) -> Option<???>;
330 pub fn record_literal_missing_fields(&self, literal: &ast::RecordExpr) -> Vec<(Field, Type)> {
331 self.imp.record_literal_missing_fields(literal)
334 pub fn record_pattern_missing_fields(&self, pattern: &ast::RecordPat) -> Vec<(Field, Type)> {
335 self.imp.record_pattern_missing_fields(pattern)
338 pub fn to_def<T: ToDef>(&self, src: &T) -> Option<T::Def> {
339 let src = self.imp.find_file(src.syntax().clone()).with_value(src).cloned();
340 T::to_def(&self.imp, src)
343 pub fn to_module_def(&self, file: FileId) -> Option<Module> {
344 self.imp.to_module_def(file).next()
347 pub fn to_module_defs(&self, file: FileId) -> impl Iterator<Item = Module> {
348 self.imp.to_module_def(file)
351 pub fn scope(&self, node: &SyntaxNode) -> SemanticsScope<'db> {
355 pub fn scope_at_offset(&self, token: &SyntaxToken, offset: TextSize) -> SemanticsScope<'db> {
356 self.imp.scope_at_offset(&token.parent().unwrap(), offset)
359 pub fn scope_for_def(&self, def: Trait) -> SemanticsScope<'db> {
360 self.imp.scope_for_def(def)
363 pub fn assert_contains_node(&self, node: &SyntaxNode) {
364 self.imp.assert_contains_node(node)
367 pub fn is_unsafe_method_call(&self, method_call_expr: &ast::MethodCallExpr) -> bool {
368 self.imp.is_unsafe_method_call(method_call_expr)
371 pub fn is_unsafe_ref_expr(&self, ref_expr: &ast::RefExpr) -> bool {
372 self.imp.is_unsafe_ref_expr(ref_expr)
375 pub fn is_unsafe_ident_pat(&self, ident_pat: &ast::IdentPat) -> bool {
376 self.imp.is_unsafe_ident_pat(ident_pat)
380 impl<'db> SemanticsImpl<'db> {
381 fn new(db: &'db dyn HirDatabase) -> Self {
384 s2d_cache: Default::default(),
385 cache: Default::default(),
386 expansion_info_cache: Default::default(),
390 fn parse(&self, file_id: FileId) -> ast::SourceFile {
391 let tree = self.db.parse(file_id).tree();
392 self.cache(tree.syntax().clone(), file_id.into());
396 fn expand(&self, macro_call: &ast::MacroCall) -> Option<SyntaxNode> {
397 let sa = self.analyze(macro_call.syntax());
398 let file_id = sa.expand(self.db, InFile::new(sa.file_id, macro_call))?;
399 let node = self.db.parse_or_expand(file_id)?;
400 self.cache(node.clone(), file_id);
404 fn expand_attr_macro(&self, item: &ast::Item) -> Option<SyntaxNode> {
405 let sa = self.analyze(item.syntax());
406 let src = InFile::new(sa.file_id, item.clone());
407 let macro_call_id = self.with_ctx(|ctx| ctx.item_to_macro_call(src))?;
408 let file_id = macro_call_id.as_file();
409 let node = self.db.parse_or_expand(file_id)?;
410 self.cache(node.clone(), file_id);
414 fn expand_derive_macro(&self, attr: &ast::Attr) -> Option<Vec<SyntaxNode>> {
415 let item = attr.syntax().parent().and_then(ast::Item::cast)?;
416 let sa = self.analyze(item.syntax());
417 let item = InFile::new(sa.file_id, &item);
418 let src = InFile::new(sa.file_id, attr.clone());
419 self.with_ctx(|ctx| {
420 let macro_call_ids = ctx.attr_to_derive_macro_call(item, src)?;
422 let expansions: Vec<_> = macro_call_ids
424 .map(|call| call.as_file())
425 .flat_map(|file_id| {
426 let node = self.db.parse_or_expand(file_id)?;
427 self.cache(node.clone(), file_id);
431 if expansions.is_empty() {
439 fn is_attr_macro_call(&self, item: &ast::Item) -> bool {
440 let sa = self.analyze(item.syntax());
441 let src = InFile::new(sa.file_id, item.clone());
442 self.with_ctx(|ctx| ctx.item_to_macro_call(src).is_some())
445 fn speculative_expand(
447 actual_macro_call: &ast::MacroCall,
448 speculative_args: &ast::TokenTree,
449 token_to_map: SyntaxToken,
450 ) -> Option<(SyntaxNode, SyntaxToken)> {
451 let sa = self.analyze(actual_macro_call.syntax());
452 let macro_call = InFile::new(sa.file_id, actual_macro_call);
453 let krate = sa.resolver.krate()?;
454 let macro_call_id = macro_call.as_call_id(self.db.upcast(), krate, |path| {
455 sa.resolver.resolve_path_as_macro(self.db.upcast(), &path)
457 hir_expand::db::expand_speculative(
460 speculative_args.syntax(),
465 fn speculative_expand_attr(
467 actual_macro_call: &ast::Item,
468 speculative_args: &ast::Item,
469 token_to_map: SyntaxToken,
470 ) -> Option<(SyntaxNode, SyntaxToken)> {
471 let sa = self.analyze(actual_macro_call.syntax());
472 let macro_call = InFile::new(sa.file_id, actual_macro_call.clone());
473 let macro_call_id = self.with_ctx(|ctx| ctx.item_to_macro_call(macro_call))?;
474 hir_expand::db::expand_speculative(
477 speculative_args.syntax(),
482 fn descend_into_macros(&self, token: SyntaxToken) -> SmallVec<[SyntaxToken; 1]> {
483 let _p = profile::span("descend_into_macros");
484 let parent = match token.parent() {
486 None => return smallvec![token],
488 let sa = self.analyze(&parent);
489 let mut queue = vec![InFile::new(sa.file_id, token)];
490 let mut cache = self.expansion_info_cache.borrow_mut();
491 let mut res = smallvec![];
492 // Remap the next token in the queue into a macro call its in, if it is not being remapped
493 // either due to not being in a macro-call or because its unused push it into the result vec,
494 // otherwise push the remapped tokens back into the queue as they can potentially be remapped again.
495 while let Some(token) = queue.pop() {
496 self.db.unwind_if_cancelled();
497 let was_not_remapped = (|| {
498 if let Some((call_id, item)) = token
501 .filter_map(ast::Item::cast)
503 self.with_ctx(|ctx| ctx.item_to_macro_call(token.with_value(item.clone())))
508 let file_id = call_id.as_file();
511 .or_insert_with(|| file_id.expansion_info(self.db.upcast()))
513 .map_token_down(self.db.upcast(), Some(item), token.as_ref())?;
515 let len = queue.len();
516 queue.extend(tokens.inspect(|token| {
517 if let Some(parent) = token.value.parent() {
518 self.cache(find_root(&parent), token.file_id);
521 return (queue.len() != len).then(|| ());
524 if let Some(macro_call) = token.value.ancestors().find_map(ast::MacroCall::cast) {
525 let tt = macro_call.token_tree()?;
526 let l_delim = match tt.left_delimiter_token() {
527 Some(it) => it.text_range().end(),
528 None => tt.syntax().text_range().start(),
530 let r_delim = match tt.right_delimiter_token() {
531 Some(it) => it.text_range().start(),
532 None => tt.syntax().text_range().end(),
534 if !TextRange::new(l_delim, r_delim).contains_range(token.value.text_range()) {
537 let file_id = sa.expand(self.db, token.with_value(¯o_call))?;
540 .or_insert_with(|| file_id.expansion_info(self.db.upcast()))
542 .map_token_down(self.db.upcast(), None, token.as_ref())?;
544 let len = queue.len();
545 queue.extend(tokens.inspect(|token| {
546 if let Some(parent) = token.value.parent() {
547 self.cache(find_root(&parent), token.file_id);
550 return (queue.len() != len).then(|| ());
556 if was_not_remapped {
557 res.push(token.value)
563 // Note this return type is deliberate as [`find_nodes_at_offset_with_descend`] wants to stop
564 // traversing the inner iterator when it finds a node.
565 fn descend_node_at_offset(
569 ) -> impl Iterator<Item = impl Iterator<Item = SyntaxNode> + '_> + '_ {
570 // Handle macro token cases
571 node.token_at_offset(offset)
572 .map(move |token| self.descend_into_macros(token))
573 .map(|it| it.into_iter().map(move |it| self.token_ancestors_with_macros(it)))
577 fn original_range(&self, node: &SyntaxNode) -> FileRange {
578 let node = self.find_file(node.clone());
579 node.as_ref().original_file_range(self.db.upcast())
582 fn diagnostics_display_range(&self, src: InFile<SyntaxNodePtr>) -> FileRange {
583 let root = self.db.parse_or_expand(src.file_id).unwrap();
584 let node = src.value.to_node(&root);
585 self.cache(root, src.file_id);
586 src.with_value(&node).original_file_range(self.db.upcast())
589 fn token_ancestors_with_macros(
592 ) -> impl Iterator<Item = SyntaxNode> + '_ {
593 token.parent().into_iter().flat_map(move |parent| self.ancestors_with_macros(parent))
596 fn ancestors_with_macros(&self, node: SyntaxNode) -> impl Iterator<Item = SyntaxNode> + '_ {
597 let node = self.find_file(node);
598 node.ancestors_with_macros(self.db.upcast()).map(|it| it.value)
601 fn ancestors_at_offset_with_macros(
605 ) -> impl Iterator<Item = SyntaxNode> + '_ {
606 node.token_at_offset(offset)
607 .map(|token| self.token_ancestors_with_macros(token))
608 .kmerge_by(|node1, node2| node1.text_range().len() < node2.text_range().len())
611 fn resolve_lifetime_param(&self, lifetime: &ast::Lifetime) -> Option<LifetimeParam> {
612 let text = lifetime.text();
613 let lifetime_param = lifetime.syntax().ancestors().find_map(|syn| {
614 let gpl = match_ast! {
616 ast::Fn(it) => it.generic_param_list()?,
617 ast::TypeAlias(it) => it.generic_param_list()?,
618 ast::Struct(it) => it.generic_param_list()?,
619 ast::Enum(it) => it.generic_param_list()?,
620 ast::Union(it) => it.generic_param_list()?,
621 ast::Trait(it) => it.generic_param_list()?,
622 ast::Impl(it) => it.generic_param_list()?,
623 ast::WherePred(it) => it.generic_param_list()?,
624 ast::ForType(it) => it.generic_param_list()?,
628 gpl.lifetime_params()
629 .find(|tp| tp.lifetime().as_ref().map(|lt| lt.text()).as_ref() == Some(&text))
631 let src = self.find_file(lifetime_param.syntax().clone()).with_value(lifetime_param);
632 ToDef::to_def(self, src)
635 fn resolve_label(&self, lifetime: &ast::Lifetime) -> Option<Label> {
636 let text = lifetime.text();
637 let label = lifetime.syntax().ancestors().find_map(|syn| {
638 let label = match_ast! {
640 ast::ForExpr(it) => it.label(),
641 ast::WhileExpr(it) => it.label(),
642 ast::LoopExpr(it) => it.label(),
643 ast::EffectExpr(it) => it.label(),
649 .and_then(|lt| lt.lifetime_ident_token())
650 .map_or(false, |lt| lt.text() == text)
653 let src = self.find_file(label.syntax().clone()).with_value(label);
654 ToDef::to_def(self, src)
657 fn resolve_type(&self, ty: &ast::Type) -> Option<Type> {
658 let scope = self.scope(ty.syntax());
659 let ctx = body::LowerCtx::new(self.db.upcast(), scope.file_id);
660 let ty = hir_ty::TyLoweringContext::new(self.db, &scope.resolver)
661 .lower_ty(&crate::TypeRef::from_ast(&ctx, ty.clone()));
662 Type::new_with_resolver(self.db, &scope.resolver, ty)
665 fn type_of_expr(&self, expr: &ast::Expr) -> Option<TypeInfo> {
666 self.analyze(expr.syntax())
667 .type_of_expr(self.db, expr)
668 .map(|(ty, coerced)| TypeInfo { original: ty, adjusted: coerced })
671 fn type_of_pat(&self, pat: &ast::Pat) -> Option<TypeInfo> {
672 self.analyze(pat.syntax())
673 .type_of_pat(self.db, pat)
674 .map(|(ty, coerced)| TypeInfo { original: ty, adjusted: coerced })
677 fn type_of_self(&self, param: &ast::SelfParam) -> Option<Type> {
678 self.analyze(param.syntax()).type_of_self(self.db, param)
681 fn resolve_method_call(&self, call: &ast::MethodCallExpr) -> Option<FunctionId> {
682 self.analyze(call.syntax()).resolve_method_call(self.db, call).map(|(id, _)| id)
685 fn resolve_method_call_as_callable(&self, call: &ast::MethodCallExpr) -> Option<Callable> {
686 let (func, subst) = self.analyze(call.syntax()).resolve_method_call(self.db, call)?;
687 let ty = self.db.value_ty(func.into()).substitute(&Interner, &subst);
688 let resolver = self.analyze(call.syntax()).resolver;
689 let ty = Type::new_with_resolver(self.db, &resolver, ty)?;
690 let mut res = ty.as_callable(self.db)?;
691 res.is_bound_method = true;
695 fn resolve_field(&self, field: &ast::FieldExpr) -> Option<Field> {
696 self.analyze(field.syntax()).resolve_field(self.db, field)
699 fn resolve_record_field(
701 field: &ast::RecordExprField,
702 ) -> Option<(Field, Option<Local>, Type)> {
703 self.analyze(field.syntax()).resolve_record_field(self.db, field)
706 fn resolve_record_pat_field(&self, field: &ast::RecordPatField) -> Option<Field> {
707 self.analyze(field.syntax()).resolve_record_pat_field(self.db, field)
710 fn resolve_macro_call(&self, macro_call: &ast::MacroCall) -> Option<MacroDef> {
711 let sa = self.analyze(macro_call.syntax());
712 let macro_call = self.find_file(macro_call.syntax().clone()).with_value(macro_call);
713 sa.resolve_macro_call(self.db, macro_call)
716 fn resolve_attr_macro_call(&self, item: &ast::Item) -> Option<MacroDef> {
717 let item_in_file = self.find_file(item.syntax().clone()).with_value(item.clone());
718 let macro_call_id = self.with_ctx(|ctx| ctx.item_to_macro_call(item_in_file))?;
719 Some(MacroDef { id: self.db.lookup_intern_macro(macro_call_id).def })
722 fn resolve_path(&self, path: &ast::Path) -> Option<PathResolution> {
723 self.analyze(path.syntax()).resolve_path(self.db, path)
726 fn resolve_extern_crate(&self, extern_crate: &ast::ExternCrate) -> Option<Crate> {
727 let krate = self.scope(extern_crate.syntax()).krate()?;
728 krate.dependencies(self.db).into_iter().find_map(|dep| {
729 if dep.name == extern_crate.name_ref()?.as_name() {
737 fn resolve_variant(&self, record_lit: ast::RecordExpr) -> Option<VariantId> {
738 self.analyze(record_lit.syntax()).resolve_variant(self.db, record_lit)
741 fn resolve_bind_pat_to_const(&self, pat: &ast::IdentPat) -> Option<ModuleDef> {
742 self.analyze(pat.syntax()).resolve_bind_pat_to_const(self.db, pat)
745 fn record_literal_missing_fields(&self, literal: &ast::RecordExpr) -> Vec<(Field, Type)> {
746 self.analyze(literal.syntax())
747 .record_literal_missing_fields(self.db, literal)
751 fn record_pattern_missing_fields(&self, pattern: &ast::RecordPat) -> Vec<(Field, Type)> {
752 self.analyze(pattern.syntax())
753 .record_pattern_missing_fields(self.db, pattern)
757 fn with_ctx<F: FnOnce(&mut SourceToDefCtx) -> T, T>(&self, f: F) -> T {
758 let mut cache = self.s2d_cache.borrow_mut();
759 let mut ctx = SourceToDefCtx { db: self.db, cache: &mut *cache };
763 fn to_module_def(&self, file: FileId) -> impl Iterator<Item = Module> {
764 self.with_ctx(|ctx| ctx.file_to_def(file)).into_iter().map(Module::from)
767 fn scope(&self, node: &SyntaxNode) -> SemanticsScope<'db> {
768 let sa = self.analyze(node);
769 SemanticsScope { db: self.db, file_id: sa.file_id, resolver: sa.resolver }
772 fn scope_at_offset(&self, node: &SyntaxNode, offset: TextSize) -> SemanticsScope<'db> {
773 let sa = self.analyze_with_offset(node, offset);
774 SemanticsScope { db: self.db, file_id: sa.file_id, resolver: sa.resolver }
777 fn scope_for_def(&self, def: Trait) -> SemanticsScope<'db> {
778 let file_id = self.db.lookup_intern_trait(def.id).id.file_id();
779 let resolver = def.id.resolver(self.db.upcast());
780 SemanticsScope { db: self.db, file_id, resolver }
783 fn analyze(&self, node: &SyntaxNode) -> SourceAnalyzer {
784 self.analyze_impl(node, None)
786 fn analyze_with_offset(&self, node: &SyntaxNode, offset: TextSize) -> SourceAnalyzer {
787 self.analyze_impl(node, Some(offset))
789 fn analyze_impl(&self, node: &SyntaxNode, offset: Option<TextSize>) -> SourceAnalyzer {
790 let _p = profile::span("Semantics::analyze_impl");
791 let node = self.find_file(node.clone());
792 let node = node.as_ref();
794 let container = match self.with_ctx(|ctx| ctx.find_container(node)) {
796 None => return SourceAnalyzer::new_for_resolver(Resolver::default(), node),
799 let resolver = match container {
800 ChildContainer::DefWithBodyId(def) => {
801 return SourceAnalyzer::new_for_body(self.db, def, node, offset)
803 ChildContainer::TraitId(it) => it.resolver(self.db.upcast()),
804 ChildContainer::ImplId(it) => it.resolver(self.db.upcast()),
805 ChildContainer::ModuleId(it) => it.resolver(self.db.upcast()),
806 ChildContainer::EnumId(it) => it.resolver(self.db.upcast()),
807 ChildContainer::VariantId(it) => it.resolver(self.db.upcast()),
808 ChildContainer::TypeAliasId(it) => it.resolver(self.db.upcast()),
809 ChildContainer::GenericDefId(it) => it.resolver(self.db.upcast()),
811 SourceAnalyzer::new_for_resolver(resolver, node)
814 fn cache(&self, root_node: SyntaxNode, file_id: HirFileId) {
815 assert!(root_node.parent().is_none());
816 let mut cache = self.cache.borrow_mut();
817 let prev = cache.insert(root_node, file_id);
818 assert!(prev == None || prev == Some(file_id))
821 fn assert_contains_node(&self, node: &SyntaxNode) {
822 self.find_file(node.clone());
825 fn lookup(&self, root_node: &SyntaxNode) -> Option<HirFileId> {
826 let cache = self.cache.borrow();
827 cache.get(root_node).copied()
830 fn find_file(&self, node: SyntaxNode) -> InFile<SyntaxNode> {
831 let root_node = find_root(&node);
832 let file_id = self.lookup(&root_node).unwrap_or_else(|| {
834 "\n\nFailed to lookup {:?} in this Semantics.\n\
835 Make sure to use only query nodes, derived from this instance of Semantics.\n\
837 known nodes: {}\n\n",
843 .map(|it| format!("{:?}", it))
848 InFile::new(file_id, node)
851 fn is_unsafe_method_call(&self, method_call_expr: &ast::MethodCallExpr) -> bool {
855 let field_expr = match expr {
856 ast::Expr::FieldExpr(field_expr) => field_expr,
859 let ty = self.type_of_expr(&field_expr.expr()?)?.original;
860 if !ty.is_packed(self.db) {
864 let func = self.resolve_method_call(method_call_expr).map(Function::from)?;
865 let res = match func.self_param(self.db)?.access(self.db) {
866 Access::Shared | Access::Exclusive => true,
867 Access::Owned => false,
874 fn is_unsafe_ref_expr(&self, ref_expr: &ast::RefExpr) -> bool {
878 let field_expr = match expr {
879 ast::Expr::FieldExpr(field_expr) => field_expr,
882 let expr = field_expr.expr()?;
883 self.type_of_expr(&expr)
885 // Binding a reference to a packed type is possibly unsafe.
886 .map(|ty| ty.original.is_packed(self.db))
889 // FIXME This needs layout computation to be correct. It will highlight
890 // more than it should with the current implementation.
893 fn is_unsafe_ident_pat(&self, ident_pat: &ast::IdentPat) -> bool {
894 if ident_pat.ref_token().is_none() {
902 // `IdentPat` can live under `RecordPat` directly under `RecordPatField` or
903 // `RecordPatFieldList`. `RecordPatField` also lives under `RecordPatFieldList`,
904 // so this tries to lookup the `IdentPat` anywhere along that structure to the
905 // `RecordPat` so we can get the containing type.
906 let record_pat = ast::RecordPatField::cast(parent.clone())
907 .and_then(|record_pat| record_pat.syntax().parent())
908 .or_else(|| Some(parent.clone()))
910 ast::RecordPatFieldList::cast(parent)?
913 .and_then(ast::RecordPat::cast)
916 // If this doesn't match a `RecordPat`, fallback to a `LetStmt` to see if
917 // this is initialized from a `FieldExpr`.
918 if let Some(record_pat) = record_pat {
919 self.type_of_pat(&ast::Pat::RecordPat(record_pat))
920 } else if let Some(let_stmt) = ast::LetStmt::cast(parent) {
921 let field_expr = match let_stmt.initializer()? {
922 ast::Expr::FieldExpr(field_expr) => field_expr,
926 self.type_of_expr(&field_expr.expr()?)
931 // Binding a reference to a packed type is possibly unsafe.
932 .map(|ty| ty.original.is_packed(self.db))
937 pub trait ToDef: AstNode + Clone {
940 fn to_def(sema: &SemanticsImpl, src: InFile<Self>) -> Option<Self::Def>;
943 macro_rules! to_def_impls {
944 ($(($def:path, $ast:path, $meth:ident)),* ,) => {$(
945 impl ToDef for $ast {
947 fn to_def(sema: &SemanticsImpl, src: InFile<Self>) -> Option<Self::Def> {
948 sema.with_ctx(|ctx| ctx.$meth(src)).map(<$def>::from)
955 (crate::Module, ast::Module, module_to_def),
956 (crate::Module, ast::SourceFile, source_file_to_def),
957 (crate::Struct, ast::Struct, struct_to_def),
958 (crate::Enum, ast::Enum, enum_to_def),
959 (crate::Union, ast::Union, union_to_def),
960 (crate::Trait, ast::Trait, trait_to_def),
961 (crate::Impl, ast::Impl, impl_to_def),
962 (crate::TypeAlias, ast::TypeAlias, type_alias_to_def),
963 (crate::Const, ast::Const, const_to_def),
964 (crate::Static, ast::Static, static_to_def),
965 (crate::Function, ast::Fn, fn_to_def),
966 (crate::Field, ast::RecordField, record_field_to_def),
967 (crate::Field, ast::TupleField, tuple_field_to_def),
968 (crate::Variant, ast::Variant, enum_variant_to_def),
969 (crate::TypeParam, ast::TypeParam, type_param_to_def),
970 (crate::LifetimeParam, ast::LifetimeParam, lifetime_param_to_def),
971 (crate::ConstParam, ast::ConstParam, const_param_to_def),
972 (crate::MacroDef, ast::Macro, macro_to_def),
973 (crate::Local, ast::IdentPat, bind_pat_to_def),
974 (crate::Local, ast::SelfParam, self_param_to_def),
975 (crate::Label, ast::Label, label_to_def),
976 (crate::Adt, ast::Adt, adt_to_def),
979 fn find_root(node: &SyntaxNode) -> SyntaxNode {
980 node.ancestors().last().unwrap()
983 /// `SemanticScope` encapsulates the notion of a scope (the set of visible
984 /// names) at a particular program point.
986 /// It is a bit tricky, as scopes do not really exist inside the compiler.
987 /// Rather, the compiler directly computes for each reference the definition it
988 /// refers to. It might transiently compute the explicit scope map while doing
989 /// so, but, generally, this is not something left after the analysis.
991 /// However, we do very much need explicit scopes for IDE purposes --
992 /// completion, at its core, lists the contents of the current scope. The notion
993 /// of scope is also useful to answer questions like "what would be the meaning
994 /// of this piece of code if we inserted it into this position?".
996 /// So `SemanticsScope` is constructed from a specific program point (a syntax
997 /// node or just a raw offset) and provides access to the set of visible names
998 /// on a somewhat best-effort basis.
1000 /// Note that if you are wondering "what does this specific existing name mean?",
1001 /// you'd better use the `resolve_` family of methods.
1003 pub struct SemanticsScope<'a> {
1004 pub db: &'a dyn HirDatabase,
1009 impl<'a> SemanticsScope<'a> {
1010 pub fn module(&self) -> Option<Module> {
1011 Some(Module { id: self.resolver.module()? })
1014 pub fn krate(&self) -> Option<Crate> {
1015 Some(Crate { id: self.resolver.krate()? })
1018 /// Note: `FxHashSet<TraitId>` should be treated as an opaque type, passed into `Type
1019 // FIXME: rename to visible_traits to not repeat scope?
1020 pub fn traits_in_scope(&self) -> FxHashSet<TraitId> {
1021 let resolver = &self.resolver;
1022 resolver.traits_in_scope(self.db.upcast())
1025 pub fn process_all_names(&self, f: &mut dyn FnMut(Name, ScopeDef)) {
1026 let scope = self.resolver.names_in_scope(self.db.upcast());
1027 for (name, entries) in scope {
1028 for entry in entries {
1029 let def = match entry {
1030 resolver::ScopeDef::ModuleDef(it) => ScopeDef::ModuleDef(it.into()),
1031 resolver::ScopeDef::MacroDef(it) => ScopeDef::MacroDef(it.into()),
1032 resolver::ScopeDef::Unknown => ScopeDef::Unknown,
1033 resolver::ScopeDef::ImplSelfType(it) => ScopeDef::ImplSelfType(it.into()),
1034 resolver::ScopeDef::AdtSelfType(it) => ScopeDef::AdtSelfType(it.into()),
1035 resolver::ScopeDef::GenericParam(id) => ScopeDef::GenericParam(id.into()),
1036 resolver::ScopeDef::Local(pat_id) => {
1037 let parent = self.resolver.body_owner().unwrap();
1038 ScopeDef::Local(Local { parent, pat_id })
1040 resolver::ScopeDef::Label(label_id) => {
1041 let parent = self.resolver.body_owner().unwrap();
1042 ScopeDef::Label(Label { parent, label_id })
1045 f(name.clone(), def)
1050 /// Resolve a path as-if it was written at the given scope. This is
1051 /// necessary a heuristic, as it doesn't take hygiene into account.
1052 pub fn speculative_resolve(&self, path: &ast::Path) -> Option<PathResolution> {
1053 let ctx = body::LowerCtx::new(self.db.upcast(), self.file_id);
1054 let path = Path::from_src(path.clone(), &ctx)?;
1055 resolve_hir_path(self.db, &self.resolver, &path)