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 algo::skip_trivia_token,
20 ast::{self, HasGenericParams, HasLoopBody},
21 match_ast, AstNode, Direction, SyntaxNode, SyntaxNodePtr, SyntaxToken, TextRange, TextSize,
26 semantics::source_to_def::{ChildContainer, SourceToDefCache, SourceToDefCtx},
27 source_analyzer::{resolve_hir_path, resolve_hir_path_as_macro, SourceAnalyzer},
28 Access, AssocItem, Callable, ConstParam, Crate, Field, Function, HasSource, HirFileId, Impl,
29 InFile, Label, LifetimeParam, Local, MacroDef, Module, ModuleDef, Name, Path, ScopeDef, Trait,
30 Type, TypeAlias, TypeParam, VariantDef,
33 #[derive(Debug, Clone, PartialEq, Eq)]
34 pub enum PathResolution {
37 /// A local binding (only value namespace)
42 ConstParam(ConstParam),
49 fn in_type_ns(&self) -> Option<TypeNs> {
51 PathResolution::Def(ModuleDef::Adt(adt)) => Some(TypeNs::AdtId((*adt).into())),
52 PathResolution::Def(ModuleDef::BuiltinType(builtin)) => {
53 Some(TypeNs::BuiltinType((*builtin).into()))
57 | ModuleDef::Variant(_)
58 | ModuleDef::Function(_)
59 | ModuleDef::Module(_)
60 | ModuleDef::Static(_)
61 | ModuleDef::Trait(_),
63 PathResolution::Def(ModuleDef::TypeAlias(alias)) => {
64 Some(TypeNs::TypeAliasId((*alias).into()))
66 PathResolution::Local(_) | PathResolution::Macro(_) | PathResolution::ConstParam(_) => {
69 PathResolution::TypeParam(param) => Some(TypeNs::GenericParam((*param).into())),
70 PathResolution::SelfType(impl_def) => Some(TypeNs::SelfType((*impl_def).into())),
71 PathResolution::AssocItem(AssocItem::Const(_) | AssocItem::Function(_)) => None,
72 PathResolution::AssocItem(AssocItem::TypeAlias(alias)) => {
73 Some(TypeNs::TypeAliasId((*alias).into()))
78 /// Returns an iterator over associated types that may be specified after this path (using
79 /// `Ty::Assoc` syntax).
80 pub fn assoc_type_shorthand_candidates<R>(
83 mut cb: impl FnMut(&Name, TypeAlias) -> Option<R>,
85 associated_type_shorthand_candidates(db, self.in_type_ns()?, |name, _, id| {
93 /// The original type of the expression or pattern.
95 /// The adjusted type, if an adjustment happened.
96 pub adjusted: Option<Type>,
100 pub fn original(self) -> Type {
104 pub fn has_adjustment(&self) -> bool {
105 self.adjusted.is_some()
108 /// The adjusted type, or the original in case no adjustments occurred.
109 pub fn adjusted(self) -> Type {
110 self.adjusted.unwrap_or(self.original)
114 /// Primary API to get semantic information, like types, from syntax trees.
115 pub struct Semantics<'db, DB> {
117 imp: SemanticsImpl<'db>,
120 pub struct SemanticsImpl<'db> {
121 pub db: &'db dyn HirDatabase,
122 s2d_cache: RefCell<SourceToDefCache>,
123 expansion_info_cache: RefCell<FxHashMap<HirFileId, Option<ExpansionInfo>>>,
124 cache: RefCell<FxHashMap<SyntaxNode, HirFileId>>,
127 impl<DB> fmt::Debug for Semantics<'_, DB> {
128 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
129 write!(f, "Semantics {{ ... }}")
133 impl<'db, DB: HirDatabase> Semantics<'db, DB> {
134 pub fn new(db: &DB) -> Semantics<DB> {
135 let impl_ = SemanticsImpl::new(db);
136 Semantics { db, imp: impl_ }
139 pub fn parse(&self, file_id: FileId) -> ast::SourceFile {
140 self.imp.parse(file_id)
143 pub fn expand(&self, macro_call: &ast::MacroCall) -> Option<SyntaxNode> {
144 self.imp.expand(macro_call)
147 /// If `item` has an attribute macro attached to it, expands it.
148 pub fn expand_attr_macro(&self, item: &ast::Item) -> Option<SyntaxNode> {
149 self.imp.expand_attr_macro(item)
152 pub fn expand_derive_macro(&self, derive: &ast::Attr) -> Option<Vec<SyntaxNode>> {
153 self.imp.expand_derive_macro(derive)
156 pub fn is_attr_macro_call(&self, item: &ast::Item) -> bool {
157 self.imp.is_attr_macro_call(item)
160 pub fn speculative_expand(
162 actual_macro_call: &ast::MacroCall,
163 speculative_args: &ast::TokenTree,
164 token_to_map: SyntaxToken,
165 ) -> Option<(SyntaxNode, SyntaxToken)> {
166 self.imp.speculative_expand(actual_macro_call, speculative_args, token_to_map)
169 pub fn speculative_expand_attr_macro(
171 actual_macro_call: &ast::Item,
172 speculative_args: &ast::Item,
173 token_to_map: SyntaxToken,
174 ) -> Option<(SyntaxNode, SyntaxToken)> {
175 self.imp.speculative_expand_attr(actual_macro_call, speculative_args, token_to_map)
178 pub fn descend_into_macros_single(&self, token: SyntaxToken) -> SyntaxToken {
179 self.imp.descend_into_macros(token).pop().unwrap()
182 pub fn descend_into_macros(&self, token: SyntaxToken) -> SmallVec<[SyntaxToken; 1]> {
183 self.imp.descend_into_macros(token)
186 /// Maps a node down by mapping its first and last token down.
187 pub fn descend_node_into_attributes<N: AstNode>(&self, node: N) -> SmallVec<[N; 1]> {
188 self.imp.descend_node_into_attributes(node)
191 /// Search for a definition's source and cache its syntax tree
192 pub fn source<Def: HasSource>(&self, def: Def) -> Option<InFile<Def::Ast>>
199 pub fn hir_file_for(&self, syntax_node: &SyntaxNode) -> HirFileId {
200 self.imp.find_file(syntax_node.clone()).file_id
203 pub fn original_range(&self, node: &SyntaxNode) -> FileRange {
204 self.imp.original_range(node)
207 pub fn original_range_opt(&self, node: &SyntaxNode) -> Option<FileRange> {
208 self.imp.original_range_opt(node)
211 pub fn original_ast_node<N: AstNode>(&self, node: N) -> Option<N> {
212 self.imp.original_ast_node(node)
215 pub fn diagnostics_display_range(&self, diagnostics: InFile<SyntaxNodePtr>) -> FileRange {
216 self.imp.diagnostics_display_range(diagnostics)
219 pub fn token_ancestors_with_macros(
222 ) -> impl Iterator<Item = SyntaxNode> + '_ {
223 token.parent().into_iter().flat_map(move |it| self.ancestors_with_macros(it))
226 pub fn ancestors_with_macros(&self, node: SyntaxNode) -> impl Iterator<Item = SyntaxNode> + '_ {
227 self.imp.ancestors_with_macros(node)
230 pub fn ancestors_at_offset_with_macros(
234 ) -> impl Iterator<Item = SyntaxNode> + '_ {
235 self.imp.ancestors_at_offset_with_macros(node, offset)
238 /// Find an AstNode by offset inside SyntaxNode, if it is inside *Macrofile*,
239 /// search up until it is of the target AstNode type
240 pub fn find_node_at_offset_with_macros<N: AstNode>(
245 self.imp.ancestors_at_offset_with_macros(node, offset).find_map(N::cast)
248 /// Find an AstNode by offset inside SyntaxNode, if it is inside *MacroCall*,
249 /// descend it and find again
250 pub fn find_node_at_offset_with_descend<N: AstNode>(
255 self.imp.descend_node_at_offset(node, offset).flatten().find_map(N::cast)
258 /// Find an AstNode by offset inside SyntaxNode, if it is inside *MacroCall*,
259 /// descend it and find again
260 pub fn find_nodes_at_offset_with_descend<'slf, N: AstNode + 'slf>(
264 ) -> impl Iterator<Item = N> + 'slf {
265 self.imp.descend_node_at_offset(node, offset).filter_map(|mut it| it.find_map(N::cast))
268 pub fn resolve_lifetime_param(&self, lifetime: &ast::Lifetime) -> Option<LifetimeParam> {
269 self.imp.resolve_lifetime_param(lifetime)
272 pub fn resolve_label(&self, lifetime: &ast::Lifetime) -> Option<Label> {
273 self.imp.resolve_label(lifetime)
276 pub fn resolve_type(&self, ty: &ast::Type) -> Option<Type> {
277 self.imp.resolve_type(ty)
280 pub fn type_of_expr(&self, expr: &ast::Expr) -> Option<TypeInfo> {
281 self.imp.type_of_expr(expr)
284 pub fn type_of_pat(&self, pat: &ast::Pat) -> Option<TypeInfo> {
285 self.imp.type_of_pat(pat)
288 pub fn type_of_self(&self, param: &ast::SelfParam) -> Option<Type> {
289 self.imp.type_of_self(param)
292 pub fn resolve_method_call(&self, call: &ast::MethodCallExpr) -> Option<Function> {
293 self.imp.resolve_method_call(call).map(Function::from)
296 pub fn resolve_method_call_as_callable(&self, call: &ast::MethodCallExpr) -> Option<Callable> {
297 self.imp.resolve_method_call_as_callable(call)
300 pub fn resolve_field(&self, field: &ast::FieldExpr) -> Option<Field> {
301 self.imp.resolve_field(field)
304 pub fn resolve_record_field(
306 field: &ast::RecordExprField,
307 ) -> Option<(Field, Option<Local>, Type)> {
308 self.imp.resolve_record_field(field)
311 pub fn resolve_record_pat_field(&self, field: &ast::RecordPatField) -> Option<Field> {
312 self.imp.resolve_record_pat_field(field)
315 pub fn resolve_macro_call(&self, macro_call: &ast::MacroCall) -> Option<MacroDef> {
316 self.imp.resolve_macro_call(macro_call)
319 pub fn resolve_attr_macro_call(&self, item: &ast::Item) -> Option<MacroDef> {
320 self.imp.resolve_attr_macro_call(item)
323 pub fn resolve_path(&self, path: &ast::Path) -> Option<PathResolution> {
324 self.imp.resolve_path(path)
327 pub fn resolve_extern_crate(&self, extern_crate: &ast::ExternCrate) -> Option<Crate> {
328 self.imp.resolve_extern_crate(extern_crate)
331 pub fn resolve_variant(&self, record_lit: ast::RecordExpr) -> Option<VariantDef> {
332 self.imp.resolve_variant(record_lit).map(VariantDef::from)
335 pub fn resolve_bind_pat_to_const(&self, pat: &ast::IdentPat) -> Option<ModuleDef> {
336 self.imp.resolve_bind_pat_to_const(pat)
339 // FIXME: use this instead?
340 // pub fn resolve_name_ref(&self, name_ref: &ast::NameRef) -> Option<???>;
342 pub fn record_literal_missing_fields(&self, literal: &ast::RecordExpr) -> Vec<(Field, Type)> {
343 self.imp.record_literal_missing_fields(literal)
346 pub fn record_pattern_missing_fields(&self, pattern: &ast::RecordPat) -> Vec<(Field, Type)> {
347 self.imp.record_pattern_missing_fields(pattern)
350 pub fn to_def<T: ToDef>(&self, src: &T) -> Option<T::Def> {
351 let src = self.imp.find_file(src.syntax().clone()).with_value(src).cloned();
352 T::to_def(&self.imp, src)
355 pub fn to_module_def(&self, file: FileId) -> Option<Module> {
356 self.imp.to_module_def(file).next()
359 pub fn to_module_defs(&self, file: FileId) -> impl Iterator<Item = Module> {
360 self.imp.to_module_def(file)
363 pub fn scope(&self, node: &SyntaxNode) -> SemanticsScope<'db> {
367 pub fn scope_at_offset(&self, token: &SyntaxToken, offset: TextSize) -> SemanticsScope<'db> {
368 self.imp.scope_at_offset(&token.parent().unwrap(), offset)
371 pub fn scope_for_def(&self, def: Trait) -> SemanticsScope<'db> {
372 self.imp.scope_for_def(def)
375 pub fn assert_contains_node(&self, node: &SyntaxNode) {
376 self.imp.assert_contains_node(node)
379 pub fn is_unsafe_method_call(&self, method_call_expr: &ast::MethodCallExpr) -> bool {
380 self.imp.is_unsafe_method_call(method_call_expr)
383 pub fn is_unsafe_ref_expr(&self, ref_expr: &ast::RefExpr) -> bool {
384 self.imp.is_unsafe_ref_expr(ref_expr)
387 pub fn is_unsafe_ident_pat(&self, ident_pat: &ast::IdentPat) -> bool {
388 self.imp.is_unsafe_ident_pat(ident_pat)
392 impl<'db> SemanticsImpl<'db> {
393 fn new(db: &'db dyn HirDatabase) -> Self {
396 s2d_cache: Default::default(),
397 cache: Default::default(),
398 expansion_info_cache: Default::default(),
402 fn parse(&self, file_id: FileId) -> ast::SourceFile {
403 let tree = self.db.parse(file_id).tree();
404 self.cache(tree.syntax().clone(), file_id.into());
408 fn expand(&self, macro_call: &ast::MacroCall) -> Option<SyntaxNode> {
409 let sa = self.analyze(macro_call.syntax());
410 let file_id = sa.expand(self.db, InFile::new(sa.file_id, macro_call))?;
411 let node = self.db.parse_or_expand(file_id)?;
412 self.cache(node.clone(), file_id);
416 fn expand_attr_macro(&self, item: &ast::Item) -> Option<SyntaxNode> {
417 let sa = self.analyze(item.syntax());
418 let src = InFile::new(sa.file_id, item.clone());
419 let macro_call_id = self.with_ctx(|ctx| ctx.item_to_macro_call(src))?;
420 let file_id = macro_call_id.as_file();
421 let node = self.db.parse_or_expand(file_id)?;
422 self.cache(node.clone(), file_id);
426 fn expand_derive_macro(&self, attr: &ast::Attr) -> Option<Vec<SyntaxNode>> {
427 let item = attr.syntax().parent().and_then(ast::Item::cast)?;
428 let sa = self.analyze(item.syntax());
429 let item = InFile::new(sa.file_id, &item);
430 let src = InFile::new(sa.file_id, attr.clone());
431 self.with_ctx(|ctx| {
432 let macro_call_ids = ctx.attr_to_derive_macro_call(item, src)?;
434 let expansions: Vec<_> = macro_call_ids
436 .map(|call| call.as_file())
437 .flat_map(|file_id| {
438 let node = self.db.parse_or_expand(file_id)?;
439 self.cache(node.clone(), file_id);
443 if expansions.is_empty() {
451 fn is_attr_macro_call(&self, item: &ast::Item) -> bool {
452 let sa = self.analyze(item.syntax());
453 let src = InFile::new(sa.file_id, item.clone());
454 self.with_ctx(|ctx| ctx.item_to_macro_call(src).is_some())
457 fn speculative_expand(
459 actual_macro_call: &ast::MacroCall,
460 speculative_args: &ast::TokenTree,
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);
465 let krate = sa.resolver.krate()?;
466 let macro_call_id = macro_call.as_call_id(self.db.upcast(), krate, |path| {
467 sa.resolver.resolve_path_as_macro(self.db.upcast(), &path)
469 hir_expand::db::expand_speculative(
472 speculative_args.syntax(),
477 fn speculative_expand_attr(
479 actual_macro_call: &ast::Item,
480 speculative_args: &ast::Item,
481 token_to_map: SyntaxToken,
482 ) -> Option<(SyntaxNode, SyntaxToken)> {
483 let sa = self.analyze(actual_macro_call.syntax());
484 let macro_call = InFile::new(sa.file_id, actual_macro_call.clone());
485 let macro_call_id = self.with_ctx(|ctx| ctx.item_to_macro_call(macro_call))?;
486 hir_expand::db::expand_speculative(
489 speculative_args.syntax(),
494 // This might not be the correct way to do this, but it works for now
495 fn descend_node_into_attributes<N: AstNode>(&self, node: N) -> SmallVec<[N; 1]> {
496 let mut res = smallvec![];
498 let first = skip_trivia_token(node.syntax().first_token()?, Direction::Next)?;
499 let last = skip_trivia_token(node.syntax().last_token()?, Direction::Prev)?;
502 let (first, last) = match tokens {
508 self.descend_into_macros_impl(first, |InFile { value, .. }| {
509 if let Some(node) = value.ancestors().find_map(N::cast) {
514 // Descend first and last token, then zip them to look for the node they belong to
515 let mut scratch: SmallVec<[_; 1]> = smallvec![];
516 self.descend_into_macros_impl(first, |token| {
520 let mut scratch = scratch.into_iter();
521 self.descend_into_macros_impl(last, |InFile { value: last, file_id: last_fid }| {
522 if let Some(InFile { value: first, file_id: first_fid }) = scratch.next() {
523 if first_fid == last_fid {
524 if let Some(p) = first.parent() {
525 let range = first.text_range().cover(last.text_range());
526 let node = find_root(&p)
527 .covering_element(range)
529 .take_while(|it| it.text_range() == range)
531 if let Some(node) = node {
542 fn descend_into_macros(&self, token: SyntaxToken) -> SmallVec<[SyntaxToken; 1]> {
543 let mut res = smallvec![];
544 self.descend_into_macros_impl(token, |InFile { value, .. }| res.push(value));
548 fn descend_into_macros_impl(&self, token: SyntaxToken, mut f: impl FnMut(InFile<SyntaxToken>)) {
549 let _p = profile::span("descend_into_macros");
550 let parent = match token.parent() {
554 let sa = self.analyze(&parent);
555 let mut stack: SmallVec<[_; 1]> = smallvec![InFile::new(sa.file_id, token)];
556 let mut cache = self.expansion_info_cache.borrow_mut();
558 let mut process_expansion_for_token =
559 |stack: &mut SmallVec<_>, file_id, item, token: InFile<&_>| {
560 let mapped_tokens = cache
562 .or_insert_with(|| file_id.expansion_info(self.db.upcast()))
564 .map_token_down(self.db.upcast(), item, token)?;
566 let len = stack.len();
567 // requeue the tokens we got from mapping our current token down
568 stack.extend(mapped_tokens.inspect(|token| {
569 if let Some(parent) = token.value.parent() {
570 self.cache(find_root(&parent), token.file_id);
573 // if the length changed we have found a mapping for the token
574 (stack.len() != len).then(|| ())
577 // Remap the next token in the queue into a macro call its in, if it is not being remapped
578 // either due to not being in a macro-call or because its unused push it into the result vec,
579 // otherwise push the remapped tokens back into the queue as they can potentially be remapped again.
580 while let Some(token) = stack.pop() {
581 self.db.unwind_if_cancelled();
582 let was_not_remapped = (|| {
583 // are we inside an attribute macro call
584 let containing_attribute_macro_call = self.with_ctx(|ctx| {
588 .filter_map(ast::Item::cast)
590 Some((ctx.item_to_macro_call(token.with_value(item.clone()))?, item))
594 if let Some((call_id, item)) = containing_attribute_macro_call {
595 let file_id = call_id.as_file();
596 return process_expansion_for_token(
604 // or are we inside a function-like macro call
605 if let Some(macro_call) = token.value.ancestors().find_map(ast::MacroCall::cast) {
606 let tt = macro_call.token_tree()?;
607 let l_delim = match tt.left_delimiter_token() {
608 Some(it) => it.text_range().end(),
609 None => tt.syntax().text_range().start(),
611 let r_delim = match tt.right_delimiter_token() {
612 Some(it) => it.text_range().start(),
613 None => tt.syntax().text_range().end(),
615 if !TextRange::new(l_delim, r_delim).contains_range(token.value.text_range()) {
619 let file_id = sa.expand(self.db, token.with_value(¯o_call))?;
620 return process_expansion_for_token(&mut stack, file_id, None, token.as_ref());
623 // outside of a macro invocation so this is a "final" token
628 if was_not_remapped {
634 // Note this return type is deliberate as [`find_nodes_at_offset_with_descend`] wants to stop
635 // traversing the inner iterator when it finds a node.
636 // The outer iterator is over the tokens descendants
637 // The inner iterator is the ancestors of a descendant
638 fn descend_node_at_offset(
642 ) -> impl Iterator<Item = impl Iterator<Item = SyntaxNode> + '_> + '_ {
643 node.token_at_offset(offset)
644 .map(move |token| self.descend_into_macros(token))
646 descendants.into_iter().map(move |it| self.token_ancestors_with_macros(it))
648 // re-order the tokens from token_at_offset by returning the ancestors with the smaller first nodes first
649 // See algo::ancestors_at_offset, which uses the same approach
650 .kmerge_by(|left, right| {
652 .map(|node| node.text_range().len())
653 .lt(right.clone().map(|node| node.text_range().len()))
657 fn original_range(&self, node: &SyntaxNode) -> FileRange {
658 let node = self.find_file(node.clone());
659 node.as_ref().original_file_range(self.db.upcast())
662 fn original_range_opt(&self, node: &SyntaxNode) -> Option<FileRange> {
663 let node = self.find_file(node.clone());
664 node.as_ref().original_file_range_opt(self.db.upcast())
667 fn original_ast_node<N: AstNode>(&self, node: N) -> Option<N> {
668 let file = self.find_file(node.syntax().clone());
669 file.with_value(node).original_ast_node(self.db.upcast()).map(|it| it.value)
672 fn diagnostics_display_range(&self, src: InFile<SyntaxNodePtr>) -> FileRange {
673 let root = self.db.parse_or_expand(src.file_id).unwrap();
674 let node = src.value.to_node(&root);
675 self.cache(root, src.file_id);
676 src.with_value(&node).original_file_range(self.db.upcast())
679 fn token_ancestors_with_macros(
682 ) -> impl Iterator<Item = SyntaxNode> + Clone + '_ {
683 token.parent().into_iter().flat_map(move |parent| self.ancestors_with_macros(parent))
686 fn ancestors_with_macros(
689 ) -> impl Iterator<Item = SyntaxNode> + Clone + '_ {
690 let node = self.find_file(node);
691 node.ancestors_with_macros(self.db.upcast()).map(|it| it.value)
694 fn ancestors_at_offset_with_macros(
698 ) -> impl Iterator<Item = SyntaxNode> + '_ {
699 node.token_at_offset(offset)
700 .map(|token| self.token_ancestors_with_macros(token))
701 .kmerge_by(|node1, node2| node1.text_range().len() < node2.text_range().len())
704 fn resolve_lifetime_param(&self, lifetime: &ast::Lifetime) -> Option<LifetimeParam> {
705 let text = lifetime.text();
706 let lifetime_param = lifetime.syntax().ancestors().find_map(|syn| {
707 let gpl = ast::AnyHasGenericParams::cast(syn)?.generic_param_list()?;
708 gpl.lifetime_params()
709 .find(|tp| tp.lifetime().as_ref().map(|lt| lt.text()).as_ref() == Some(&text))
711 let src = self.find_file(lifetime_param.syntax().clone()).with_value(lifetime_param);
712 ToDef::to_def(self, src)
715 fn resolve_label(&self, lifetime: &ast::Lifetime) -> Option<Label> {
716 let text = lifetime.text();
717 let label = lifetime.syntax().ancestors().find_map(|syn| {
718 let label = match_ast! {
720 ast::ForExpr(it) => it.label(),
721 ast::WhileExpr(it) => it.label(),
722 ast::LoopExpr(it) => it.label(),
723 ast::BlockExpr(it) => it.label(),
729 .and_then(|lt| lt.lifetime_ident_token())
730 .map_or(false, |lt| lt.text() == text)
733 let src = self.find_file(label.syntax().clone()).with_value(label);
734 ToDef::to_def(self, src)
737 fn resolve_type(&self, ty: &ast::Type) -> Option<Type> {
738 let scope = self.scope(ty.syntax());
739 let ctx = body::LowerCtx::new(self.db.upcast(), scope.file_id);
740 let ty = hir_ty::TyLoweringContext::new(self.db, &scope.resolver)
741 .lower_ty(&crate::TypeRef::from_ast(&ctx, ty.clone()));
742 Type::new_with_resolver(self.db, &scope.resolver, ty)
745 fn type_of_expr(&self, expr: &ast::Expr) -> Option<TypeInfo> {
746 self.analyze(expr.syntax())
747 .type_of_expr(self.db, expr)
748 .map(|(ty, coerced)| TypeInfo { original: ty, adjusted: coerced })
751 fn type_of_pat(&self, pat: &ast::Pat) -> Option<TypeInfo> {
752 self.analyze(pat.syntax())
753 .type_of_pat(self.db, pat)
754 .map(|(ty, coerced)| TypeInfo { original: ty, adjusted: coerced })
757 fn type_of_self(&self, param: &ast::SelfParam) -> Option<Type> {
758 self.analyze(param.syntax()).type_of_self(self.db, param)
761 fn resolve_method_call(&self, call: &ast::MethodCallExpr) -> Option<FunctionId> {
762 self.analyze(call.syntax()).resolve_method_call(self.db, call).map(|(id, _)| id)
765 fn resolve_method_call_as_callable(&self, call: &ast::MethodCallExpr) -> Option<Callable> {
766 let (func, subst) = self.analyze(call.syntax()).resolve_method_call(self.db, call)?;
767 let ty = self.db.value_ty(func.into()).substitute(&Interner, &subst);
768 let resolver = self.analyze(call.syntax()).resolver;
769 let ty = Type::new_with_resolver(self.db, &resolver, ty)?;
770 let mut res = ty.as_callable(self.db)?;
771 res.is_bound_method = true;
775 fn resolve_field(&self, field: &ast::FieldExpr) -> Option<Field> {
776 self.analyze(field.syntax()).resolve_field(self.db, field)
779 fn resolve_record_field(
781 field: &ast::RecordExprField,
782 ) -> Option<(Field, Option<Local>, Type)> {
783 self.analyze(field.syntax()).resolve_record_field(self.db, field)
786 fn resolve_record_pat_field(&self, field: &ast::RecordPatField) -> Option<Field> {
787 self.analyze(field.syntax()).resolve_record_pat_field(self.db, field)
790 fn resolve_macro_call(&self, macro_call: &ast::MacroCall) -> Option<MacroDef> {
791 let sa = self.analyze(macro_call.syntax());
792 let macro_call = self.find_file(macro_call.syntax().clone()).with_value(macro_call);
793 sa.resolve_macro_call(self.db, macro_call)
796 fn resolve_attr_macro_call(&self, item: &ast::Item) -> Option<MacroDef> {
797 let item_in_file = self.find_file(item.syntax().clone()).with_value(item.clone());
798 let macro_call_id = self.with_ctx(|ctx| ctx.item_to_macro_call(item_in_file))?;
799 Some(MacroDef { id: self.db.lookup_intern_macro(macro_call_id).def })
802 fn resolve_path(&self, path: &ast::Path) -> Option<PathResolution> {
803 self.analyze(path.syntax()).resolve_path(self.db, path)
806 fn resolve_extern_crate(&self, extern_crate: &ast::ExternCrate) -> Option<Crate> {
807 let krate = self.scope(extern_crate.syntax()).krate()?;
808 krate.dependencies(self.db).into_iter().find_map(|dep| {
809 if dep.name == extern_crate.name_ref()?.as_name() {
817 fn resolve_variant(&self, record_lit: ast::RecordExpr) -> Option<VariantId> {
818 self.analyze(record_lit.syntax()).resolve_variant(self.db, record_lit)
821 fn resolve_bind_pat_to_const(&self, pat: &ast::IdentPat) -> Option<ModuleDef> {
822 self.analyze(pat.syntax()).resolve_bind_pat_to_const(self.db, pat)
825 fn record_literal_missing_fields(&self, literal: &ast::RecordExpr) -> Vec<(Field, Type)> {
826 self.analyze(literal.syntax())
827 .record_literal_missing_fields(self.db, literal)
831 fn record_pattern_missing_fields(&self, pattern: &ast::RecordPat) -> Vec<(Field, Type)> {
832 self.analyze(pattern.syntax())
833 .record_pattern_missing_fields(self.db, pattern)
837 fn with_ctx<F: FnOnce(&mut SourceToDefCtx) -> T, T>(&self, f: F) -> T {
838 let mut cache = self.s2d_cache.borrow_mut();
839 let mut ctx = SourceToDefCtx { db: self.db, cache: &mut *cache };
843 fn to_module_def(&self, file: FileId) -> impl Iterator<Item = Module> {
844 self.with_ctx(|ctx| ctx.file_to_def(file)).into_iter().map(Module::from)
847 fn scope(&self, node: &SyntaxNode) -> SemanticsScope<'db> {
848 let sa = self.analyze(node);
849 SemanticsScope { db: self.db, file_id: sa.file_id, resolver: sa.resolver }
852 fn scope_at_offset(&self, node: &SyntaxNode, offset: TextSize) -> SemanticsScope<'db> {
853 let sa = self.analyze_with_offset(node, offset);
854 SemanticsScope { db: self.db, file_id: sa.file_id, resolver: sa.resolver }
857 fn scope_for_def(&self, def: Trait) -> SemanticsScope<'db> {
858 let file_id = self.db.lookup_intern_trait(def.id).id.file_id();
859 let resolver = def.id.resolver(self.db.upcast());
860 SemanticsScope { db: self.db, file_id, resolver }
863 fn source<Def: HasSource>(&self, def: Def) -> Option<InFile<Def::Ast>>
867 let res = def.source(self.db)?;
868 self.cache(find_root(res.value.syntax()), res.file_id);
872 fn analyze(&self, node: &SyntaxNode) -> SourceAnalyzer {
873 self.analyze_impl(node, None)
875 fn analyze_with_offset(&self, node: &SyntaxNode, offset: TextSize) -> SourceAnalyzer {
876 self.analyze_impl(node, Some(offset))
878 fn analyze_impl(&self, node: &SyntaxNode, offset: Option<TextSize>) -> SourceAnalyzer {
879 let _p = profile::span("Semantics::analyze_impl");
880 let node = self.find_file(node.clone());
881 let node = node.as_ref();
883 let container = match self.with_ctx(|ctx| ctx.find_container(node)) {
885 None => return SourceAnalyzer::new_for_resolver(Resolver::default(), node),
888 let resolver = match container {
889 ChildContainer::DefWithBodyId(def) => {
890 return SourceAnalyzer::new_for_body(self.db, def, node, offset)
892 ChildContainer::TraitId(it) => it.resolver(self.db.upcast()),
893 ChildContainer::ImplId(it) => it.resolver(self.db.upcast()),
894 ChildContainer::ModuleId(it) => it.resolver(self.db.upcast()),
895 ChildContainer::EnumId(it) => it.resolver(self.db.upcast()),
896 ChildContainer::VariantId(it) => it.resolver(self.db.upcast()),
897 ChildContainer::TypeAliasId(it) => it.resolver(self.db.upcast()),
898 ChildContainer::GenericDefId(it) => it.resolver(self.db.upcast()),
900 SourceAnalyzer::new_for_resolver(resolver, node)
903 fn cache(&self, root_node: SyntaxNode, file_id: HirFileId) {
904 assert!(root_node.parent().is_none());
905 let mut cache = self.cache.borrow_mut();
906 let prev = cache.insert(root_node, file_id);
907 assert!(prev == None || prev == Some(file_id))
910 fn assert_contains_node(&self, node: &SyntaxNode) {
911 self.find_file(node.clone());
914 fn lookup(&self, root_node: &SyntaxNode) -> Option<HirFileId> {
915 let cache = self.cache.borrow();
916 cache.get(root_node).copied()
919 fn find_file(&self, node: SyntaxNode) -> InFile<SyntaxNode> {
920 let root_node = find_root(&node);
921 let file_id = self.lookup(&root_node).unwrap_or_else(|| {
923 "\n\nFailed to lookup {:?} in this Semantics.\n\
924 Make sure to use only query nodes, derived from this instance of Semantics.\n\
926 known nodes: {}\n\n",
932 .map(|it| format!("{:?}", it))
937 InFile::new(file_id, node)
940 fn is_unsafe_method_call(&self, method_call_expr: &ast::MethodCallExpr) -> bool {
944 let field_expr = match expr {
945 ast::Expr::FieldExpr(field_expr) => field_expr,
948 let ty = self.type_of_expr(&field_expr.expr()?)?.original;
949 if !ty.is_packed(self.db) {
953 let func = self.resolve_method_call(method_call_expr).map(Function::from)?;
954 let res = match func.self_param(self.db)?.access(self.db) {
955 Access::Shared | Access::Exclusive => true,
956 Access::Owned => false,
963 fn is_unsafe_ref_expr(&self, ref_expr: &ast::RefExpr) -> bool {
967 let field_expr = match expr {
968 ast::Expr::FieldExpr(field_expr) => field_expr,
971 let expr = field_expr.expr()?;
972 self.type_of_expr(&expr)
974 // Binding a reference to a packed type is possibly unsafe.
975 .map(|ty| ty.original.is_packed(self.db))
978 // FIXME This needs layout computation to be correct. It will highlight
979 // more than it should with the current implementation.
982 fn is_unsafe_ident_pat(&self, ident_pat: &ast::IdentPat) -> bool {
983 if ident_pat.ref_token().is_none() {
991 // `IdentPat` can live under `RecordPat` directly under `RecordPatField` or
992 // `RecordPatFieldList`. `RecordPatField` also lives under `RecordPatFieldList`,
993 // so this tries to lookup the `IdentPat` anywhere along that structure to the
994 // `RecordPat` so we can get the containing type.
995 let record_pat = ast::RecordPatField::cast(parent.clone())
996 .and_then(|record_pat| record_pat.syntax().parent())
997 .or_else(|| Some(parent.clone()))
999 ast::RecordPatFieldList::cast(parent)?
1002 .and_then(ast::RecordPat::cast)
1005 // If this doesn't match a `RecordPat`, fallback to a `LetStmt` to see if
1006 // this is initialized from a `FieldExpr`.
1007 if let Some(record_pat) = record_pat {
1008 self.type_of_pat(&ast::Pat::RecordPat(record_pat))
1009 } else if let Some(let_stmt) = ast::LetStmt::cast(parent) {
1010 let field_expr = match let_stmt.initializer()? {
1011 ast::Expr::FieldExpr(field_expr) => field_expr,
1015 self.type_of_expr(&field_expr.expr()?)
1020 // Binding a reference to a packed type is possibly unsafe.
1021 .map(|ty| ty.original.is_packed(self.db))
1026 pub trait ToDef: AstNode + Clone {
1029 fn to_def(sema: &SemanticsImpl, src: InFile<Self>) -> Option<Self::Def>;
1032 macro_rules! to_def_impls {
1033 ($(($def:path, $ast:path, $meth:ident)),* ,) => {$(
1034 impl ToDef for $ast {
1036 fn to_def(sema: &SemanticsImpl, src: InFile<Self>) -> Option<Self::Def> {
1037 sema.with_ctx(|ctx| ctx.$meth(src)).map(<$def>::from)
1044 (crate::Module, ast::Module, module_to_def),
1045 (crate::Module, ast::SourceFile, source_file_to_def),
1046 (crate::Struct, ast::Struct, struct_to_def),
1047 (crate::Enum, ast::Enum, enum_to_def),
1048 (crate::Union, ast::Union, union_to_def),
1049 (crate::Trait, ast::Trait, trait_to_def),
1050 (crate::Impl, ast::Impl, impl_to_def),
1051 (crate::TypeAlias, ast::TypeAlias, type_alias_to_def),
1052 (crate::Const, ast::Const, const_to_def),
1053 (crate::Static, ast::Static, static_to_def),
1054 (crate::Function, ast::Fn, fn_to_def),
1055 (crate::Field, ast::RecordField, record_field_to_def),
1056 (crate::Field, ast::TupleField, tuple_field_to_def),
1057 (crate::Variant, ast::Variant, enum_variant_to_def),
1058 (crate::TypeParam, ast::TypeParam, type_param_to_def),
1059 (crate::LifetimeParam, ast::LifetimeParam, lifetime_param_to_def),
1060 (crate::ConstParam, ast::ConstParam, const_param_to_def),
1061 (crate::MacroDef, ast::Macro, macro_to_def),
1062 (crate::Local, ast::IdentPat, bind_pat_to_def),
1063 (crate::Local, ast::SelfParam, self_param_to_def),
1064 (crate::Label, ast::Label, label_to_def),
1065 (crate::Adt, ast::Adt, adt_to_def),
1068 fn find_root(node: &SyntaxNode) -> SyntaxNode {
1069 node.ancestors().last().unwrap()
1072 /// `SemanticScope` encapsulates the notion of a scope (the set of visible
1073 /// names) at a particular program point.
1075 /// It is a bit tricky, as scopes do not really exist inside the compiler.
1076 /// Rather, the compiler directly computes for each reference the definition it
1077 /// refers to. It might transiently compute the explicit scope map while doing
1078 /// so, but, generally, this is not something left after the analysis.
1080 /// However, we do very much need explicit scopes for IDE purposes --
1081 /// completion, at its core, lists the contents of the current scope. The notion
1082 /// of scope is also useful to answer questions like "what would be the meaning
1083 /// of this piece of code if we inserted it into this position?".
1085 /// So `SemanticsScope` is constructed from a specific program point (a syntax
1086 /// node or just a raw offset) and provides access to the set of visible names
1087 /// on a somewhat best-effort basis.
1089 /// Note that if you are wondering "what does this specific existing name mean?",
1090 /// you'd better use the `resolve_` family of methods.
1092 pub struct SemanticsScope<'a> {
1093 pub db: &'a dyn HirDatabase,
1098 impl<'a> SemanticsScope<'a> {
1099 pub fn module(&self) -> Option<Module> {
1100 Some(Module { id: self.resolver.module()? })
1103 pub fn krate(&self) -> Option<Crate> {
1104 Some(Crate { id: self.resolver.krate()? })
1107 /// Note: `FxHashSet<TraitId>` should be treated as an opaque type, passed into `Type
1108 // FIXME: rename to visible_traits to not repeat scope?
1109 pub fn traits_in_scope(&self) -> FxHashSet<TraitId> {
1110 let resolver = &self.resolver;
1111 resolver.traits_in_scope(self.db.upcast())
1114 pub fn process_all_names(&self, f: &mut dyn FnMut(Name, ScopeDef)) {
1115 let scope = self.resolver.names_in_scope(self.db.upcast());
1116 for (name, entries) in scope {
1117 for entry in entries {
1118 let def = match entry {
1119 resolver::ScopeDef::ModuleDef(it) => ScopeDef::ModuleDef(it.into()),
1120 resolver::ScopeDef::MacroDef(it) => ScopeDef::MacroDef(it.into()),
1121 resolver::ScopeDef::Unknown => ScopeDef::Unknown,
1122 resolver::ScopeDef::ImplSelfType(it) => ScopeDef::ImplSelfType(it.into()),
1123 resolver::ScopeDef::AdtSelfType(it) => ScopeDef::AdtSelfType(it.into()),
1124 resolver::ScopeDef::GenericParam(id) => ScopeDef::GenericParam(id.into()),
1125 resolver::ScopeDef::Local(pat_id) => {
1126 let parent = self.resolver.body_owner().unwrap();
1127 ScopeDef::Local(Local { parent, pat_id })
1129 resolver::ScopeDef::Label(label_id) => {
1130 let parent = self.resolver.body_owner().unwrap();
1131 ScopeDef::Label(Label { parent, label_id })
1134 f(name.clone(), def)
1139 /// Resolve a path as-if it was written at the given scope. This is
1140 /// necessary a heuristic, as it doesn't take hygiene into account.
1141 pub fn speculative_resolve(&self, path: &ast::Path) -> Option<PathResolution> {
1142 let ctx = body::LowerCtx::new(self.db.upcast(), self.file_id);
1143 let path = Path::from_src(path.clone(), &ctx)?;
1144 resolve_hir_path(self.db, &self.resolver, &path)
1147 /// Resolve a path as-if it was written at the given scope. This is
1148 /// necessary a heuristic, as it doesn't take hygiene into account.
1149 // FIXME: This special casing solely exists for attributes for now
1150 // ideally we should have a path resolution infra that properly knows about overlapping namespaces
1151 pub fn speculative_resolve_as_mac(&self, path: &ast::Path) -> Option<MacroDef> {
1152 let ctx = body::LowerCtx::new(self.db.upcast(), self.file_id);
1153 let path = Path::from_src(path.clone(), &ctx)?;
1154 resolve_hir_path_as_macro(self.db, &self.resolver, &path)