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, MacroCallId};
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, HasAttrs, HasGenericParams, HasLoopBody},
21 match_ast, AstNode, AstToken, Direction, SyntaxElement, SyntaxNode, SyntaxNodePtr, SyntaxToken,
27 semantics::source_to_def::{ChildContainer, SourceToDefCache, SourceToDefCtx},
28 source_analyzer::{resolve_hir_path, SourceAnalyzer},
29 Access, AssocItem, BuiltinAttr, Callable, ConstParam, Crate, Field, Function, HasSource,
30 HirFileId, Impl, InFile, Label, LifetimeParam, Local, MacroDef, Module, ModuleDef, Name, Path,
31 ScopeDef, ToolModule, Trait, Type, TypeAlias, TypeParam, VariantDef,
34 #[derive(Debug, Clone, PartialEq, Eq)]
35 pub enum PathResolution {
38 /// A local binding (only value namespace)
43 ConstParam(ConstParam),
47 BuiltinAttr(BuiltinAttr),
48 ToolModule(ToolModule),
52 fn in_type_ns(&self) -> Option<TypeNs> {
54 PathResolution::Def(ModuleDef::Adt(adt)) => Some(TypeNs::AdtId((*adt).into())),
55 PathResolution::Def(ModuleDef::BuiltinType(builtin)) => {
56 Some(TypeNs::BuiltinType((*builtin).into()))
60 | ModuleDef::Variant(_)
61 | ModuleDef::Function(_)
62 | ModuleDef::Module(_)
63 | ModuleDef::Static(_)
64 | ModuleDef::Trait(_),
66 PathResolution::Def(ModuleDef::TypeAlias(alias)) => {
67 Some(TypeNs::TypeAliasId((*alias).into()))
69 PathResolution::BuiltinAttr(_)
70 | PathResolution::ToolModule(_)
71 | PathResolution::Local(_)
72 | PathResolution::Macro(_)
73 | PathResolution::ConstParam(_) => None,
74 PathResolution::TypeParam(param) => Some(TypeNs::GenericParam((*param).into())),
75 PathResolution::SelfType(impl_def) => Some(TypeNs::SelfType((*impl_def).into())),
76 PathResolution::AssocItem(AssocItem::Const(_) | AssocItem::Function(_)) => None,
77 PathResolution::AssocItem(AssocItem::TypeAlias(alias)) => {
78 Some(TypeNs::TypeAliasId((*alias).into()))
83 /// Returns an iterator over associated types that may be specified after this path (using
84 /// `Ty::Assoc` syntax).
85 pub fn assoc_type_shorthand_candidates<R>(
88 mut cb: impl FnMut(&Name, TypeAlias) -> Option<R>,
90 associated_type_shorthand_candidates(db, self.in_type_ns()?, |name, _, id| {
98 /// The original type of the expression or pattern.
100 /// The adjusted type, if an adjustment happened.
101 pub adjusted: Option<Type>,
105 pub fn original(self) -> Type {
109 pub fn has_adjustment(&self) -> bool {
110 self.adjusted.is_some()
113 /// The adjusted type, or the original in case no adjustments occurred.
114 pub fn adjusted(self) -> Type {
115 self.adjusted.unwrap_or(self.original)
119 /// Primary API to get semantic information, like types, from syntax trees.
120 pub struct Semantics<'db, DB> {
122 imp: SemanticsImpl<'db>,
125 pub struct SemanticsImpl<'db> {
126 pub db: &'db dyn HirDatabase,
127 s2d_cache: RefCell<SourceToDefCache>,
128 expansion_info_cache: RefCell<FxHashMap<HirFileId, Option<ExpansionInfo>>>,
129 // Rootnode to HirFileId cache
130 cache: RefCell<FxHashMap<SyntaxNode, HirFileId>>,
131 // MacroCall to its expansion's HirFileId cache
132 macro_call_cache: RefCell<FxHashMap<InFile<ast::MacroCall>, HirFileId>>,
135 impl<DB> fmt::Debug for Semantics<'_, DB> {
136 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
137 write!(f, "Semantics {{ ... }}")
141 impl<'db, DB: HirDatabase> Semantics<'db, DB> {
142 pub fn new(db: &DB) -> Semantics<DB> {
143 let impl_ = SemanticsImpl::new(db);
144 Semantics { db, imp: impl_ }
147 pub fn parse(&self, file_id: FileId) -> ast::SourceFile {
148 self.imp.parse(file_id)
151 pub fn parse_or_expand(&self, file_id: HirFileId) -> Option<SyntaxNode> {
152 self.imp.parse_or_expand(file_id)
155 pub fn expand(&self, macro_call: &ast::MacroCall) -> Option<SyntaxNode> {
156 self.imp.expand(macro_call)
159 /// If `item` has an attribute macro attached to it, expands it.
160 pub fn expand_attr_macro(&self, item: &ast::Item) -> Option<SyntaxNode> {
161 self.imp.expand_attr_macro(item)
164 pub fn resolve_derive_macro(&self, derive: &ast::Attr) -> Option<Vec<Option<MacroDef>>> {
165 self.imp.resolve_derive_macro(derive)
168 pub fn expand_derive_macro(&self, derive: &ast::Attr) -> Option<Vec<SyntaxNode>> {
169 self.imp.expand_derive_macro(derive)
172 pub fn is_attr_macro_call(&self, item: &ast::Item) -> bool {
173 self.imp.is_attr_macro_call(item)
176 pub fn speculative_expand(
178 actual_macro_call: &ast::MacroCall,
179 speculative_args: &ast::TokenTree,
180 token_to_map: SyntaxToken,
181 ) -> Option<(SyntaxNode, SyntaxToken)> {
182 self.imp.speculative_expand(actual_macro_call, speculative_args, token_to_map)
185 pub fn speculative_expand_attr_macro(
187 actual_macro_call: &ast::Item,
188 speculative_args: &ast::Item,
189 token_to_map: SyntaxToken,
190 ) -> Option<(SyntaxNode, SyntaxToken)> {
191 self.imp.speculative_expand_attr(actual_macro_call, speculative_args, token_to_map)
194 /// Descend the token into macrocalls to its first mapped counterpart.
195 pub fn descend_into_macros_single(&self, token: SyntaxToken) -> SyntaxToken {
196 self.imp.descend_into_macros_single(token)
199 /// Descend the token into macrocalls to all its mapped counterparts.
200 pub fn descend_into_macros(&self, token: SyntaxToken) -> SmallVec<[SyntaxToken; 1]> {
201 self.imp.descend_into_macros(token)
204 /// Maps a node down by mapping its first and last token down.
205 pub fn descend_node_into_attributes<N: AstNode>(&self, node: N) -> SmallVec<[N; 1]> {
206 self.imp.descend_node_into_attributes(node)
209 /// Search for a definition's source and cache its syntax tree
210 pub fn source<Def: HasSource>(&self, def: Def) -> Option<InFile<Def::Ast>>
217 pub fn hir_file_for(&self, syntax_node: &SyntaxNode) -> HirFileId {
218 self.imp.find_file(syntax_node).file_id
221 pub fn original_range(&self, node: &SyntaxNode) -> FileRange {
222 self.imp.original_range(node)
225 pub fn original_range_opt(&self, node: &SyntaxNode) -> Option<FileRange> {
226 self.imp.original_range_opt(node)
229 pub fn original_ast_node<N: AstNode>(&self, node: N) -> Option<N> {
230 self.imp.original_ast_node(node)
233 pub fn diagnostics_display_range(&self, diagnostics: InFile<SyntaxNodePtr>) -> FileRange {
234 self.imp.diagnostics_display_range(diagnostics)
237 pub fn token_ancestors_with_macros(
240 ) -> impl Iterator<Item = SyntaxNode> + '_ {
241 token.parent().into_iter().flat_map(move |it| self.ancestors_with_macros(it))
244 /// Iterates the ancestors of the given node, climbing up macro expansions while doing so.
245 pub fn ancestors_with_macros(&self, node: SyntaxNode) -> impl Iterator<Item = SyntaxNode> + '_ {
246 self.imp.ancestors_with_macros(node)
249 pub fn ancestors_at_offset_with_macros(
253 ) -> impl Iterator<Item = SyntaxNode> + '_ {
254 self.imp.ancestors_at_offset_with_macros(node, offset)
257 /// Find an AstNode by offset inside SyntaxNode, if it is inside *Macrofile*,
258 /// search up until it is of the target AstNode type
259 pub fn find_node_at_offset_with_macros<N: AstNode>(
264 self.imp.ancestors_at_offset_with_macros(node, offset).find_map(N::cast)
267 /// Find an AstNode by offset inside SyntaxNode, if it is inside *MacroCall*,
268 /// descend it and find again
269 pub fn find_node_at_offset_with_descend<N: AstNode>(
274 self.imp.descend_node_at_offset(node, offset).flatten().find_map(N::cast)
277 /// Find an AstNode by offset inside SyntaxNode, if it is inside *MacroCall*,
278 /// descend it and find again
279 pub fn find_nodes_at_offset_with_descend<'slf, N: AstNode + 'slf>(
283 ) -> impl Iterator<Item = N> + 'slf {
284 self.imp.descend_node_at_offset(node, offset).filter_map(|mut it| it.find_map(N::cast))
287 pub fn resolve_lifetime_param(&self, lifetime: &ast::Lifetime) -> Option<LifetimeParam> {
288 self.imp.resolve_lifetime_param(lifetime)
291 pub fn resolve_label(&self, lifetime: &ast::Lifetime) -> Option<Label> {
292 self.imp.resolve_label(lifetime)
295 pub fn resolve_type(&self, ty: &ast::Type) -> Option<Type> {
296 self.imp.resolve_type(ty)
299 pub fn type_of_expr(&self, expr: &ast::Expr) -> Option<TypeInfo> {
300 self.imp.type_of_expr(expr)
303 pub fn type_of_pat(&self, pat: &ast::Pat) -> Option<TypeInfo> {
304 self.imp.type_of_pat(pat)
307 pub fn type_of_self(&self, param: &ast::SelfParam) -> Option<Type> {
308 self.imp.type_of_self(param)
311 pub fn resolve_method_call(&self, call: &ast::MethodCallExpr) -> Option<Function> {
312 self.imp.resolve_method_call(call).map(Function::from)
315 pub fn resolve_method_call_as_callable(&self, call: &ast::MethodCallExpr) -> Option<Callable> {
316 self.imp.resolve_method_call_as_callable(call)
319 pub fn resolve_field(&self, field: &ast::FieldExpr) -> Option<Field> {
320 self.imp.resolve_field(field)
323 pub fn resolve_record_field(
325 field: &ast::RecordExprField,
326 ) -> Option<(Field, Option<Local>, Type)> {
327 self.imp.resolve_record_field(field)
330 pub fn resolve_record_pat_field(&self, field: &ast::RecordPatField) -> Option<Field> {
331 self.imp.resolve_record_pat_field(field)
334 pub fn resolve_macro_call(&self, macro_call: &ast::MacroCall) -> Option<MacroDef> {
335 self.imp.resolve_macro_call(macro_call)
338 pub fn resolve_attr_macro_call(&self, item: &ast::Item) -> Option<MacroDef> {
339 self.imp.resolve_attr_macro_call(item)
342 pub fn resolve_path(&self, path: &ast::Path) -> Option<PathResolution> {
343 self.imp.resolve_path(path)
346 pub fn resolve_extern_crate(&self, extern_crate: &ast::ExternCrate) -> Option<Crate> {
347 self.imp.resolve_extern_crate(extern_crate)
350 pub fn resolve_variant(&self, record_lit: ast::RecordExpr) -> Option<VariantDef> {
351 self.imp.resolve_variant(record_lit).map(VariantDef::from)
354 pub fn resolve_bind_pat_to_const(&self, pat: &ast::IdentPat) -> Option<ModuleDef> {
355 self.imp.resolve_bind_pat_to_const(pat)
358 pub fn resolve_derive_ident(&self, ident: &ast::Ident) -> Option<PathResolution> {
359 self.imp.resolve_derive_ident(ident)
362 // FIXME: use this instead?
363 // pub fn resolve_name_ref(&self, name_ref: &ast::NameRef) -> Option<???>;
365 pub fn record_literal_missing_fields(&self, literal: &ast::RecordExpr) -> Vec<(Field, Type)> {
366 self.imp.record_literal_missing_fields(literal)
369 pub fn record_pattern_missing_fields(&self, pattern: &ast::RecordPat) -> Vec<(Field, Type)> {
370 self.imp.record_pattern_missing_fields(pattern)
373 pub fn to_def<T: ToDef>(&self, src: &T) -> Option<T::Def> {
374 let src = self.imp.find_file(src.syntax()).with_value(src).cloned();
375 T::to_def(&self.imp, src)
378 pub fn to_module_def(&self, file: FileId) -> Option<Module> {
379 self.imp.to_module_def(file).next()
382 pub fn to_module_defs(&self, file: FileId) -> impl Iterator<Item = Module> {
383 self.imp.to_module_def(file)
386 pub fn scope(&self, node: &SyntaxNode) -> SemanticsScope<'db> {
390 pub fn scope_at_offset(&self, token: &SyntaxToken, offset: TextSize) -> SemanticsScope<'db> {
391 self.imp.scope_at_offset(&token.parent().unwrap(), offset)
394 pub fn scope_for_def(&self, def: Trait) -> SemanticsScope<'db> {
395 self.imp.scope_for_def(def)
398 pub fn assert_contains_node(&self, node: &SyntaxNode) {
399 self.imp.assert_contains_node(node)
402 pub fn is_unsafe_method_call(&self, method_call_expr: &ast::MethodCallExpr) -> bool {
403 self.imp.is_unsafe_method_call(method_call_expr)
406 pub fn is_unsafe_ref_expr(&self, ref_expr: &ast::RefExpr) -> bool {
407 self.imp.is_unsafe_ref_expr(ref_expr)
410 pub fn is_unsafe_ident_pat(&self, ident_pat: &ast::IdentPat) -> bool {
411 self.imp.is_unsafe_ident_pat(ident_pat)
415 impl<'db> SemanticsImpl<'db> {
416 fn new(db: &'db dyn HirDatabase) -> Self {
419 s2d_cache: Default::default(),
420 cache: Default::default(),
421 expansion_info_cache: Default::default(),
422 macro_call_cache: Default::default(),
426 fn parse(&self, file_id: FileId) -> ast::SourceFile {
427 let tree = self.db.parse(file_id).tree();
428 self.cache(tree.syntax().clone(), file_id.into());
432 fn parse_or_expand(&self, file_id: HirFileId) -> Option<SyntaxNode> {
433 let node = self.db.parse_or_expand(file_id)?;
434 self.cache(node.clone(), file_id);
438 fn expand(&self, macro_call: &ast::MacroCall) -> Option<SyntaxNode> {
439 let sa = self.analyze_no_infer(macro_call.syntax());
440 let file_id = sa.expand(self.db, InFile::new(sa.file_id, macro_call))?;
441 let node = self.db.parse_or_expand(file_id)?;
442 self.cache(node.clone(), file_id);
446 fn expand_attr_macro(&self, item: &ast::Item) -> Option<SyntaxNode> {
447 let src = self.find_file(item.syntax()).with_value(item.clone());
448 let macro_call_id = self.with_ctx(|ctx| ctx.item_to_macro_call(src))?;
449 let file_id = macro_call_id.as_file();
450 let node = self.db.parse_or_expand(file_id)?;
451 self.cache(node.clone(), file_id);
455 fn resolve_derive_macro(&self, attr: &ast::Attr) -> Option<Vec<Option<MacroDef>>> {
457 .derive_macro_calls(attr)?
459 .map(|call| Some(MacroDef { id: self.db.lookup_intern_macro_call(call?).def }))
464 fn expand_derive_macro(&self, attr: &ast::Attr) -> Option<Vec<SyntaxNode>> {
465 let res: Vec<_> = self
466 .derive_macro_calls(attr)?
469 let file_id = call?.as_file();
470 let node = self.db.parse_or_expand(file_id)?;
471 self.cache(node.clone(), file_id);
478 fn derive_macro_calls(&self, attr: &ast::Attr) -> Option<Vec<Option<MacroCallId>>> {
479 let item = attr.syntax().parent().and_then(ast::Item::cast)?;
480 let file_id = self.find_file(item.syntax()).file_id;
481 let item = InFile::new(file_id, &item);
482 let src = InFile::new(file_id, attr.clone());
483 self.with_ctx(|ctx| {
484 let res = ctx.attr_to_derive_macro_call(item, src)?;
489 fn is_attr_macro_call(&self, item: &ast::Item) -> bool {
490 let file_id = self.find_file(item.syntax()).file_id;
491 let src = InFile::new(file_id, item.clone());
492 self.with_ctx(|ctx| ctx.item_to_macro_call(src).is_some())
495 fn speculative_expand(
497 actual_macro_call: &ast::MacroCall,
498 speculative_args: &ast::TokenTree,
499 token_to_map: SyntaxToken,
500 ) -> Option<(SyntaxNode, SyntaxToken)> {
501 let SourceAnalyzer { file_id, resolver, .. } =
502 self.analyze_no_infer(actual_macro_call.syntax());
503 let macro_call = InFile::new(file_id, actual_macro_call);
504 let krate = resolver.krate()?;
505 let macro_call_id = macro_call.as_call_id(self.db.upcast(), krate, |path| {
506 resolver.resolve_path_as_macro(self.db.upcast(), &path)
508 hir_expand::db::expand_speculative(
511 speculative_args.syntax(),
516 fn speculative_expand_attr(
518 actual_macro_call: &ast::Item,
519 speculative_args: &ast::Item,
520 token_to_map: SyntaxToken,
521 ) -> Option<(SyntaxNode, SyntaxToken)> {
522 let file_id = self.find_file(actual_macro_call.syntax()).file_id;
523 let macro_call = InFile::new(file_id, actual_macro_call.clone());
524 let macro_call_id = self.with_ctx(|ctx| ctx.item_to_macro_call(macro_call))?;
525 hir_expand::db::expand_speculative(
528 speculative_args.syntax(),
533 // This might not be the correct way to do this, but it works for now
534 fn descend_node_into_attributes<N: AstNode>(&self, node: N) -> SmallVec<[N; 1]> {
535 let mut res = smallvec![];
537 let first = skip_trivia_token(node.syntax().first_token()?, Direction::Next)?;
538 let last = skip_trivia_token(node.syntax().last_token()?, Direction::Prev)?;
541 let (first, last) = match tokens {
547 self.descend_into_macros_impl(
549 &mut |InFile { value, .. }| {
550 if let Some(node) = value.ancestors().find_map(N::cast) {
557 // Descend first and last token, then zip them to look for the node they belong to
558 let mut scratch: SmallVec<[_; 1]> = smallvec![];
559 self.descend_into_macros_impl(
567 let mut scratch = scratch.into_iter();
568 self.descend_into_macros_impl(
570 &mut |InFile { value: last, file_id: last_fid }| {
571 if let Some(InFile { value: first, file_id: first_fid }) = scratch.next() {
572 if first_fid == last_fid {
573 if let Some(p) = first.parent() {
574 let range = first.text_range().cover(last.text_range());
575 let node = find_root(&p)
576 .covering_element(range)
578 .take_while(|it| it.text_range() == range)
580 if let Some(node) = node {
593 fn descend_into_macros(&self, token: SyntaxToken) -> SmallVec<[SyntaxToken; 1]> {
594 let mut res = smallvec![];
595 self.descend_into_macros_impl(token, &mut |InFile { value, .. }| res.push(value), false);
599 fn descend_into_macros_single(&self, token: SyntaxToken) -> SyntaxToken {
600 let mut res = token.clone();
601 self.descend_into_macros_impl(token, &mut |InFile { value, .. }| res = value, true);
605 fn descend_into_macros_impl(
608 f: &mut dyn FnMut(InFile<SyntaxToken>),
611 let _p = profile::span("descend_into_macros");
612 let parent = match token.parent() {
616 let sa = self.analyze_no_infer(&parent);
617 let mut stack: SmallVec<[_; 4]> = smallvec![InFile::new(sa.file_id, token)];
618 let mut cache = self.expansion_info_cache.borrow_mut();
619 let mut mcache = self.macro_call_cache.borrow_mut();
621 let mut process_expansion_for_token =
622 |stack: &mut SmallVec<_>, macro_file, item, token: InFile<&_>| {
623 let expansion_info = cache
625 .or_insert_with(|| macro_file.expansion_info(self.db.upcast()))
629 let InFile { file_id, value } = expansion_info.expanded();
630 self.cache(value, file_id);
633 let mut mapped_tokens =
634 expansion_info.map_token_down(self.db.upcast(), item, token)?;
636 let len = stack.len();
637 // requeue the tokens we got from mapping our current token down
639 stack.extend(mapped_tokens.next());
641 stack.extend(mapped_tokens);
643 // if the length changed we have found a mapping for the token
644 (stack.len() != len).then(|| ())
647 // Remap the next token in the queue into a macro call its in, if it is not being remapped
648 // either due to not being in a macro-call or because its unused push it into the result vec,
649 // otherwise push the remapped tokens back into the queue as they can potentially be remapped again.
650 while let Some(token) = stack.pop() {
651 self.db.unwind_if_cancelled();
652 let was_not_remapped = (|| {
653 // are we inside an attribute macro call
654 let containing_attribute_macro_call = self.with_ctx(|ctx| {
655 token.value.ancestors().filter_map(ast::Item::cast).find_map(|item| {
656 if item.attrs().next().is_none() {
657 // Don't force populate the dyn cache for items that don't have an attribute anyways
660 Some((ctx.item_to_macro_call(token.with_value(item.clone()))?, item))
663 if let Some((call_id, item)) = containing_attribute_macro_call {
664 let file_id = call_id.as_file();
665 return process_expansion_for_token(
673 // or are we inside a function-like macro call
675 // FIXME replace map.while_some with take_while once stable
676 token.value.ancestors().map(ast::TokenTree::cast).while_some().last()
678 let macro_call = tt.syntax().parent().and_then(ast::MacroCall::cast)?;
679 if tt.left_delimiter_token().map_or(false, |it| it == token.value) {
682 if tt.right_delimiter_token().map_or(false, |it| it == token.value) {
686 let mcall = token.with_value(macro_call);
687 let file_id = match mcache.get(&mcall) {
690 let it = sa.expand(self.db, mcall.as_ref())?;
691 mcache.insert(mcall, it);
695 return process_expansion_for_token(&mut stack, file_id, None, token.as_ref());
698 // outside of a macro invocation so this is a "final" token
703 if was_not_remapped {
709 // Note this return type is deliberate as [`find_nodes_at_offset_with_descend`] wants to stop
710 // traversing the inner iterator when it finds a node.
711 // The outer iterator is over the tokens descendants
712 // The inner iterator is the ancestors of a descendant
713 fn descend_node_at_offset(
717 ) -> impl Iterator<Item = impl Iterator<Item = SyntaxNode> + '_> + '_ {
718 node.token_at_offset(offset)
719 .map(move |token| self.descend_into_macros(token))
721 descendants.into_iter().map(move |it| self.token_ancestors_with_macros(it))
723 // re-order the tokens from token_at_offset by returning the ancestors with the smaller first nodes first
724 // See algo::ancestors_at_offset, which uses the same approach
725 .kmerge_by(|left, right| {
727 .map(|node| node.text_range().len())
728 .lt(right.clone().map(|node| node.text_range().len()))
732 fn original_range(&self, node: &SyntaxNode) -> FileRange {
733 let node = self.find_file(node);
734 node.original_file_range(self.db.upcast())
737 fn original_range_opt(&self, node: &SyntaxNode) -> Option<FileRange> {
738 let node = self.find_file(node);
739 node.original_file_range_opt(self.db.upcast())
742 fn original_ast_node<N: AstNode>(&self, node: N) -> Option<N> {
743 let InFile { file_id, .. } = self.find_file(node.syntax());
744 InFile::new(file_id, node).original_ast_node(self.db.upcast()).map(|it| it.value)
747 fn diagnostics_display_range(&self, src: InFile<SyntaxNodePtr>) -> FileRange {
748 let root = self.db.parse_or_expand(src.file_id).unwrap();
749 let node = src.value.to_node(&root);
750 self.cache(root, src.file_id);
751 src.with_value(&node).original_file_range(self.db.upcast())
754 fn token_ancestors_with_macros(
757 ) -> impl Iterator<Item = SyntaxNode> + Clone + '_ {
758 token.parent().into_iter().flat_map(move |parent| self.ancestors_with_macros(parent))
761 fn ancestors_with_macros(
764 ) -> impl Iterator<Item = SyntaxNode> + Clone + '_ {
765 let node = self.find_file(&node);
766 node.ancestors_with_macros(self.db.upcast()).map(|it| it.value)
769 fn ancestors_at_offset_with_macros(
773 ) -> impl Iterator<Item = SyntaxNode> + '_ {
774 node.token_at_offset(offset)
775 .map(|token| self.token_ancestors_with_macros(token))
776 .kmerge_by(|node1, node2| node1.text_range().len() < node2.text_range().len())
779 fn resolve_lifetime_param(&self, lifetime: &ast::Lifetime) -> Option<LifetimeParam> {
780 let text = lifetime.text();
781 let lifetime_param = lifetime.syntax().ancestors().find_map(|syn| {
782 let gpl = ast::AnyHasGenericParams::cast(syn)?.generic_param_list()?;
783 gpl.lifetime_params()
784 .find(|tp| tp.lifetime().as_ref().map(|lt| lt.text()).as_ref() == Some(&text))
786 let file_id = self.find_file(lifetime_param.syntax()).file_id;
787 let src = InFile::new(file_id, lifetime_param);
788 ToDef::to_def(self, src)
791 fn resolve_label(&self, lifetime: &ast::Lifetime) -> Option<Label> {
792 let text = lifetime.text();
793 let label = lifetime.syntax().ancestors().find_map(|syn| {
794 let label = match_ast! {
796 ast::ForExpr(it) => it.label(),
797 ast::WhileExpr(it) => it.label(),
798 ast::LoopExpr(it) => it.label(),
799 ast::BlockExpr(it) => it.label(),
805 .and_then(|lt| lt.lifetime_ident_token())
806 .map_or(false, |lt| lt.text() == text)
809 let file_id = self.find_file(label.syntax()).file_id;
810 let src = InFile::new(file_id, label);
811 ToDef::to_def(self, src)
814 fn resolve_type(&self, ty: &ast::Type) -> Option<Type> {
815 let scope = self.scope(ty.syntax());
816 let ctx = body::LowerCtx::new(self.db.upcast(), scope.file_id);
817 let ty = hir_ty::TyLoweringContext::new(self.db, &scope.resolver)
818 .lower_ty(&crate::TypeRef::from_ast(&ctx, ty.clone()));
819 Type::new_with_resolver(self.db, &scope.resolver, ty)
822 fn type_of_expr(&self, expr: &ast::Expr) -> Option<TypeInfo> {
823 self.analyze(expr.syntax())
824 .type_of_expr(self.db, expr)
825 .map(|(ty, coerced)| TypeInfo { original: ty, adjusted: coerced })
828 fn type_of_pat(&self, pat: &ast::Pat) -> Option<TypeInfo> {
829 self.analyze(pat.syntax())
830 .type_of_pat(self.db, pat)
831 .map(|(ty, coerced)| TypeInfo { original: ty, adjusted: coerced })
834 fn type_of_self(&self, param: &ast::SelfParam) -> Option<Type> {
835 self.analyze(param.syntax()).type_of_self(self.db, param)
838 fn resolve_method_call(&self, call: &ast::MethodCallExpr) -> Option<FunctionId> {
839 self.analyze(call.syntax()).resolve_method_call(self.db, call).map(|(id, _)| id)
842 fn resolve_method_call_as_callable(&self, call: &ast::MethodCallExpr) -> Option<Callable> {
843 let (func, subst) = self.analyze(call.syntax()).resolve_method_call(self.db, call)?;
844 let ty = self.db.value_ty(func.into()).substitute(Interner, &subst);
845 let resolver = self.analyze(call.syntax()).resolver;
846 let ty = Type::new_with_resolver(self.db, &resolver, ty)?;
847 let mut res = ty.as_callable(self.db)?;
848 res.is_bound_method = true;
852 fn resolve_field(&self, field: &ast::FieldExpr) -> Option<Field> {
853 self.analyze(field.syntax()).resolve_field(self.db, field)
856 fn resolve_record_field(
858 field: &ast::RecordExprField,
859 ) -> Option<(Field, Option<Local>, Type)> {
860 self.analyze(field.syntax()).resolve_record_field(self.db, field)
863 fn resolve_record_pat_field(&self, field: &ast::RecordPatField) -> Option<Field> {
864 self.analyze(field.syntax()).resolve_record_pat_field(self.db, field)
867 fn resolve_macro_call(&self, macro_call: &ast::MacroCall) -> Option<MacroDef> {
868 let sa = self.analyze(macro_call.syntax());
869 let macro_call = self.find_file(macro_call.syntax()).with_value(macro_call);
870 sa.resolve_macro_call(self.db, macro_call)
873 fn resolve_attr_macro_call(&self, item: &ast::Item) -> Option<MacroDef> {
874 let item_in_file = self.find_file(item.syntax()).with_value(item.clone());
875 let macro_call_id = self.with_ctx(|ctx| ctx.item_to_macro_call(item_in_file))?;
876 Some(MacroDef { id: self.db.lookup_intern_macro_call(macro_call_id).def })
879 fn resolve_path(&self, path: &ast::Path) -> Option<PathResolution> {
880 self.analyze(path.syntax()).resolve_path(self.db, path)
883 fn resolve_extern_crate(&self, extern_crate: &ast::ExternCrate) -> Option<Crate> {
884 let krate = self.scope(extern_crate.syntax()).krate()?;
885 krate.dependencies(self.db).into_iter().find_map(|dep| {
886 if dep.name == extern_crate.name_ref()?.as_name() {
894 fn resolve_variant(&self, record_lit: ast::RecordExpr) -> Option<VariantId> {
895 self.analyze(record_lit.syntax()).resolve_variant(self.db, record_lit)
898 fn resolve_bind_pat_to_const(&self, pat: &ast::IdentPat) -> Option<ModuleDef> {
899 self.analyze(pat.syntax()).resolve_bind_pat_to_const(self.db, pat)
902 fn resolve_derive_ident(&self, ident: &ast::Ident) -> Option<PathResolution> {
903 // derive macros are always at depth 2, tokentree -> meta -> attribute
904 let syntax = ident.syntax();
905 let attr = syntax.ancestors().nth(2).and_then(ast::Attr::cast)?;
907 let tt = attr.token_tree()?;
908 if !tt.syntax().text_range().contains_range(ident.syntax().text_range()) {
912 // Fetch hir::Attr definition
913 // FIXME: Move this to ToDef impl?
914 let adt = attr.syntax().parent().and_then(ast::Adt::cast)?;
915 let attr_pos = adt.attrs().position(|it| it == attr)?;
917 let file_id = self.find_file(adt.syntax()).file_id;
918 let adt = InFile::new(file_id, adt);
919 let def = self.with_ctx(|ctx| ctx.adt_to_def(adt))?;
920 self.db.attrs(def.into())
922 let attr_def = attrs.get(attr_pos)?;
924 let mut derive_paths = attr_def.parse_path_comma_token_tree()?;
925 let derives = self.resolve_derive_macro(&attr)?;
929 .children_with_tokens()
930 .filter_map(SyntaxElement::into_token)
931 .take_while(|tok| tok != syntax)
932 .filter(|t| t.kind() == T![,])
934 let path_segment_idx = syntax
935 .siblings_with_tokens(Direction::Prev)
936 .filter_map(SyntaxElement::into_token)
937 .take_while(|tok| matches!(tok.kind(), T![:] | T![ident]))
938 .filter(|tok| tok.kind() == T![ident])
941 let mut mod_path = derive_paths.nth(derive_idx)?;
943 if path_segment_idx < mod_path.len() {
944 // the path for the given ident is a qualifier, resolve to module if possible
945 while path_segment_idx < mod_path.len() {
946 mod_path.pop_segment();
950 &self.scope(attr.syntax()).resolver,
951 &Path::from_known_path(mod_path, []),
953 .filter(|res| matches!(res, PathResolution::Def(ModuleDef::Module(_))))
955 // otherwise fetch the derive
956 derives.get(derive_idx)?.map(PathResolution::Macro)
960 fn record_literal_missing_fields(&self, literal: &ast::RecordExpr) -> Vec<(Field, Type)> {
961 self.analyze(literal.syntax())
962 .record_literal_missing_fields(self.db, literal)
966 fn record_pattern_missing_fields(&self, pattern: &ast::RecordPat) -> Vec<(Field, Type)> {
967 self.analyze(pattern.syntax())
968 .record_pattern_missing_fields(self.db, pattern)
972 fn with_ctx<F: FnOnce(&mut SourceToDefCtx) -> T, T>(&self, f: F) -> T {
973 let mut cache = self.s2d_cache.borrow_mut();
974 let mut ctx = SourceToDefCtx { db: self.db, cache: &mut *cache };
978 fn to_module_def(&self, file: FileId) -> impl Iterator<Item = Module> {
979 self.with_ctx(|ctx| ctx.file_to_def(file)).into_iter().map(Module::from)
982 fn scope(&self, node: &SyntaxNode) -> SemanticsScope<'db> {
983 let SourceAnalyzer { file_id, resolver, .. } = self.analyze_no_infer(node);
984 SemanticsScope { db: self.db, file_id, resolver }
987 fn scope_at_offset(&self, node: &SyntaxNode, offset: TextSize) -> SemanticsScope<'db> {
988 let SourceAnalyzer { file_id, resolver, .. } =
989 self.analyze_with_offset_no_infer(node, offset);
990 SemanticsScope { db: self.db, file_id, resolver }
993 fn scope_for_def(&self, def: Trait) -> SemanticsScope<'db> {
994 let file_id = self.db.lookup_intern_trait(def.id).id.file_id();
995 let resolver = def.id.resolver(self.db.upcast());
996 SemanticsScope { db: self.db, file_id, resolver }
999 fn source<Def: HasSource>(&self, def: Def) -> Option<InFile<Def::Ast>>
1003 let res = def.source(self.db)?;
1004 self.cache(find_root(res.value.syntax()), res.file_id);
1008 fn analyze(&self, node: &SyntaxNode) -> SourceAnalyzer {
1009 self.analyze_impl(node, None, true)
1012 fn analyze_no_infer(&self, node: &SyntaxNode) -> SourceAnalyzer {
1013 self.analyze_impl(node, None, false)
1016 fn analyze_with_offset_no_infer(&self, node: &SyntaxNode, offset: TextSize) -> SourceAnalyzer {
1017 self.analyze_impl(node, Some(offset), false)
1023 offset: Option<TextSize>,
1025 ) -> SourceAnalyzer {
1026 let _p = profile::span("Semantics::analyze_impl");
1027 let node = self.find_file(node);
1029 let container = match self.with_ctx(|ctx| ctx.find_container(node)) {
1031 None => return SourceAnalyzer::new_for_resolver(Resolver::default(), node),
1034 let resolver = match container {
1035 ChildContainer::DefWithBodyId(def) => {
1036 return if infer_body {
1037 SourceAnalyzer::new_for_body(self.db, def, node, offset)
1039 SourceAnalyzer::new_for_body_no_infer(self.db, def, node, offset)
1042 ChildContainer::TraitId(it) => it.resolver(self.db.upcast()),
1043 ChildContainer::ImplId(it) => it.resolver(self.db.upcast()),
1044 ChildContainer::ModuleId(it) => it.resolver(self.db.upcast()),
1045 ChildContainer::EnumId(it) => it.resolver(self.db.upcast()),
1046 ChildContainer::VariantId(it) => it.resolver(self.db.upcast()),
1047 ChildContainer::TypeAliasId(it) => it.resolver(self.db.upcast()),
1048 ChildContainer::GenericDefId(it) => it.resolver(self.db.upcast()),
1050 SourceAnalyzer::new_for_resolver(resolver, node)
1053 fn cache(&self, root_node: SyntaxNode, file_id: HirFileId) {
1054 assert!(root_node.parent().is_none());
1055 let mut cache = self.cache.borrow_mut();
1056 let prev = cache.insert(root_node, file_id);
1057 assert!(prev == None || prev == Some(file_id))
1060 fn assert_contains_node(&self, node: &SyntaxNode) {
1061 self.find_file(node);
1064 fn lookup(&self, root_node: &SyntaxNode) -> Option<HirFileId> {
1065 let cache = self.cache.borrow();
1066 cache.get(root_node).copied()
1069 fn find_file<'node>(&self, node: &'node SyntaxNode) -> InFile<&'node SyntaxNode> {
1070 let root_node = find_root(node);
1071 let file_id = self.lookup(&root_node).unwrap_or_else(|| {
1073 "\n\nFailed to lookup {:?} in this Semantics.\n\
1074 Make sure to use only query nodes, derived from this instance of Semantics.\n\
1076 known nodes: {}\n\n",
1082 .map(|it| format!("{:?}", it))
1083 .collect::<Vec<_>>()
1087 InFile::new(file_id, node)
1090 fn is_unsafe_method_call(&self, method_call_expr: &ast::MethodCallExpr) -> bool {
1094 let field_expr = match expr {
1095 ast::Expr::FieldExpr(field_expr) => field_expr,
1098 let ty = self.type_of_expr(&field_expr.expr()?)?.original;
1099 if !ty.is_packed(self.db) {
1103 let func = self.resolve_method_call(method_call_expr).map(Function::from)?;
1104 let res = match func.self_param(self.db)?.access(self.db) {
1105 Access::Shared | Access::Exclusive => true,
1106 Access::Owned => false,
1113 fn is_unsafe_ref_expr(&self, ref_expr: &ast::RefExpr) -> bool {
1117 let field_expr = match expr {
1118 ast::Expr::FieldExpr(field_expr) => field_expr,
1121 let expr = field_expr.expr()?;
1122 self.type_of_expr(&expr)
1124 // Binding a reference to a packed type is possibly unsafe.
1125 .map(|ty| ty.original.is_packed(self.db))
1128 // FIXME This needs layout computation to be correct. It will highlight
1129 // more than it should with the current implementation.
1132 fn is_unsafe_ident_pat(&self, ident_pat: &ast::IdentPat) -> bool {
1133 if ident_pat.ref_token().is_none() {
1140 .and_then(|parent| {
1141 // `IdentPat` can live under `RecordPat` directly under `RecordPatField` or
1142 // `RecordPatFieldList`. `RecordPatField` also lives under `RecordPatFieldList`,
1143 // so this tries to lookup the `IdentPat` anywhere along that structure to the
1144 // `RecordPat` so we can get the containing type.
1145 let record_pat = ast::RecordPatField::cast(parent.clone())
1146 .and_then(|record_pat| record_pat.syntax().parent())
1147 .or_else(|| Some(parent.clone()))
1148 .and_then(|parent| {
1149 ast::RecordPatFieldList::cast(parent)?
1152 .and_then(ast::RecordPat::cast)
1155 // If this doesn't match a `RecordPat`, fallback to a `LetStmt` to see if
1156 // this is initialized from a `FieldExpr`.
1157 if let Some(record_pat) = record_pat {
1158 self.type_of_pat(&ast::Pat::RecordPat(record_pat))
1159 } else if let Some(let_stmt) = ast::LetStmt::cast(parent) {
1160 let field_expr = match let_stmt.initializer()? {
1161 ast::Expr::FieldExpr(field_expr) => field_expr,
1165 self.type_of_expr(&field_expr.expr()?)
1170 // Binding a reference to a packed type is possibly unsafe.
1171 .map(|ty| ty.original.is_packed(self.db))
1176 pub trait ToDef: AstNode + Clone {
1179 fn to_def(sema: &SemanticsImpl, src: InFile<Self>) -> Option<Self::Def>;
1182 macro_rules! to_def_impls {
1183 ($(($def:path, $ast:path, $meth:ident)),* ,) => {$(
1184 impl ToDef for $ast {
1186 fn to_def(sema: &SemanticsImpl, src: InFile<Self>) -> Option<Self::Def> {
1187 sema.with_ctx(|ctx| ctx.$meth(src)).map(<$def>::from)
1194 (crate::Module, ast::Module, module_to_def),
1195 (crate::Module, ast::SourceFile, source_file_to_def),
1196 (crate::Struct, ast::Struct, struct_to_def),
1197 (crate::Enum, ast::Enum, enum_to_def),
1198 (crate::Union, ast::Union, union_to_def),
1199 (crate::Trait, ast::Trait, trait_to_def),
1200 (crate::Impl, ast::Impl, impl_to_def),
1201 (crate::TypeAlias, ast::TypeAlias, type_alias_to_def),
1202 (crate::Const, ast::Const, const_to_def),
1203 (crate::Static, ast::Static, static_to_def),
1204 (crate::Function, ast::Fn, fn_to_def),
1205 (crate::Field, ast::RecordField, record_field_to_def),
1206 (crate::Field, ast::TupleField, tuple_field_to_def),
1207 (crate::Variant, ast::Variant, enum_variant_to_def),
1208 (crate::TypeParam, ast::TypeParam, type_param_to_def),
1209 (crate::LifetimeParam, ast::LifetimeParam, lifetime_param_to_def),
1210 (crate::ConstParam, ast::ConstParam, const_param_to_def),
1211 (crate::GenericParam, ast::GenericParam, generic_param_to_def),
1212 (crate::MacroDef, ast::Macro, macro_to_def),
1213 (crate::Local, ast::IdentPat, bind_pat_to_def),
1214 (crate::Local, ast::SelfParam, self_param_to_def),
1215 (crate::Label, ast::Label, label_to_def),
1216 (crate::Adt, ast::Adt, adt_to_def),
1219 fn find_root(node: &SyntaxNode) -> SyntaxNode {
1220 node.ancestors().last().unwrap()
1223 /// `SemanticScope` encapsulates the notion of a scope (the set of visible
1224 /// names) at a particular program point.
1226 /// It is a bit tricky, as scopes do not really exist inside the compiler.
1227 /// Rather, the compiler directly computes for each reference the definition it
1228 /// refers to. It might transiently compute the explicit scope map while doing
1229 /// so, but, generally, this is not something left after the analysis.
1231 /// However, we do very much need explicit scopes for IDE purposes --
1232 /// completion, at its core, lists the contents of the current scope. The notion
1233 /// of scope is also useful to answer questions like "what would be the meaning
1234 /// of this piece of code if we inserted it into this position?".
1236 /// So `SemanticsScope` is constructed from a specific program point (a syntax
1237 /// node or just a raw offset) and provides access to the set of visible names
1238 /// on a somewhat best-effort basis.
1240 /// Note that if you are wondering "what does this specific existing name mean?",
1241 /// you'd better use the `resolve_` family of methods.
1243 pub struct SemanticsScope<'a> {
1244 pub db: &'a dyn HirDatabase,
1249 impl<'a> SemanticsScope<'a> {
1250 pub fn module(&self) -> Option<Module> {
1251 Some(Module { id: self.resolver.module()? })
1254 pub fn krate(&self) -> Option<Crate> {
1255 Some(Crate { id: self.resolver.krate()? })
1258 /// Note: `FxHashSet<TraitId>` should be treated as an opaque type, passed into `Type
1259 pub fn visible_traits(&self) -> FxHashSet<TraitId> {
1260 let resolver = &self.resolver;
1261 resolver.traits_in_scope(self.db.upcast())
1264 pub fn process_all_names(&self, f: &mut dyn FnMut(Name, ScopeDef)) {
1265 let scope = self.resolver.names_in_scope(self.db.upcast());
1266 for (name, entries) in scope {
1267 for entry in entries {
1268 let def = match entry {
1269 resolver::ScopeDef::ModuleDef(it) => ScopeDef::ModuleDef(it.into()),
1270 resolver::ScopeDef::MacroDef(it) => ScopeDef::MacroDef(it.into()),
1271 resolver::ScopeDef::Unknown => ScopeDef::Unknown,
1272 resolver::ScopeDef::ImplSelfType(it) => ScopeDef::ImplSelfType(it.into()),
1273 resolver::ScopeDef::AdtSelfType(it) => ScopeDef::AdtSelfType(it.into()),
1274 resolver::ScopeDef::GenericParam(id) => ScopeDef::GenericParam(id.into()),
1275 resolver::ScopeDef::Local(pat_id) => {
1276 let parent = self.resolver.body_owner().unwrap();
1277 ScopeDef::Local(Local { parent, pat_id })
1279 resolver::ScopeDef::Label(label_id) => {
1280 let parent = self.resolver.body_owner().unwrap();
1281 ScopeDef::Label(Label { parent, label_id })
1284 f(name.clone(), def)
1289 /// Resolve a path as-if it was written at the given scope. This is
1290 /// necessary a heuristic, as it doesn't take hygiene into account.
1291 pub fn speculative_resolve(&self, path: &ast::Path) -> Option<PathResolution> {
1292 let ctx = body::LowerCtx::new(self.db.upcast(), self.file_id);
1293 let path = Path::from_src(path.clone(), &ctx)?;
1294 resolve_hir_path(self.db, &self.resolver, &path)