5 use std::{cell::RefCell, fmt, iter};
7 use base_db::{FileId, FileRange};
10 resolver::{self, HasResolver, Resolver, TypeNs},
11 AsMacroCall, FunctionId, TraitId, VariantId,
14 name::{known, AsName},
15 ExpansionInfo, MacroCallId,
18 use itertools::Itertools;
19 use rustc_hash::{FxHashMap, FxHashSet};
20 use smallvec::{smallvec, SmallVec};
22 algo::skip_trivia_token,
23 ast::{self, HasAttrs as _, HasGenericParams, HasLoopBody},
24 match_ast, AstNode, Direction, SyntaxNode, SyntaxNodePtr, SyntaxToken, TextSize,
29 semantics::source_to_def::{ChildContainer, SourceToDefCache, SourceToDefCtx},
30 source_analyzer::{resolve_hir_path, SourceAnalyzer},
31 Access, AssocItem, BuiltinAttr, Callable, ConstParam, Crate, Field, Function, HasSource,
32 HirFileId, Impl, InFile, Label, LifetimeParam, Local, MacroDef, Module, ModuleDef, Name, Path,
33 ScopeDef, ToolModule, Trait, Type, TypeAlias, TypeParam, VariantDef,
36 #[derive(Debug, Clone, PartialEq, Eq)]
37 pub enum PathResolution {
40 /// A local binding (only value namespace)
45 ConstParam(ConstParam),
49 BuiltinAttr(BuiltinAttr),
50 ToolModule(ToolModule),
54 pub(crate) fn in_type_ns(&self) -> Option<TypeNs> {
56 PathResolution::Def(ModuleDef::Adt(adt)) => Some(TypeNs::AdtId((*adt).into())),
57 PathResolution::Def(ModuleDef::BuiltinType(builtin)) => {
58 Some(TypeNs::BuiltinType((*builtin).into()))
62 | ModuleDef::Variant(_)
63 | ModuleDef::Function(_)
64 | ModuleDef::Module(_)
65 | ModuleDef::Static(_)
66 | ModuleDef::Trait(_),
68 PathResolution::Def(ModuleDef::TypeAlias(alias)) => {
69 Some(TypeNs::TypeAliasId((*alias).into()))
71 PathResolution::BuiltinAttr(_)
72 | PathResolution::ToolModule(_)
73 | PathResolution::Local(_)
74 | PathResolution::Macro(_)
75 | PathResolution::ConstParam(_) => None,
76 PathResolution::TypeParam(param) => Some(TypeNs::GenericParam((*param).into())),
77 PathResolution::SelfType(impl_def) => Some(TypeNs::SelfType((*impl_def).into())),
78 PathResolution::AssocItem(AssocItem::Const(_) | AssocItem::Function(_)) => None,
79 PathResolution::AssocItem(AssocItem::TypeAlias(alias)) => {
80 Some(TypeNs::TypeAliasId((*alias).into()))
88 /// The original type of the expression or pattern.
90 /// The adjusted type, if an adjustment happened.
91 pub adjusted: Option<Type>,
95 pub fn original(self) -> Type {
99 pub fn has_adjustment(&self) -> bool {
100 self.adjusted.is_some()
103 /// The adjusted type, or the original in case no adjustments occurred.
104 pub fn adjusted(self) -> Type {
105 self.adjusted.unwrap_or(self.original)
109 /// Primary API to get semantic information, like types, from syntax trees.
110 pub struct Semantics<'db, DB> {
112 imp: SemanticsImpl<'db>,
115 pub struct SemanticsImpl<'db> {
116 pub db: &'db dyn HirDatabase,
117 s2d_cache: RefCell<SourceToDefCache>,
118 expansion_info_cache: RefCell<FxHashMap<HirFileId, Option<ExpansionInfo>>>,
119 // Rootnode to HirFileId cache
120 cache: RefCell<FxHashMap<SyntaxNode, HirFileId>>,
121 // MacroCall to its expansion's HirFileId cache
122 macro_call_cache: RefCell<FxHashMap<InFile<ast::MacroCall>, HirFileId>>,
125 impl<DB> fmt::Debug for Semantics<'_, DB> {
126 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127 write!(f, "Semantics {{ ... }}")
131 impl<'db, DB: HirDatabase> Semantics<'db, DB> {
132 pub fn new(db: &DB) -> Semantics<DB> {
133 let impl_ = SemanticsImpl::new(db);
134 Semantics { db, imp: impl_ }
137 pub fn parse(&self, file_id: FileId) -> ast::SourceFile {
138 self.imp.parse(file_id)
141 pub fn parse_or_expand(&self, file_id: HirFileId) -> Option<SyntaxNode> {
142 self.imp.parse_or_expand(file_id)
145 pub fn expand(&self, macro_call: &ast::MacroCall) -> Option<SyntaxNode> {
146 self.imp.expand(macro_call)
149 /// If `item` has an attribute macro attached to it, expands it.
150 pub fn expand_attr_macro(&self, item: &ast::Item) -> Option<SyntaxNode> {
151 self.imp.expand_attr_macro(item)
154 pub fn resolve_derive_macro(&self, derive: &ast::Attr) -> Option<Vec<Option<MacroDef>>> {
155 self.imp.resolve_derive_macro(derive)
158 pub fn expand_derive_macro(&self, derive: &ast::Attr) -> Option<Vec<SyntaxNode>> {
159 self.imp.expand_derive_macro(derive)
162 pub fn is_attr_macro_call(&self, item: &ast::Item) -> bool {
163 self.imp.is_attr_macro_call(item)
166 pub fn is_derive_annotated(&self, item: &ast::Adt) -> bool {
167 self.imp.is_derive_annotated(item)
170 pub fn speculative_expand(
172 actual_macro_call: &ast::MacroCall,
173 speculative_args: &ast::TokenTree,
174 token_to_map: SyntaxToken,
175 ) -> Option<(SyntaxNode, SyntaxToken)> {
176 self.imp.speculative_expand(actual_macro_call, speculative_args, token_to_map)
179 pub fn speculative_expand_attr_macro(
181 actual_macro_call: &ast::Item,
182 speculative_args: &ast::Item,
183 token_to_map: SyntaxToken,
184 ) -> Option<(SyntaxNode, SyntaxToken)> {
185 self.imp.speculative_expand_attr(actual_macro_call, speculative_args, token_to_map)
188 /// Descend the token into macrocalls to its first mapped counterpart.
189 pub fn descend_into_macros_single(&self, token: SyntaxToken) -> SyntaxToken {
190 self.imp.descend_into_macros_single(token)
193 /// Descend the token into macrocalls to all its mapped counterparts.
194 pub fn descend_into_macros(&self, token: SyntaxToken) -> SmallVec<[SyntaxToken; 1]> {
195 self.imp.descend_into_macros(token)
198 /// Maps a node down by mapping its first and last token down.
199 pub fn descend_node_into_attributes<N: AstNode>(&self, node: N) -> SmallVec<[N; 1]> {
200 self.imp.descend_node_into_attributes(node)
203 /// Search for a definition's source and cache its syntax tree
204 pub fn source<Def: HasSource>(&self, def: Def) -> Option<InFile<Def::Ast>>
211 pub fn hir_file_for(&self, syntax_node: &SyntaxNode) -> HirFileId {
212 self.imp.find_file(syntax_node).file_id
215 /// Attempts to map the node out of macro expanded files returning the original file range.
216 /// If upmapping is not possible, this will fall back to the range of the macro call of the
217 /// macro file the node resides in.
218 pub fn original_range(&self, node: &SyntaxNode) -> FileRange {
219 self.imp.original_range(node)
222 /// Attempts to map the node out of macro expanded files returning the original file range.
223 pub fn original_range_opt(&self, node: &SyntaxNode) -> Option<FileRange> {
224 self.imp.original_range_opt(node)
227 /// Attempts to map the node out of macro expanded files.
228 /// This only work for attribute expansions, as other ones do not have nodes as input.
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 record_literal_missing_fields(&self, literal: &ast::RecordExpr) -> Vec<(Field, Type)> {
359 self.imp.record_literal_missing_fields(literal)
362 pub fn record_pattern_missing_fields(&self, pattern: &ast::RecordPat) -> Vec<(Field, Type)> {
363 self.imp.record_pattern_missing_fields(pattern)
366 pub fn to_def<T: ToDef>(&self, src: &T) -> Option<T::Def> {
367 let src = self.imp.find_file(src.syntax()).with_value(src).cloned();
368 T::to_def(&self.imp, src)
371 pub fn to_module_def(&self, file: FileId) -> Option<Module> {
372 self.imp.to_module_def(file).next()
375 pub fn to_module_defs(&self, file: FileId) -> impl Iterator<Item = Module> {
376 self.imp.to_module_def(file)
379 pub fn scope(&self, node: &SyntaxNode) -> SemanticsScope<'db> {
383 pub fn scope_at_offset(&self, node: &SyntaxNode, offset: TextSize) -> SemanticsScope<'db> {
384 self.imp.scope_at_offset(&node, offset)
387 pub fn scope_for_def(&self, def: Trait) -> SemanticsScope<'db> {
388 self.imp.scope_for_def(def)
391 pub fn assert_contains_node(&self, node: &SyntaxNode) {
392 self.imp.assert_contains_node(node)
395 pub fn is_unsafe_method_call(&self, method_call_expr: &ast::MethodCallExpr) -> bool {
396 self.imp.is_unsafe_method_call(method_call_expr)
399 pub fn is_unsafe_ref_expr(&self, ref_expr: &ast::RefExpr) -> bool {
400 self.imp.is_unsafe_ref_expr(ref_expr)
403 pub fn is_unsafe_ident_pat(&self, ident_pat: &ast::IdentPat) -> bool {
404 self.imp.is_unsafe_ident_pat(ident_pat)
408 impl<'db> SemanticsImpl<'db> {
409 fn new(db: &'db dyn HirDatabase) -> Self {
412 s2d_cache: Default::default(),
413 cache: Default::default(),
414 expansion_info_cache: Default::default(),
415 macro_call_cache: Default::default(),
419 fn parse(&self, file_id: FileId) -> ast::SourceFile {
420 let tree = self.db.parse(file_id).tree();
421 self.cache(tree.syntax().clone(), file_id.into());
425 fn parse_or_expand(&self, file_id: HirFileId) -> Option<SyntaxNode> {
426 let node = self.db.parse_or_expand(file_id)?;
427 self.cache(node.clone(), file_id);
431 fn expand(&self, macro_call: &ast::MacroCall) -> Option<SyntaxNode> {
432 let sa = self.analyze_no_infer(macro_call.syntax());
433 let file_id = sa.expand(self.db, InFile::new(sa.file_id, macro_call))?;
434 let node = self.parse_or_expand(file_id)?;
438 fn expand_attr_macro(&self, item: &ast::Item) -> Option<SyntaxNode> {
439 let src = self.wrap_node_infile(item.clone());
440 let macro_call_id = self.with_ctx(|ctx| ctx.item_to_macro_call(src))?;
441 let file_id = macro_call_id.as_file();
442 let node = self.parse_or_expand(file_id)?;
446 fn resolve_derive_macro(&self, attr: &ast::Attr) -> Option<Vec<Option<MacroDef>>> {
448 .derive_macro_calls(attr)?
450 .map(|call| Some(MacroDef { id: self.db.lookup_intern_macro_call(call?).def }))
455 fn expand_derive_macro(&self, attr: &ast::Attr) -> Option<Vec<SyntaxNode>> {
456 let res: Vec<_> = self
457 .derive_macro_calls(attr)?
460 let file_id = call?.as_file();
461 let node = self.db.parse_or_expand(file_id)?;
462 self.cache(node.clone(), file_id);
469 fn derive_macro_calls(&self, attr: &ast::Attr) -> Option<Vec<Option<MacroCallId>>> {
470 let adt = attr.syntax().parent().and_then(ast::Adt::cast)?;
471 let file_id = self.find_file(adt.syntax()).file_id;
472 let adt = InFile::new(file_id, &adt);
473 let src = InFile::new(file_id, attr.clone());
474 self.with_ctx(|ctx| {
475 let (.., res) = ctx.attr_to_derive_macro_call(adt, src)?;
480 fn is_derive_annotated(&self, adt: &ast::Adt) -> bool {
481 let file_id = self.find_file(adt.syntax()).file_id;
482 let adt = InFile::new(file_id, adt);
483 self.with_ctx(|ctx| ctx.has_derives(adt))
486 fn is_attr_macro_call(&self, item: &ast::Item) -> bool {
487 let file_id = self.find_file(item.syntax()).file_id;
488 let src = InFile::new(file_id, item.clone());
489 self.with_ctx(|ctx| ctx.item_to_macro_call(src).is_some())
492 fn speculative_expand(
494 actual_macro_call: &ast::MacroCall,
495 speculative_args: &ast::TokenTree,
496 token_to_map: SyntaxToken,
497 ) -> Option<(SyntaxNode, SyntaxToken)> {
498 let SourceAnalyzer { file_id, resolver, .. } =
499 self.analyze_no_infer(actual_macro_call.syntax());
500 let macro_call = InFile::new(file_id, actual_macro_call);
501 let krate = resolver.krate()?;
502 let macro_call_id = macro_call.as_call_id(self.db.upcast(), krate, |path| {
503 resolver.resolve_path_as_macro(self.db.upcast(), &path)
505 hir_expand::db::expand_speculative(
508 speculative_args.syntax(),
513 fn speculative_expand_attr(
515 actual_macro_call: &ast::Item,
516 speculative_args: &ast::Item,
517 token_to_map: SyntaxToken,
518 ) -> Option<(SyntaxNode, SyntaxToken)> {
519 let macro_call = self.wrap_node_infile(actual_macro_call.clone());
520 let macro_call_id = self.with_ctx(|ctx| ctx.item_to_macro_call(macro_call))?;
521 hir_expand::db::expand_speculative(
524 speculative_args.syntax(),
529 // This might not be the correct way to do this, but it works for now
530 fn descend_node_into_attributes<N: AstNode>(&self, node: N) -> SmallVec<[N; 1]> {
531 let mut res = smallvec![];
533 let first = skip_trivia_token(node.syntax().first_token()?, Direction::Next)?;
534 let last = skip_trivia_token(node.syntax().last_token()?, Direction::Prev)?;
537 let (first, last) = match tokens {
543 self.descend_into_macros_impl(
545 &mut |InFile { value, .. }| {
546 if let Some(node) = value.ancestors().find_map(N::cast) {
553 // Descend first and last token, then zip them to look for the node they belong to
554 let mut scratch: SmallVec<[_; 1]> = smallvec![];
555 self.descend_into_macros_impl(
563 let mut scratch = scratch.into_iter();
564 self.descend_into_macros_impl(
566 &mut |InFile { value: last, file_id: last_fid }| {
567 if let Some(InFile { value: first, file_id: first_fid }) = scratch.next() {
568 if first_fid == last_fid {
569 if let Some(p) = first.parent() {
570 let range = first.text_range().cover(last.text_range());
571 let node = find_root(&p)
572 .covering_element(range)
574 .take_while(|it| it.text_range() == range)
576 if let Some(node) = node {
589 fn descend_into_macros(&self, token: SyntaxToken) -> SmallVec<[SyntaxToken; 1]> {
590 let mut res = smallvec![];
591 self.descend_into_macros_impl(token, &mut |InFile { value, .. }| res.push(value), false);
595 fn descend_into_macros_single(&self, token: SyntaxToken) -> SyntaxToken {
596 let mut res = token.clone();
597 self.descend_into_macros_impl(token, &mut |InFile { value, .. }| res = value, true);
601 fn descend_into_macros_impl(
604 f: &mut dyn FnMut(InFile<SyntaxToken>),
607 let _p = profile::span("descend_into_macros");
608 let parent = match token.parent() {
612 let sa = self.analyze_no_infer(&parent);
613 let mut stack: SmallVec<[_; 4]> = smallvec![InFile::new(sa.file_id, token)];
614 let mut cache = self.expansion_info_cache.borrow_mut();
615 let mut mcache = self.macro_call_cache.borrow_mut();
617 let mut process_expansion_for_token =
618 |stack: &mut SmallVec<_>, macro_file, item, token: InFile<&_>| {
619 let expansion_info = cache
621 .or_insert_with(|| macro_file.expansion_info(self.db.upcast()))
625 let InFile { file_id, value } = expansion_info.expanded();
626 self.cache(value, file_id);
629 let mut mapped_tokens =
630 expansion_info.map_token_down(self.db.upcast(), item, token)?;
632 let len = stack.len();
633 // requeue the tokens we got from mapping our current token down
635 stack.extend(mapped_tokens.next());
637 stack.extend(mapped_tokens);
639 // if the length changed we have found a mapping for the token
640 (stack.len() != len).then(|| ())
643 // Remap the next token in the queue into a macro call its in, if it is not being remapped
644 // either due to not being in a macro-call or because its unused push it into the result vec,
645 // otherwise push the remapped tokens back into the queue as they can potentially be remapped again.
646 while let Some(token) = stack.pop() {
647 self.db.unwind_if_cancelled();
648 let was_not_remapped = (|| {
649 // are we inside an attribute macro call
650 let containing_attribute_macro_call = self.with_ctx(|ctx| {
651 token.value.ancestors().filter_map(ast::Item::cast).find_map(|item| {
652 if item.attrs().next().is_none() {
653 // Don't force populate the dyn cache for items that don't have an attribute anyways
656 Some((ctx.item_to_macro_call(token.with_value(item.clone()))?, item))
659 if let Some((call_id, item)) = containing_attribute_macro_call {
660 let file_id = call_id.as_file();
661 return process_expansion_for_token(
669 // or are we inside a function-like macro call
671 // FIXME replace map.while_some with take_while once stable
672 token.value.ancestors().map(ast::TokenTree::cast).while_some().last()
674 let parent = tt.syntax().parent()?;
675 // check for derive attribute here
676 let macro_call = match_ast! {
678 ast::MacroCall(mcall) => mcall,
679 // attribute we failed expansion for earlier, this might be a derive invocation
680 // so try downmapping the token into the pseudo derive expansion
681 // see [hir_expand::builtin_attr_macro] for how the pseudo derive expansion works
683 let attr = meta.parent_attr()?;
684 let adt = attr.syntax().parent().and_then(ast::Adt::cast)?;
685 let call_id = self.with_ctx(|ctx| {
686 let (_, call_id, _) = ctx.attr_to_derive_macro_call(
687 token.with_value(&adt),
688 token.with_value(attr),
692 let file_id = call_id.as_file();
693 return process_expansion_for_token(
704 if tt.left_delimiter_token().map_or(false, |it| it == token.value) {
707 if tt.right_delimiter_token().map_or(false, |it| it == token.value) {
711 let mcall = token.with_value(macro_call);
712 let file_id = match mcache.get(&mcall) {
715 let it = sa.expand(self.db, mcall.as_ref())?;
716 mcache.insert(mcall, it);
720 return process_expansion_for_token(&mut stack, file_id, None, token.as_ref());
723 // outside of a macro invocation so this is a "final" token
728 if was_not_remapped {
734 // Note this return type is deliberate as [`find_nodes_at_offset_with_descend`] wants to stop
735 // traversing the inner iterator when it finds a node.
736 // The outer iterator is over the tokens descendants
737 // The inner iterator is the ancestors of a descendant
738 fn descend_node_at_offset(
742 ) -> impl Iterator<Item = impl Iterator<Item = SyntaxNode> + '_> + '_ {
743 node.token_at_offset(offset)
744 .map(move |token| self.descend_into_macros(token))
746 descendants.into_iter().map(move |it| self.token_ancestors_with_macros(it))
748 // re-order the tokens from token_at_offset by returning the ancestors with the smaller first nodes first
749 // See algo::ancestors_at_offset, which uses the same approach
750 .kmerge_by(|left, right| {
752 .map(|node| node.text_range().len())
753 .lt(right.clone().map(|node| node.text_range().len()))
757 fn original_range(&self, node: &SyntaxNode) -> FileRange {
758 let node = self.find_file(node);
759 node.original_file_range(self.db.upcast())
762 fn original_range_opt(&self, node: &SyntaxNode) -> Option<FileRange> {
763 let node = self.find_file(node);
764 node.original_file_range_opt(self.db.upcast())
767 fn original_ast_node<N: AstNode>(&self, node: N) -> Option<N> {
768 self.wrap_node_infile(node).original_ast_node(self.db.upcast()).map(|it| it.value)
771 fn diagnostics_display_range(&self, src: InFile<SyntaxNodePtr>) -> FileRange {
772 let root = self.parse_or_expand(src.file_id).unwrap();
773 let node = src.map(|it| it.to_node(&root));
774 node.as_ref().original_file_range(self.db.upcast())
777 fn token_ancestors_with_macros(
780 ) -> impl Iterator<Item = SyntaxNode> + Clone + '_ {
781 token.parent().into_iter().flat_map(move |parent| self.ancestors_with_macros(parent))
784 fn ancestors_with_macros(
787 ) -> impl Iterator<Item = SyntaxNode> + Clone + '_ {
788 let node = self.find_file(&node);
789 let db = self.db.upcast();
790 iter::successors(Some(node.cloned()), move |&InFile { file_id, ref value }| {
791 match value.parent() {
792 Some(parent) => Some(InFile::new(file_id, parent)),
794 self.cache(value.clone(), file_id);
795 file_id.call_node(db)
802 fn ancestors_at_offset_with_macros(
806 ) -> impl Iterator<Item = SyntaxNode> + '_ {
807 node.token_at_offset(offset)
808 .map(|token| self.token_ancestors_with_macros(token))
809 .kmerge_by(|node1, node2| node1.text_range().len() < node2.text_range().len())
812 fn resolve_lifetime_param(&self, lifetime: &ast::Lifetime) -> Option<LifetimeParam> {
813 let text = lifetime.text();
814 let lifetime_param = lifetime.syntax().ancestors().find_map(|syn| {
815 let gpl = ast::AnyHasGenericParams::cast(syn)?.generic_param_list()?;
816 gpl.lifetime_params()
817 .find(|tp| tp.lifetime().as_ref().map(|lt| lt.text()).as_ref() == Some(&text))
819 let src = self.wrap_node_infile(lifetime_param);
820 ToDef::to_def(self, src)
823 fn resolve_label(&self, lifetime: &ast::Lifetime) -> Option<Label> {
824 let text = lifetime.text();
825 let label = lifetime.syntax().ancestors().find_map(|syn| {
826 let label = match_ast! {
828 ast::ForExpr(it) => it.label(),
829 ast::WhileExpr(it) => it.label(),
830 ast::LoopExpr(it) => it.label(),
831 ast::BlockExpr(it) => it.label(),
837 .and_then(|lt| lt.lifetime_ident_token())
838 .map_or(false, |lt| lt.text() == text)
841 let src = self.wrap_node_infile(label);
842 ToDef::to_def(self, src)
845 fn resolve_type(&self, ty: &ast::Type) -> Option<Type> {
846 let scope = self.scope(ty.syntax());
847 let ctx = body::LowerCtx::new(self.db.upcast(), scope.file_id);
848 let ty = hir_ty::TyLoweringContext::new(self.db, &scope.resolver)
849 .lower_ty(&crate::TypeRef::from_ast(&ctx, ty.clone()));
850 Type::new_with_resolver(self.db, &scope.resolver, ty)
853 fn type_of_expr(&self, expr: &ast::Expr) -> Option<TypeInfo> {
854 self.analyze(expr.syntax())
855 .type_of_expr(self.db, expr)
856 .map(|(ty, coerced)| TypeInfo { original: ty, adjusted: coerced })
859 fn type_of_pat(&self, pat: &ast::Pat) -> Option<TypeInfo> {
860 self.analyze(pat.syntax())
861 .type_of_pat(self.db, pat)
862 .map(|(ty, coerced)| TypeInfo { original: ty, adjusted: coerced })
865 fn type_of_self(&self, param: &ast::SelfParam) -> Option<Type> {
866 self.analyze(param.syntax()).type_of_self(self.db, param)
869 fn resolve_method_call(&self, call: &ast::MethodCallExpr) -> Option<FunctionId> {
870 self.analyze(call.syntax()).resolve_method_call(self.db, call).map(|(id, _)| id)
873 fn resolve_method_call_as_callable(&self, call: &ast::MethodCallExpr) -> Option<Callable> {
874 let (func, subst) = self.analyze(call.syntax()).resolve_method_call(self.db, call)?;
875 let ty = self.db.value_ty(func.into()).substitute(Interner, &subst);
876 let resolver = self.analyze(call.syntax()).resolver;
877 let ty = Type::new_with_resolver(self.db, &resolver, ty)?;
878 let mut res = ty.as_callable(self.db)?;
879 res.is_bound_method = true;
883 fn resolve_field(&self, field: &ast::FieldExpr) -> Option<Field> {
884 self.analyze(field.syntax()).resolve_field(self.db, field)
887 fn resolve_record_field(
889 field: &ast::RecordExprField,
890 ) -> Option<(Field, Option<Local>, Type)> {
891 self.analyze(field.syntax()).resolve_record_field(self.db, field)
894 fn resolve_record_pat_field(&self, field: &ast::RecordPatField) -> Option<Field> {
895 self.analyze(field.syntax()).resolve_record_pat_field(self.db, field)
898 fn resolve_macro_call(&self, macro_call: &ast::MacroCall) -> Option<MacroDef> {
899 let sa = self.analyze(macro_call.syntax());
900 let macro_call = self.find_file(macro_call.syntax()).with_value(macro_call);
901 sa.resolve_macro_call(self.db, macro_call)
904 fn resolve_attr_macro_call(&self, item: &ast::Item) -> Option<MacroDef> {
905 let item_in_file = self.wrap_node_infile(item.clone());
906 let macro_call_id = self.with_ctx(|ctx| ctx.item_to_macro_call(item_in_file))?;
907 Some(MacroDef { id: self.db.lookup_intern_macro_call(macro_call_id).def })
910 fn resolve_path(&self, path: &ast::Path) -> Option<PathResolution> {
911 self.analyze(path.syntax()).resolve_path(self.db, path)
914 fn resolve_extern_crate(&self, extern_crate: &ast::ExternCrate) -> Option<Crate> {
915 let krate = self.scope(extern_crate.syntax()).krate()?;
916 let name = extern_crate.name_ref()?.as_name();
917 if name == known::SELF_PARAM {
921 .dependencies(self.db)
923 .find_map(|dep| (dep.name == name).then(|| dep.krate))
926 fn resolve_variant(&self, record_lit: ast::RecordExpr) -> Option<VariantId> {
927 self.analyze(record_lit.syntax()).resolve_variant(self.db, record_lit)
930 fn resolve_bind_pat_to_const(&self, pat: &ast::IdentPat) -> Option<ModuleDef> {
931 self.analyze(pat.syntax()).resolve_bind_pat_to_const(self.db, pat)
934 fn record_literal_missing_fields(&self, literal: &ast::RecordExpr) -> Vec<(Field, Type)> {
935 self.analyze(literal.syntax())
936 .record_literal_missing_fields(self.db, literal)
940 fn record_pattern_missing_fields(&self, pattern: &ast::RecordPat) -> Vec<(Field, Type)> {
941 self.analyze(pattern.syntax())
942 .record_pattern_missing_fields(self.db, pattern)
946 fn with_ctx<F: FnOnce(&mut SourceToDefCtx) -> T, T>(&self, f: F) -> T {
947 let mut cache = self.s2d_cache.borrow_mut();
948 let mut ctx = SourceToDefCtx { db: self.db, cache: &mut *cache };
952 fn to_module_def(&self, file: FileId) -> impl Iterator<Item = Module> {
953 self.with_ctx(|ctx| ctx.file_to_def(file)).into_iter().map(Module::from)
956 fn scope(&self, node: &SyntaxNode) -> SemanticsScope<'db> {
957 let SourceAnalyzer { file_id, resolver, .. } = self.analyze_no_infer(node);
958 SemanticsScope { db: self.db, file_id, resolver }
961 fn scope_at_offset(&self, node: &SyntaxNode, offset: TextSize) -> SemanticsScope<'db> {
962 let SourceAnalyzer { file_id, resolver, .. } =
963 self.analyze_with_offset_no_infer(node, offset);
964 SemanticsScope { db: self.db, file_id, resolver }
967 fn scope_for_def(&self, def: Trait) -> SemanticsScope<'db> {
968 let file_id = self.db.lookup_intern_trait(def.id).id.file_id();
969 let resolver = def.id.resolver(self.db.upcast());
970 SemanticsScope { db: self.db, file_id, resolver }
973 fn source<Def: HasSource>(&self, def: Def) -> Option<InFile<Def::Ast>>
977 let res = def.source(self.db)?;
978 self.cache(find_root(res.value.syntax()), res.file_id);
982 fn analyze(&self, node: &SyntaxNode) -> SourceAnalyzer {
983 self.analyze_impl(node, None, true)
986 fn analyze_no_infer(&self, node: &SyntaxNode) -> SourceAnalyzer {
987 self.analyze_impl(node, None, false)
990 fn analyze_with_offset_no_infer(&self, node: &SyntaxNode, offset: TextSize) -> SourceAnalyzer {
991 self.analyze_impl(node, Some(offset), false)
997 offset: Option<TextSize>,
999 ) -> SourceAnalyzer {
1000 let _p = profile::span("Semantics::analyze_impl");
1001 let node = self.find_file(node);
1003 let container = match self.with_ctx(|ctx| ctx.find_container(node)) {
1005 None => return SourceAnalyzer::new_for_resolver(Resolver::default(), node),
1008 let resolver = match container {
1009 ChildContainer::DefWithBodyId(def) => {
1010 return if infer_body {
1011 SourceAnalyzer::new_for_body(self.db, def, node, offset)
1013 SourceAnalyzer::new_for_body_no_infer(self.db, def, node, offset)
1016 ChildContainer::TraitId(it) => it.resolver(self.db.upcast()),
1017 ChildContainer::ImplId(it) => it.resolver(self.db.upcast()),
1018 ChildContainer::ModuleId(it) => it.resolver(self.db.upcast()),
1019 ChildContainer::EnumId(it) => it.resolver(self.db.upcast()),
1020 ChildContainer::VariantId(it) => it.resolver(self.db.upcast()),
1021 ChildContainer::TypeAliasId(it) => it.resolver(self.db.upcast()),
1022 ChildContainer::GenericDefId(it) => it.resolver(self.db.upcast()),
1024 SourceAnalyzer::new_for_resolver(resolver, node)
1027 fn cache(&self, root_node: SyntaxNode, file_id: HirFileId) {
1028 assert!(root_node.parent().is_none());
1029 let mut cache = self.cache.borrow_mut();
1030 let prev = cache.insert(root_node, file_id);
1031 assert!(prev == None || prev == Some(file_id))
1034 fn assert_contains_node(&self, node: &SyntaxNode) {
1035 self.find_file(node);
1038 fn lookup(&self, root_node: &SyntaxNode) -> Option<HirFileId> {
1039 let cache = self.cache.borrow();
1040 cache.get(root_node).copied()
1043 fn wrap_node_infile<N: AstNode>(&self, node: N) -> InFile<N> {
1044 let InFile { file_id, .. } = self.find_file(node.syntax());
1045 InFile::new(file_id, node)
1048 fn find_file<'node>(&self, node: &'node SyntaxNode) -> InFile<&'node SyntaxNode> {
1049 let root_node = find_root(node);
1050 let file_id = self.lookup(&root_node).unwrap_or_else(|| {
1052 "\n\nFailed to lookup {:?} in this Semantics.\n\
1053 Make sure to use only query nodes, derived from this instance of Semantics.\n\
1055 known nodes: {}\n\n",
1061 .map(|it| format!("{:?}", it))
1062 .collect::<Vec<_>>()
1066 InFile::new(file_id, node)
1069 fn is_unsafe_method_call(&self, method_call_expr: &ast::MethodCallExpr) -> bool {
1073 let field_expr = match expr {
1074 ast::Expr::FieldExpr(field_expr) => field_expr,
1077 let ty = self.type_of_expr(&field_expr.expr()?)?.original;
1078 if !ty.is_packed(self.db) {
1082 let func = self.resolve_method_call(method_call_expr).map(Function::from)?;
1083 let res = match func.self_param(self.db)?.access(self.db) {
1084 Access::Shared | Access::Exclusive => true,
1085 Access::Owned => false,
1092 fn is_unsafe_ref_expr(&self, ref_expr: &ast::RefExpr) -> bool {
1096 let field_expr = match expr {
1097 ast::Expr::FieldExpr(field_expr) => field_expr,
1100 let expr = field_expr.expr()?;
1101 self.type_of_expr(&expr)
1103 // Binding a reference to a packed type is possibly unsafe.
1104 .map(|ty| ty.original.is_packed(self.db))
1107 // FIXME This needs layout computation to be correct. It will highlight
1108 // more than it should with the current implementation.
1111 fn is_unsafe_ident_pat(&self, ident_pat: &ast::IdentPat) -> bool {
1112 if ident_pat.ref_token().is_none() {
1119 .and_then(|parent| {
1120 // `IdentPat` can live under `RecordPat` directly under `RecordPatField` or
1121 // `RecordPatFieldList`. `RecordPatField` also lives under `RecordPatFieldList`,
1122 // so this tries to lookup the `IdentPat` anywhere along that structure to the
1123 // `RecordPat` so we can get the containing type.
1124 let record_pat = ast::RecordPatField::cast(parent.clone())
1125 .and_then(|record_pat| record_pat.syntax().parent())
1126 .or_else(|| Some(parent.clone()))
1127 .and_then(|parent| {
1128 ast::RecordPatFieldList::cast(parent)?
1131 .and_then(ast::RecordPat::cast)
1134 // If this doesn't match a `RecordPat`, fallback to a `LetStmt` to see if
1135 // this is initialized from a `FieldExpr`.
1136 if let Some(record_pat) = record_pat {
1137 self.type_of_pat(&ast::Pat::RecordPat(record_pat))
1138 } else if let Some(let_stmt) = ast::LetStmt::cast(parent) {
1139 let field_expr = match let_stmt.initializer()? {
1140 ast::Expr::FieldExpr(field_expr) => field_expr,
1144 self.type_of_expr(&field_expr.expr()?)
1149 // Binding a reference to a packed type is possibly unsafe.
1150 .map(|ty| ty.original.is_packed(self.db))
1155 pub trait ToDef: AstNode + Clone {
1158 fn to_def(sema: &SemanticsImpl, src: InFile<Self>) -> Option<Self::Def>;
1161 macro_rules! to_def_impls {
1162 ($(($def:path, $ast:path, $meth:ident)),* ,) => {$(
1163 impl ToDef for $ast {
1165 fn to_def(sema: &SemanticsImpl, src: InFile<Self>) -> Option<Self::Def> {
1166 sema.with_ctx(|ctx| ctx.$meth(src)).map(<$def>::from)
1173 (crate::Module, ast::Module, module_to_def),
1174 (crate::Module, ast::SourceFile, source_file_to_def),
1175 (crate::Struct, ast::Struct, struct_to_def),
1176 (crate::Enum, ast::Enum, enum_to_def),
1177 (crate::Union, ast::Union, union_to_def),
1178 (crate::Trait, ast::Trait, trait_to_def),
1179 (crate::Impl, ast::Impl, impl_to_def),
1180 (crate::TypeAlias, ast::TypeAlias, type_alias_to_def),
1181 (crate::Const, ast::Const, const_to_def),
1182 (crate::Static, ast::Static, static_to_def),
1183 (crate::Function, ast::Fn, fn_to_def),
1184 (crate::Field, ast::RecordField, record_field_to_def),
1185 (crate::Field, ast::TupleField, tuple_field_to_def),
1186 (crate::Variant, ast::Variant, enum_variant_to_def),
1187 (crate::TypeParam, ast::TypeParam, type_param_to_def),
1188 (crate::LifetimeParam, ast::LifetimeParam, lifetime_param_to_def),
1189 (crate::ConstParam, ast::ConstParam, const_param_to_def),
1190 (crate::GenericParam, ast::GenericParam, generic_param_to_def),
1191 (crate::MacroDef, ast::Macro, macro_to_def),
1192 (crate::Local, ast::IdentPat, bind_pat_to_def),
1193 (crate::Local, ast::SelfParam, self_param_to_def),
1194 (crate::Label, ast::Label, label_to_def),
1195 (crate::Adt, ast::Adt, adt_to_def),
1198 fn find_root(node: &SyntaxNode) -> SyntaxNode {
1199 node.ancestors().last().unwrap()
1202 /// `SemanticScope` encapsulates the notion of a scope (the set of visible
1203 /// names) at a particular program point.
1205 /// It is a bit tricky, as scopes do not really exist inside the compiler.
1206 /// Rather, the compiler directly computes for each reference the definition it
1207 /// refers to. It might transiently compute the explicit scope map while doing
1208 /// so, but, generally, this is not something left after the analysis.
1210 /// However, we do very much need explicit scopes for IDE purposes --
1211 /// completion, at its core, lists the contents of the current scope. The notion
1212 /// of scope is also useful to answer questions like "what would be the meaning
1213 /// of this piece of code if we inserted it into this position?".
1215 /// So `SemanticsScope` is constructed from a specific program point (a syntax
1216 /// node or just a raw offset) and provides access to the set of visible names
1217 /// on a somewhat best-effort basis.
1219 /// Note that if you are wondering "what does this specific existing name mean?",
1220 /// you'd better use the `resolve_` family of methods.
1222 pub struct SemanticsScope<'a> {
1223 pub db: &'a dyn HirDatabase,
1228 impl<'a> SemanticsScope<'a> {
1229 pub fn module(&self) -> Option<Module> {
1230 Some(Module { id: self.resolver.module()? })
1233 pub fn krate(&self) -> Option<Crate> {
1234 Some(Crate { id: self.resolver.krate()? })
1237 pub(crate) fn resolver(&self) -> &Resolver {
1241 /// Note: `FxHashSet<TraitId>` should be treated as an opaque type, passed into `Type
1242 pub fn visible_traits(&self) -> FxHashSet<TraitId> {
1243 let resolver = &self.resolver;
1244 resolver.traits_in_scope(self.db.upcast())
1247 pub fn process_all_names(&self, f: &mut dyn FnMut(Name, ScopeDef)) {
1248 let scope = self.resolver.names_in_scope(self.db.upcast());
1249 for (name, entries) in scope {
1250 for entry in entries {
1251 let def = match entry {
1252 resolver::ScopeDef::ModuleDef(it) => ScopeDef::ModuleDef(it.into()),
1253 resolver::ScopeDef::MacroDef(it) => ScopeDef::MacroDef(it.into()),
1254 resolver::ScopeDef::Unknown => ScopeDef::Unknown,
1255 resolver::ScopeDef::ImplSelfType(it) => ScopeDef::ImplSelfType(it.into()),
1256 resolver::ScopeDef::AdtSelfType(it) => ScopeDef::AdtSelfType(it.into()),
1257 resolver::ScopeDef::GenericParam(id) => ScopeDef::GenericParam(id.into()),
1258 resolver::ScopeDef::Local(pat_id) => {
1259 let parent = self.resolver.body_owner().unwrap();
1260 ScopeDef::Local(Local { parent, pat_id })
1262 resolver::ScopeDef::Label(label_id) => {
1263 let parent = self.resolver.body_owner().unwrap();
1264 ScopeDef::Label(Label { parent, label_id })
1267 f(name.clone(), def)
1272 /// Resolve a path as-if it was written at the given scope. This is
1273 /// necessary a heuristic, as it doesn't take hygiene into account.
1274 pub fn speculative_resolve(&self, path: &ast::Path) -> Option<PathResolution> {
1275 let ctx = body::LowerCtx::new(self.db.upcast(), self.file_id);
1276 let path = Path::from_src(path.clone(), &ctx)?;
1277 resolve_hir_path(self.db, &self.resolver, &path)
1280 /// Iterates over associated types that may be specified after the given path (using
1281 /// `Ty::Assoc` syntax).
1282 pub fn assoc_type_shorthand_candidates<R>(
1284 resolution: &PathResolution,
1285 mut cb: impl FnMut(&Name, TypeAlias) -> Option<R>,
1287 let def = self.resolver.generic_def()?;
1288 hir_ty::associated_type_shorthand_candidates(
1291 resolution.in_type_ns()?,
1292 |name, _, id| cb(name, id.into()),