1 //! See `Semantics`.
2
3 mod source_to_def;
4
5 use std::{cell::RefCell, fmt, iter, mem, ops};
6
7 use base_db::{FileId, FileRange};
8 use either::Either;
9 use hir_def::{
10 hir::Expr,
11 lower::LowerCtx,
12 macro_id_to_def_id,
13 nameres::MacroSubNs,
14 resolver::{self, HasResolver, Resolver, TypeNs},
15 type_ref::Mutability,
16 AsMacroCall, DefWithBodyId, FieldId, FunctionId, MacroId, TraitId, VariantId,
17 };
18 use hir_expand::{
19 db::ExpandDatabase,
20 name::{known, AsName},
21 ExpansionInfo, MacroCallId,
22 };
23 use itertools::Itertools;
24 use rustc_hash::{FxHashMap, FxHashSet};
25 use smallvec::{smallvec, SmallVec};
26 use syntax::{
27 algo::skip_trivia_token,
28 ast::{self, HasAttrs as _, HasGenericParams, HasLoopBody},
29 match_ast, AstNode, Direction, SyntaxKind, SyntaxNode, SyntaxNodePtr, SyntaxToken, TextSize,
30 };
31
32 use crate::{
33 db::HirDatabase,
34 semantics::source_to_def::{ChildContainer, SourceToDefCache, SourceToDefCtx},
35 source_analyzer::{resolve_hir_path, SourceAnalyzer},
36 Access, Adjust, Adjustment, AutoBorrow, BindingMode, BuiltinAttr, Callable, ConstParam, Crate,
37 DeriveHelper, Field, Function, HasSource, HirFileId, Impl, InFile, Label, LifetimeParam, Local,
38 Macro, Module, ModuleDef, Name, OverloadedDeref, Path, ScopeDef, ToolModule, Trait, Type,
39 TypeAlias, TypeParam, VariantDef,
40 };
41
42 #[derive(Debug, Clone, PartialEq, Eq)]
43 pub enum PathResolution {
44 /// An item
45 Def(ModuleDef),
46 /// A local binding (only value namespace)
47 Local(Local),
48 /// A type parameter
49 TypeParam(TypeParam),
50 /// A const parameter
51 ConstParam(ConstParam),
52 SelfType(Impl),
53 BuiltinAttr(BuiltinAttr),
54 ToolModule(ToolModule),
55 DeriveHelper(DeriveHelper),
56 }
57
58 impl PathResolution {
in_type_ns(&self) -> Option<TypeNs>59 pub(crate) fn in_type_ns(&self) -> Option<TypeNs> {
60 match self {
61 PathResolution::Def(ModuleDef::Adt(adt)) => Some(TypeNs::AdtId((*adt).into())),
62 PathResolution::Def(ModuleDef::BuiltinType(builtin)) => {
63 Some(TypeNs::BuiltinType((*builtin).into()))
64 }
65 PathResolution::Def(
66 ModuleDef::Const(_)
67 | ModuleDef::Variant(_)
68 | ModuleDef::Macro(_)
69 | ModuleDef::Function(_)
70 | ModuleDef::Module(_)
71 | ModuleDef::Static(_)
72 | ModuleDef::Trait(_)
73 | ModuleDef::TraitAlias(_),
74 ) => None,
75 PathResolution::Def(ModuleDef::TypeAlias(alias)) => {
76 Some(TypeNs::TypeAliasId((*alias).into()))
77 }
78 PathResolution::BuiltinAttr(_)
79 | PathResolution::ToolModule(_)
80 | PathResolution::Local(_)
81 | PathResolution::DeriveHelper(_)
82 | PathResolution::ConstParam(_) => None,
83 PathResolution::TypeParam(param) => Some(TypeNs::GenericParam((*param).into())),
84 PathResolution::SelfType(impl_def) => Some(TypeNs::SelfType((*impl_def).into())),
85 }
86 }
87 }
88
89 #[derive(Debug)]
90 pub struct TypeInfo {
91 /// The original type of the expression or pattern.
92 pub original: Type,
93 /// The adjusted type, if an adjustment happened.
94 pub adjusted: Option<Type>,
95 }
96
97 impl TypeInfo {
original(self) -> Type98 pub fn original(self) -> Type {
99 self.original
100 }
101
has_adjustment(&self) -> bool102 pub fn has_adjustment(&self) -> bool {
103 self.adjusted.is_some()
104 }
105
106 /// The adjusted type, or the original in case no adjustments occurred.
adjusted(self) -> Type107 pub fn adjusted(self) -> Type {
108 self.adjusted.unwrap_or(self.original)
109 }
110 }
111
112 /// Primary API to get semantic information, like types, from syntax trees.
113 pub struct Semantics<'db, DB> {
114 pub db: &'db DB,
115 imp: SemanticsImpl<'db>,
116 }
117
118 pub struct SemanticsImpl<'db> {
119 pub db: &'db dyn HirDatabase,
120 s2d_cache: RefCell<SourceToDefCache>,
121 expansion_info_cache: RefCell<FxHashMap<HirFileId, Option<ExpansionInfo>>>,
122 // Rootnode to HirFileId cache
123 cache: RefCell<FxHashMap<SyntaxNode, HirFileId>>,
124 // MacroCall to its expansion's HirFileId cache
125 macro_call_cache: RefCell<FxHashMap<InFile<ast::MacroCall>, HirFileId>>,
126 }
127
128 impl<DB> fmt::Debug for Semantics<'_, DB> {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result129 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
130 write!(f, "Semantics {{ ... }}")
131 }
132 }
133
134 impl<'db, DB: HirDatabase> Semantics<'db, DB> {
new(db: &DB) -> Semantics<'_, DB>135 pub fn new(db: &DB) -> Semantics<'_, DB> {
136 let impl_ = SemanticsImpl::new(db);
137 Semantics { db, imp: impl_ }
138 }
139
parse(&self, file_id: FileId) -> ast::SourceFile140 pub fn parse(&self, file_id: FileId) -> ast::SourceFile {
141 self.imp.parse(file_id)
142 }
143
parse_or_expand(&self, file_id: HirFileId) -> SyntaxNode144 pub fn parse_or_expand(&self, file_id: HirFileId) -> SyntaxNode {
145 self.imp.parse_or_expand(file_id)
146 }
147
expand(&self, macro_call: &ast::MacroCall) -> Option<SyntaxNode>148 pub fn expand(&self, macro_call: &ast::MacroCall) -> Option<SyntaxNode> {
149 self.imp.expand(macro_call)
150 }
151
152 /// If `item` has an attribute macro attached to it, expands it.
expand_attr_macro(&self, item: &ast::Item) -> Option<SyntaxNode>153 pub fn expand_attr_macro(&self, item: &ast::Item) -> Option<SyntaxNode> {
154 self.imp.expand_attr_macro(item)
155 }
156
expand_derive_as_pseudo_attr_macro(&self, attr: &ast::Attr) -> Option<SyntaxNode>157 pub fn expand_derive_as_pseudo_attr_macro(&self, attr: &ast::Attr) -> Option<SyntaxNode> {
158 self.imp.expand_derive_as_pseudo_attr_macro(attr)
159 }
160
resolve_derive_macro(&self, derive: &ast::Attr) -> Option<Vec<Option<Macro>>>161 pub fn resolve_derive_macro(&self, derive: &ast::Attr) -> Option<Vec<Option<Macro>>> {
162 self.imp.resolve_derive_macro(derive)
163 }
164
expand_derive_macro(&self, derive: &ast::Attr) -> Option<Vec<SyntaxNode>>165 pub fn expand_derive_macro(&self, derive: &ast::Attr) -> Option<Vec<SyntaxNode>> {
166 self.imp.expand_derive_macro(derive)
167 }
168
is_attr_macro_call(&self, item: &ast::Item) -> bool169 pub fn is_attr_macro_call(&self, item: &ast::Item) -> bool {
170 self.imp.is_attr_macro_call(item)
171 }
172
is_derive_annotated(&self, item: &ast::Adt) -> bool173 pub fn is_derive_annotated(&self, item: &ast::Adt) -> bool {
174 self.imp.is_derive_annotated(item)
175 }
176
speculative_expand( &self, actual_macro_call: &ast::MacroCall, speculative_args: &ast::TokenTree, token_to_map: SyntaxToken, ) -> Option<(SyntaxNode, SyntaxToken)>177 pub fn speculative_expand(
178 &self,
179 actual_macro_call: &ast::MacroCall,
180 speculative_args: &ast::TokenTree,
181 token_to_map: SyntaxToken,
182 ) -> Option<(SyntaxNode, SyntaxToken)> {
183 self.imp.speculative_expand(actual_macro_call, speculative_args, token_to_map)
184 }
185
speculative_expand_attr_macro( &self, actual_macro_call: &ast::Item, speculative_args: &ast::Item, token_to_map: SyntaxToken, ) -> Option<(SyntaxNode, SyntaxToken)>186 pub fn speculative_expand_attr_macro(
187 &self,
188 actual_macro_call: &ast::Item,
189 speculative_args: &ast::Item,
190 token_to_map: SyntaxToken,
191 ) -> Option<(SyntaxNode, SyntaxToken)> {
192 self.imp.speculative_expand_attr(actual_macro_call, speculative_args, token_to_map)
193 }
194
speculative_expand_derive_as_pseudo_attr_macro( &self, actual_macro_call: &ast::Attr, speculative_args: &ast::Attr, token_to_map: SyntaxToken, ) -> Option<(SyntaxNode, SyntaxToken)>195 pub fn speculative_expand_derive_as_pseudo_attr_macro(
196 &self,
197 actual_macro_call: &ast::Attr,
198 speculative_args: &ast::Attr,
199 token_to_map: SyntaxToken,
200 ) -> Option<(SyntaxNode, SyntaxToken)> {
201 self.imp.speculative_expand_derive_as_pseudo_attr_macro(
202 actual_macro_call,
203 speculative_args,
204 token_to_map,
205 )
206 }
207
208 /// Descend the token into macrocalls to its first mapped counterpart.
descend_into_macros_single(&self, token: SyntaxToken) -> SyntaxToken209 pub fn descend_into_macros_single(&self, token: SyntaxToken) -> SyntaxToken {
210 self.imp.descend_into_macros_single(token)
211 }
212
213 /// Descend the token into macrocalls to all its mapped counterparts.
descend_into_macros(&self, token: SyntaxToken) -> SmallVec<[SyntaxToken; 1]>214 pub fn descend_into_macros(&self, token: SyntaxToken) -> SmallVec<[SyntaxToken; 1]> {
215 self.imp.descend_into_macros(token)
216 }
217
218 /// Descend the token into macrocalls to all its mapped counterparts that have the same text as the input token.
219 ///
220 /// Returns the original non descended token if none of the mapped counterparts have the same text.
descend_into_macros_with_same_text( &self, token: SyntaxToken, ) -> SmallVec<[SyntaxToken; 1]>221 pub fn descend_into_macros_with_same_text(
222 &self,
223 token: SyntaxToken,
224 ) -> SmallVec<[SyntaxToken; 1]> {
225 self.imp.descend_into_macros_with_same_text(token)
226 }
227
descend_into_macros_with_kind_preference(&self, token: SyntaxToken) -> SyntaxToken228 pub fn descend_into_macros_with_kind_preference(&self, token: SyntaxToken) -> SyntaxToken {
229 self.imp.descend_into_macros_with_kind_preference(token)
230 }
231
232 /// Maps a node down by mapping its first and last token down.
descend_node_into_attributes<N: AstNode>(&self, node: N) -> SmallVec<[N; 1]>233 pub fn descend_node_into_attributes<N: AstNode>(&self, node: N) -> SmallVec<[N; 1]> {
234 self.imp.descend_node_into_attributes(node)
235 }
236
237 /// Search for a definition's source and cache its syntax tree
source<Def: HasSource>(&self, def: Def) -> Option<InFile<Def::Ast>> where Def::Ast: AstNode,238 pub fn source<Def: HasSource>(&self, def: Def) -> Option<InFile<Def::Ast>>
239 where
240 Def::Ast: AstNode,
241 {
242 self.imp.source(def)
243 }
244
hir_file_for(&self, syntax_node: &SyntaxNode) -> HirFileId245 pub fn hir_file_for(&self, syntax_node: &SyntaxNode) -> HirFileId {
246 self.imp.find_file(syntax_node).file_id
247 }
248
249 /// Attempts to map the node out of macro expanded files returning the original file range.
250 /// If upmapping is not possible, this will fall back to the range of the macro call of the
251 /// macro file the node resides in.
original_range(&self, node: &SyntaxNode) -> FileRange252 pub fn original_range(&self, node: &SyntaxNode) -> FileRange {
253 self.imp.original_range(node)
254 }
255
256 /// Attempts to map the node out of macro expanded files returning the original file range.
original_range_opt(&self, node: &SyntaxNode) -> Option<FileRange>257 pub fn original_range_opt(&self, node: &SyntaxNode) -> Option<FileRange> {
258 self.imp.original_range_opt(node)
259 }
260
261 /// Attempts to map the node out of macro expanded files.
262 /// This only work for attribute expansions, as other ones do not have nodes as input.
original_ast_node<N: AstNode>(&self, node: N) -> Option<N>263 pub fn original_ast_node<N: AstNode>(&self, node: N) -> Option<N> {
264 self.imp.original_ast_node(node)
265 }
266 /// Attempts to map the node out of macro expanded files.
267 /// This only work for attribute expansions, as other ones do not have nodes as input.
original_syntax_node(&self, node: &SyntaxNode) -> Option<SyntaxNode>268 pub fn original_syntax_node(&self, node: &SyntaxNode) -> Option<SyntaxNode> {
269 self.imp.original_syntax_node(node)
270 }
271
diagnostics_display_range(&self, diagnostics: InFile<SyntaxNodePtr>) -> FileRange272 pub fn diagnostics_display_range(&self, diagnostics: InFile<SyntaxNodePtr>) -> FileRange {
273 self.imp.diagnostics_display_range(diagnostics)
274 }
275
token_ancestors_with_macros( &self, token: SyntaxToken, ) -> impl Iterator<Item = SyntaxNode> + '_276 pub fn token_ancestors_with_macros(
277 &self,
278 token: SyntaxToken,
279 ) -> impl Iterator<Item = SyntaxNode> + '_ {
280 token.parent().into_iter().flat_map(move |it| self.ancestors_with_macros(it))
281 }
282
283 /// Iterates the ancestors of the given node, climbing up macro expansions while doing so.
ancestors_with_macros(&self, node: SyntaxNode) -> impl Iterator<Item = SyntaxNode> + '_284 pub fn ancestors_with_macros(&self, node: SyntaxNode) -> impl Iterator<Item = SyntaxNode> + '_ {
285 self.imp.ancestors_with_macros(node)
286 }
287
ancestors_at_offset_with_macros( &self, node: &SyntaxNode, offset: TextSize, ) -> impl Iterator<Item = SyntaxNode> + '_288 pub fn ancestors_at_offset_with_macros(
289 &self,
290 node: &SyntaxNode,
291 offset: TextSize,
292 ) -> impl Iterator<Item = SyntaxNode> + '_ {
293 self.imp.ancestors_at_offset_with_macros(node, offset)
294 }
295
296 /// Find an AstNode by offset inside SyntaxNode, if it is inside *Macrofile*,
297 /// search up until it is of the target AstNode type
find_node_at_offset_with_macros<N: AstNode>( &self, node: &SyntaxNode, offset: TextSize, ) -> Option<N>298 pub fn find_node_at_offset_with_macros<N: AstNode>(
299 &self,
300 node: &SyntaxNode,
301 offset: TextSize,
302 ) -> Option<N> {
303 self.imp.ancestors_at_offset_with_macros(node, offset).find_map(N::cast)
304 }
305
306 /// Find an AstNode by offset inside SyntaxNode, if it is inside *MacroCall*,
307 /// descend it and find again
find_node_at_offset_with_descend<N: AstNode>( &self, node: &SyntaxNode, offset: TextSize, ) -> Option<N>308 pub fn find_node_at_offset_with_descend<N: AstNode>(
309 &self,
310 node: &SyntaxNode,
311 offset: TextSize,
312 ) -> Option<N> {
313 self.imp.descend_node_at_offset(node, offset).flatten().find_map(N::cast)
314 }
315
316 /// Find an AstNode by offset inside SyntaxNode, if it is inside *MacroCall*,
317 /// descend it and find again
find_nodes_at_offset_with_descend<'slf, N: AstNode + 'slf>( &'slf self, node: &SyntaxNode, offset: TextSize, ) -> impl Iterator<Item = N> + 'slf318 pub fn find_nodes_at_offset_with_descend<'slf, N: AstNode + 'slf>(
319 &'slf self,
320 node: &SyntaxNode,
321 offset: TextSize,
322 ) -> impl Iterator<Item = N> + 'slf {
323 self.imp.descend_node_at_offset(node, offset).filter_map(|mut it| it.find_map(N::cast))
324 }
325
resolve_lifetime_param(&self, lifetime: &ast::Lifetime) -> Option<LifetimeParam>326 pub fn resolve_lifetime_param(&self, lifetime: &ast::Lifetime) -> Option<LifetimeParam> {
327 self.imp.resolve_lifetime_param(lifetime)
328 }
329
resolve_label(&self, lifetime: &ast::Lifetime) -> Option<Label>330 pub fn resolve_label(&self, lifetime: &ast::Lifetime) -> Option<Label> {
331 self.imp.resolve_label(lifetime)
332 }
333
resolve_type(&self, ty: &ast::Type) -> Option<Type>334 pub fn resolve_type(&self, ty: &ast::Type) -> Option<Type> {
335 self.imp.resolve_type(ty)
336 }
337
resolve_trait(&self, trait_: &ast::Path) -> Option<Trait>338 pub fn resolve_trait(&self, trait_: &ast::Path) -> Option<Trait> {
339 self.imp.resolve_trait(trait_)
340 }
341
expr_adjustments(&self, expr: &ast::Expr) -> Option<Vec<Adjustment>>342 pub fn expr_adjustments(&self, expr: &ast::Expr) -> Option<Vec<Adjustment>> {
343 self.imp.expr_adjustments(expr)
344 }
345
type_of_expr(&self, expr: &ast::Expr) -> Option<TypeInfo>346 pub fn type_of_expr(&self, expr: &ast::Expr) -> Option<TypeInfo> {
347 self.imp.type_of_expr(expr)
348 }
349
type_of_pat(&self, pat: &ast::Pat) -> Option<TypeInfo>350 pub fn type_of_pat(&self, pat: &ast::Pat) -> Option<TypeInfo> {
351 self.imp.type_of_pat(pat)
352 }
353
354 /// It also includes the changes that binding mode makes in the type. For example in
355 /// `let ref x @ Some(_) = None` the result of `type_of_pat` is `Option<T>` but the result
356 /// of this function is `&mut Option<T>`
type_of_binding_in_pat(&self, pat: &ast::IdentPat) -> Option<Type>357 pub fn type_of_binding_in_pat(&self, pat: &ast::IdentPat) -> Option<Type> {
358 self.imp.type_of_binding_in_pat(pat)
359 }
360
type_of_self(&self, param: &ast::SelfParam) -> Option<Type>361 pub fn type_of_self(&self, param: &ast::SelfParam) -> Option<Type> {
362 self.imp.type_of_self(param)
363 }
364
pattern_adjustments(&self, pat: &ast::Pat) -> SmallVec<[Type; 1]>365 pub fn pattern_adjustments(&self, pat: &ast::Pat) -> SmallVec<[Type; 1]> {
366 self.imp.pattern_adjustments(pat)
367 }
368
binding_mode_of_pat(&self, pat: &ast::IdentPat) -> Option<BindingMode>369 pub fn binding_mode_of_pat(&self, pat: &ast::IdentPat) -> Option<BindingMode> {
370 self.imp.binding_mode_of_pat(pat)
371 }
372
resolve_method_call(&self, call: &ast::MethodCallExpr) -> Option<Function>373 pub fn resolve_method_call(&self, call: &ast::MethodCallExpr) -> Option<Function> {
374 self.imp.resolve_method_call(call).map(Function::from)
375 }
376
377 /// Attempts to resolve this call expression as a method call falling back to resolving it as a field.
resolve_method_call_field_fallback( &self, call: &ast::MethodCallExpr, ) -> Option<Either<Function, Field>>378 pub fn resolve_method_call_field_fallback(
379 &self,
380 call: &ast::MethodCallExpr,
381 ) -> Option<Either<Function, Field>> {
382 self.imp
383 .resolve_method_call_fallback(call)
384 .map(|it| it.map_left(Function::from).map_right(Field::from))
385 }
386
resolve_await_to_poll(&self, await_expr: &ast::AwaitExpr) -> Option<Function>387 pub fn resolve_await_to_poll(&self, await_expr: &ast::AwaitExpr) -> Option<Function> {
388 self.imp.resolve_await_to_poll(await_expr).map(Function::from)
389 }
390
resolve_prefix_expr(&self, prefix_expr: &ast::PrefixExpr) -> Option<Function>391 pub fn resolve_prefix_expr(&self, prefix_expr: &ast::PrefixExpr) -> Option<Function> {
392 self.imp.resolve_prefix_expr(prefix_expr).map(Function::from)
393 }
394
resolve_index_expr(&self, index_expr: &ast::IndexExpr) -> Option<Function>395 pub fn resolve_index_expr(&self, index_expr: &ast::IndexExpr) -> Option<Function> {
396 self.imp.resolve_index_expr(index_expr).map(Function::from)
397 }
398
resolve_bin_expr(&self, bin_expr: &ast::BinExpr) -> Option<Function>399 pub fn resolve_bin_expr(&self, bin_expr: &ast::BinExpr) -> Option<Function> {
400 self.imp.resolve_bin_expr(bin_expr).map(Function::from)
401 }
402
resolve_try_expr(&self, try_expr: &ast::TryExpr) -> Option<Function>403 pub fn resolve_try_expr(&self, try_expr: &ast::TryExpr) -> Option<Function> {
404 self.imp.resolve_try_expr(try_expr).map(Function::from)
405 }
406
resolve_method_call_as_callable(&self, call: &ast::MethodCallExpr) -> Option<Callable>407 pub fn resolve_method_call_as_callable(&self, call: &ast::MethodCallExpr) -> Option<Callable> {
408 self.imp.resolve_method_call_as_callable(call)
409 }
410
resolve_field(&self, field: &ast::FieldExpr) -> Option<Field>411 pub fn resolve_field(&self, field: &ast::FieldExpr) -> Option<Field> {
412 self.imp.resolve_field(field)
413 }
414
resolve_record_field( &self, field: &ast::RecordExprField, ) -> Option<(Field, Option<Local>, Type)>415 pub fn resolve_record_field(
416 &self,
417 field: &ast::RecordExprField,
418 ) -> Option<(Field, Option<Local>, Type)> {
419 self.imp.resolve_record_field(field)
420 }
421
resolve_record_pat_field(&self, field: &ast::RecordPatField) -> Option<(Field, Type)>422 pub fn resolve_record_pat_field(&self, field: &ast::RecordPatField) -> Option<(Field, Type)> {
423 self.imp.resolve_record_pat_field(field)
424 }
425
resolve_macro_call(&self, macro_call: &ast::MacroCall) -> Option<Macro>426 pub fn resolve_macro_call(&self, macro_call: &ast::MacroCall) -> Option<Macro> {
427 self.imp.resolve_macro_call(macro_call)
428 }
429
is_unsafe_macro_call(&self, macro_call: &ast::MacroCall) -> bool430 pub fn is_unsafe_macro_call(&self, macro_call: &ast::MacroCall) -> bool {
431 self.imp.is_unsafe_macro_call(macro_call)
432 }
433
resolve_attr_macro_call(&self, item: &ast::Item) -> Option<Macro>434 pub fn resolve_attr_macro_call(&self, item: &ast::Item) -> Option<Macro> {
435 self.imp.resolve_attr_macro_call(item)
436 }
437
resolve_path(&self, path: &ast::Path) -> Option<PathResolution>438 pub fn resolve_path(&self, path: &ast::Path) -> Option<PathResolution> {
439 self.imp.resolve_path(path)
440 }
441
resolve_extern_crate(&self, extern_crate: &ast::ExternCrate) -> Option<Crate>442 pub fn resolve_extern_crate(&self, extern_crate: &ast::ExternCrate) -> Option<Crate> {
443 self.imp.resolve_extern_crate(extern_crate)
444 }
445
resolve_variant(&self, record_lit: ast::RecordExpr) -> Option<VariantDef>446 pub fn resolve_variant(&self, record_lit: ast::RecordExpr) -> Option<VariantDef> {
447 self.imp.resolve_variant(record_lit).map(VariantDef::from)
448 }
449
resolve_bind_pat_to_const(&self, pat: &ast::IdentPat) -> Option<ModuleDef>450 pub fn resolve_bind_pat_to_const(&self, pat: &ast::IdentPat) -> Option<ModuleDef> {
451 self.imp.resolve_bind_pat_to_const(pat)
452 }
453
record_literal_missing_fields(&self, literal: &ast::RecordExpr) -> Vec<(Field, Type)>454 pub fn record_literal_missing_fields(&self, literal: &ast::RecordExpr) -> Vec<(Field, Type)> {
455 self.imp.record_literal_missing_fields(literal)
456 }
457
record_pattern_missing_fields(&self, pattern: &ast::RecordPat) -> Vec<(Field, Type)>458 pub fn record_pattern_missing_fields(&self, pattern: &ast::RecordPat) -> Vec<(Field, Type)> {
459 self.imp.record_pattern_missing_fields(pattern)
460 }
461
to_def<T: ToDef>(&self, src: &T) -> Option<T::Def>462 pub fn to_def<T: ToDef>(&self, src: &T) -> Option<T::Def> {
463 self.imp.to_def(src)
464 }
465
to_module_def(&self, file: FileId) -> Option<Module>466 pub fn to_module_def(&self, file: FileId) -> Option<Module> {
467 self.imp.to_module_def(file).next()
468 }
469
to_module_defs(&self, file: FileId) -> impl Iterator<Item = Module>470 pub fn to_module_defs(&self, file: FileId) -> impl Iterator<Item = Module> {
471 self.imp.to_module_def(file)
472 }
473
scope(&self, node: &SyntaxNode) -> Option<SemanticsScope<'db>>474 pub fn scope(&self, node: &SyntaxNode) -> Option<SemanticsScope<'db>> {
475 self.imp.scope(node)
476 }
477
scope_at_offset( &self, node: &SyntaxNode, offset: TextSize, ) -> Option<SemanticsScope<'db>>478 pub fn scope_at_offset(
479 &self,
480 node: &SyntaxNode,
481 offset: TextSize,
482 ) -> Option<SemanticsScope<'db>> {
483 self.imp.scope_at_offset(node, offset)
484 }
485
assert_contains_node(&self, node: &SyntaxNode)486 pub fn assert_contains_node(&self, node: &SyntaxNode) {
487 self.imp.assert_contains_node(node)
488 }
489
is_unsafe_method_call(&self, method_call_expr: &ast::MethodCallExpr) -> bool490 pub fn is_unsafe_method_call(&self, method_call_expr: &ast::MethodCallExpr) -> bool {
491 self.imp.is_unsafe_method_call(method_call_expr)
492 }
493
is_unsafe_ref_expr(&self, ref_expr: &ast::RefExpr) -> bool494 pub fn is_unsafe_ref_expr(&self, ref_expr: &ast::RefExpr) -> bool {
495 self.imp.is_unsafe_ref_expr(ref_expr)
496 }
497
is_unsafe_ident_pat(&self, ident_pat: &ast::IdentPat) -> bool498 pub fn is_unsafe_ident_pat(&self, ident_pat: &ast::IdentPat) -> bool {
499 self.imp.is_unsafe_ident_pat(ident_pat)
500 }
501
502 /// Returns `true` if the `node` is inside an `unsafe` context.
is_inside_unsafe(&self, expr: &ast::Expr) -> bool503 pub fn is_inside_unsafe(&self, expr: &ast::Expr) -> bool {
504 self.imp.is_inside_unsafe(expr)
505 }
506 }
507
508 impl<'db> SemanticsImpl<'db> {
new(db: &'db dyn HirDatabase) -> Self509 fn new(db: &'db dyn HirDatabase) -> Self {
510 SemanticsImpl {
511 db,
512 s2d_cache: Default::default(),
513 cache: Default::default(),
514 expansion_info_cache: Default::default(),
515 macro_call_cache: Default::default(),
516 }
517 }
518
parse(&self, file_id: FileId) -> ast::SourceFile519 fn parse(&self, file_id: FileId) -> ast::SourceFile {
520 let tree = self.db.parse(file_id).tree();
521 self.cache(tree.syntax().clone(), file_id.into());
522 tree
523 }
524
parse_or_expand(&self, file_id: HirFileId) -> SyntaxNode525 fn parse_or_expand(&self, file_id: HirFileId) -> SyntaxNode {
526 let node = self.db.parse_or_expand(file_id);
527 self.cache(node.clone(), file_id);
528 node
529 }
530
expand(&self, macro_call: &ast::MacroCall) -> Option<SyntaxNode>531 fn expand(&self, macro_call: &ast::MacroCall) -> Option<SyntaxNode> {
532 let sa = self.analyze_no_infer(macro_call.syntax())?;
533 let file_id = sa.expand(self.db, InFile::new(sa.file_id, macro_call))?;
534 let node = self.parse_or_expand(file_id);
535 Some(node)
536 }
537
expand_attr_macro(&self, item: &ast::Item) -> Option<SyntaxNode>538 fn expand_attr_macro(&self, item: &ast::Item) -> Option<SyntaxNode> {
539 let src = self.wrap_node_infile(item.clone());
540 let macro_call_id = self.with_ctx(|ctx| ctx.item_to_macro_call(src))?;
541 Some(self.parse_or_expand(macro_call_id.as_file()))
542 }
543
expand_derive_as_pseudo_attr_macro(&self, attr: &ast::Attr) -> Option<SyntaxNode>544 fn expand_derive_as_pseudo_attr_macro(&self, attr: &ast::Attr) -> Option<SyntaxNode> {
545 let adt = attr.syntax().parent().and_then(ast::Adt::cast)?;
546 let src = self.wrap_node_infile(attr.clone());
547 let call_id = self.with_ctx(|ctx| {
548 ctx.attr_to_derive_macro_call(src.with_value(&adt), src).map(|(_, it, _)| it)
549 })?;
550 Some(self.parse_or_expand(call_id.as_file()))
551 }
552
resolve_derive_macro(&self, attr: &ast::Attr) -> Option<Vec<Option<Macro>>>553 fn resolve_derive_macro(&self, attr: &ast::Attr) -> Option<Vec<Option<Macro>>> {
554 let calls = self.derive_macro_calls(attr)?;
555 self.with_ctx(|ctx| {
556 Some(
557 calls
558 .into_iter()
559 .map(|call| {
560 macro_call_to_macro_id(ctx, self.db.upcast(), call?).map(|id| Macro { id })
561 })
562 .collect(),
563 )
564 })
565 }
566
expand_derive_macro(&self, attr: &ast::Attr) -> Option<Vec<SyntaxNode>>567 fn expand_derive_macro(&self, attr: &ast::Attr) -> Option<Vec<SyntaxNode>> {
568 let res: Vec<_> = self
569 .derive_macro_calls(attr)?
570 .into_iter()
571 .flat_map(|call| {
572 let file_id = call?.as_file();
573 let node = self.db.parse_or_expand(file_id);
574 self.cache(node.clone(), file_id);
575 Some(node)
576 })
577 .collect();
578 Some(res)
579 }
580
derive_macro_calls(&self, attr: &ast::Attr) -> Option<Vec<Option<MacroCallId>>>581 fn derive_macro_calls(&self, attr: &ast::Attr) -> Option<Vec<Option<MacroCallId>>> {
582 let adt = attr.syntax().parent().and_then(ast::Adt::cast)?;
583 let file_id = self.find_file(adt.syntax()).file_id;
584 let adt = InFile::new(file_id, &adt);
585 let src = InFile::new(file_id, attr.clone());
586 self.with_ctx(|ctx| {
587 let (.., res) = ctx.attr_to_derive_macro_call(adt, src)?;
588 Some(res.to_vec())
589 })
590 }
591
is_derive_annotated(&self, adt: &ast::Adt) -> bool592 fn is_derive_annotated(&self, adt: &ast::Adt) -> bool {
593 let file_id = self.find_file(adt.syntax()).file_id;
594 let adt = InFile::new(file_id, adt);
595 self.with_ctx(|ctx| ctx.has_derives(adt))
596 }
597
is_attr_macro_call(&self, item: &ast::Item) -> bool598 fn is_attr_macro_call(&self, item: &ast::Item) -> bool {
599 let file_id = self.find_file(item.syntax()).file_id;
600 let src = InFile::new(file_id, item.clone());
601 self.with_ctx(|ctx| ctx.item_to_macro_call(src).is_some())
602 }
603
speculative_expand( &self, actual_macro_call: &ast::MacroCall, speculative_args: &ast::TokenTree, token_to_map: SyntaxToken, ) -> Option<(SyntaxNode, SyntaxToken)>604 fn speculative_expand(
605 &self,
606 actual_macro_call: &ast::MacroCall,
607 speculative_args: &ast::TokenTree,
608 token_to_map: SyntaxToken,
609 ) -> Option<(SyntaxNode, SyntaxToken)> {
610 let SourceAnalyzer { file_id, resolver, .. } =
611 self.analyze_no_infer(actual_macro_call.syntax())?;
612 let macro_call = InFile::new(file_id, actual_macro_call);
613 let krate = resolver.krate();
614 let macro_call_id = macro_call.as_call_id(self.db.upcast(), krate, |path| {
615 resolver
616 .resolve_path_as_macro(self.db.upcast(), &path, Some(MacroSubNs::Bang))
617 .map(|it| macro_id_to_def_id(self.db.upcast(), it))
618 })?;
619 hir_expand::db::expand_speculative(
620 self.db.upcast(),
621 macro_call_id,
622 speculative_args.syntax(),
623 token_to_map,
624 )
625 }
626
speculative_expand_attr( &self, actual_macro_call: &ast::Item, speculative_args: &ast::Item, token_to_map: SyntaxToken, ) -> Option<(SyntaxNode, SyntaxToken)>627 fn speculative_expand_attr(
628 &self,
629 actual_macro_call: &ast::Item,
630 speculative_args: &ast::Item,
631 token_to_map: SyntaxToken,
632 ) -> Option<(SyntaxNode, SyntaxToken)> {
633 let macro_call = self.wrap_node_infile(actual_macro_call.clone());
634 let macro_call_id = self.with_ctx(|ctx| ctx.item_to_macro_call(macro_call))?;
635 hir_expand::db::expand_speculative(
636 self.db.upcast(),
637 macro_call_id,
638 speculative_args.syntax(),
639 token_to_map,
640 )
641 }
642
speculative_expand_derive_as_pseudo_attr_macro( &self, actual_macro_call: &ast::Attr, speculative_args: &ast::Attr, token_to_map: SyntaxToken, ) -> Option<(SyntaxNode, SyntaxToken)>643 fn speculative_expand_derive_as_pseudo_attr_macro(
644 &self,
645 actual_macro_call: &ast::Attr,
646 speculative_args: &ast::Attr,
647 token_to_map: SyntaxToken,
648 ) -> Option<(SyntaxNode, SyntaxToken)> {
649 let attr = self.wrap_node_infile(actual_macro_call.clone());
650 let adt = actual_macro_call.syntax().parent().and_then(ast::Adt::cast)?;
651 let macro_call_id = self.with_ctx(|ctx| {
652 ctx.attr_to_derive_macro_call(attr.with_value(&adt), attr).map(|(_, it, _)| it)
653 })?;
654 hir_expand::db::expand_speculative(
655 self.db.upcast(),
656 macro_call_id,
657 speculative_args.syntax(),
658 token_to_map,
659 )
660 }
661
662 // This might not be the correct way to do this, but it works for now
descend_node_into_attributes<N: AstNode>(&self, node: N) -> SmallVec<[N; 1]>663 fn descend_node_into_attributes<N: AstNode>(&self, node: N) -> SmallVec<[N; 1]> {
664 let mut res = smallvec![];
665 let tokens = (|| {
666 let first = skip_trivia_token(node.syntax().first_token()?, Direction::Next)?;
667 let last = skip_trivia_token(node.syntax().last_token()?, Direction::Prev)?;
668 Some((first, last))
669 })();
670 let (first, last) = match tokens {
671 Some(it) => it,
672 None => return res,
673 };
674
675 if first == last {
676 self.descend_into_macros_impl(first, &mut |InFile { value, .. }| {
677 if let Some(node) = value.parent_ancestors().find_map(N::cast) {
678 res.push(node)
679 }
680 false
681 });
682 } else {
683 // Descend first and last token, then zip them to look for the node they belong to
684 let mut scratch: SmallVec<[_; 1]> = smallvec![];
685 self.descend_into_macros_impl(first, &mut |token| {
686 scratch.push(token);
687 false
688 });
689
690 let mut scratch = scratch.into_iter();
691 self.descend_into_macros_impl(
692 last,
693 &mut |InFile { value: last, file_id: last_fid }| {
694 if let Some(InFile { value: first, file_id: first_fid }) = scratch.next() {
695 if first_fid == last_fid {
696 if let Some(p) = first.parent() {
697 let range = first.text_range().cover(last.text_range());
698 let node = find_root(&p)
699 .covering_element(range)
700 .ancestors()
701 .take_while(|it| it.text_range() == range)
702 .find_map(N::cast);
703 if let Some(node) = node {
704 res.push(node);
705 }
706 }
707 }
708 }
709 false
710 },
711 );
712 }
713 res
714 }
715
descend_into_macros(&self, token: SyntaxToken) -> SmallVec<[SyntaxToken; 1]>716 fn descend_into_macros(&self, token: SyntaxToken) -> SmallVec<[SyntaxToken; 1]> {
717 let mut res = smallvec![];
718 self.descend_into_macros_impl(token, &mut |InFile { value, .. }| {
719 res.push(value);
720 false
721 });
722 res
723 }
724
descend_into_macros_with_same_text(&self, token: SyntaxToken) -> SmallVec<[SyntaxToken; 1]>725 fn descend_into_macros_with_same_text(&self, token: SyntaxToken) -> SmallVec<[SyntaxToken; 1]> {
726 let text = token.text();
727 let mut res = smallvec![];
728 self.descend_into_macros_impl(token.clone(), &mut |InFile { value, .. }| {
729 if value.text() == text {
730 res.push(value);
731 }
732 false
733 });
734 if res.is_empty() {
735 res.push(token);
736 }
737 res
738 }
739
descend_into_macros_with_kind_preference(&self, token: SyntaxToken) -> SyntaxToken740 fn descend_into_macros_with_kind_preference(&self, token: SyntaxToken) -> SyntaxToken {
741 let fetch_kind = |token: &SyntaxToken| match token.parent() {
742 Some(node) => match node.kind() {
743 kind @ (SyntaxKind::NAME | SyntaxKind::NAME_REF) => {
744 node.parent().map_or(kind, |it| it.kind())
745 }
746 _ => token.kind(),
747 },
748 None => token.kind(),
749 };
750 let preferred_kind = fetch_kind(&token);
751 let mut res = None;
752 self.descend_into_macros_impl(token.clone(), &mut |InFile { value, .. }| {
753 if fetch_kind(&value) == preferred_kind {
754 res = Some(value);
755 true
756 } else {
757 if let None = res {
758 res = Some(value)
759 }
760 false
761 }
762 });
763 res.unwrap_or(token)
764 }
765
descend_into_macros_single(&self, token: SyntaxToken) -> SyntaxToken766 fn descend_into_macros_single(&self, token: SyntaxToken) -> SyntaxToken {
767 let mut res = token.clone();
768 self.descend_into_macros_impl(token, &mut |InFile { value, .. }| {
769 res = value;
770 true
771 });
772 res
773 }
774
descend_into_macros_impl( &self, token: SyntaxToken, f: &mut dyn FnMut(InFile<SyntaxToken>) -> bool, )775 fn descend_into_macros_impl(
776 &self,
777 token: SyntaxToken,
778 f: &mut dyn FnMut(InFile<SyntaxToken>) -> bool,
779 ) {
780 let _p = profile::span("descend_into_macros");
781 let parent = match token.parent() {
782 Some(it) => it,
783 None => return,
784 };
785 let sa = match self.analyze_no_infer(&parent) {
786 Some(it) => it,
787 None => return,
788 };
789 let def_map = sa.resolver.def_map();
790
791 let mut stack: SmallVec<[_; 4]> = smallvec![InFile::new(sa.file_id, token)];
792 let mut cache = self.expansion_info_cache.borrow_mut();
793 let mut mcache = self.macro_call_cache.borrow_mut();
794
795 let mut process_expansion_for_token =
796 |stack: &mut SmallVec<_>, macro_file, item, token: InFile<&_>| {
797 let expansion_info = cache
798 .entry(macro_file)
799 .or_insert_with(|| macro_file.expansion_info(self.db.upcast()))
800 .as_ref()?;
801
802 {
803 let InFile { file_id, value } = expansion_info.expanded();
804 self.cache(value, file_id);
805 }
806
807 let mapped_tokens = expansion_info.map_token_down(self.db.upcast(), item, token)?;
808 let len = stack.len();
809
810 // requeue the tokens we got from mapping our current token down
811 stack.extend(mapped_tokens);
812 // if the length changed we have found a mapping for the token
813 (stack.len() != len).then_some(())
814 };
815
816 // Remap the next token in the queue into a macro call its in, if it is not being remapped
817 // either due to not being in a macro-call or because its unused push it into the result vec,
818 // otherwise push the remapped tokens back into the queue as they can potentially be remapped again.
819 while let Some(token) = stack.pop() {
820 self.db.unwind_if_cancelled();
821 let was_not_remapped = (|| {
822 // First expand into attribute invocations
823 let containing_attribute_macro_call = self.with_ctx(|ctx| {
824 token.value.parent_ancestors().filter_map(ast::Item::cast).find_map(|item| {
825 if item.attrs().next().is_none() {
826 // Don't force populate the dyn cache for items that don't have an attribute anyways
827 return None;
828 }
829 Some((ctx.item_to_macro_call(token.with_value(item.clone()))?, item))
830 })
831 });
832 if let Some((call_id, item)) = containing_attribute_macro_call {
833 let file_id = call_id.as_file();
834 return process_expansion_for_token(
835 &mut stack,
836 file_id,
837 Some(item),
838 token.as_ref(),
839 );
840 }
841
842 // Then check for token trees, that means we are either in a function-like macro or
843 // secondary attribute inputs
844 let tt = token.value.parent_ancestors().map_while(ast::TokenTree::cast).last()?;
845 let parent = tt.syntax().parent()?;
846
847 if tt.left_delimiter_token().map_or(false, |it| it == token.value) {
848 return None;
849 }
850 if tt.right_delimiter_token().map_or(false, |it| it == token.value) {
851 return None;
852 }
853
854 if let Some(macro_call) = ast::MacroCall::cast(parent.clone()) {
855 let mcall = token.with_value(macro_call);
856 let file_id = match mcache.get(&mcall) {
857 Some(&it) => it,
858 None => {
859 let it = sa.expand(self.db, mcall.as_ref())?;
860 mcache.insert(mcall, it);
861 it
862 }
863 };
864 process_expansion_for_token(&mut stack, file_id, None, token.as_ref())
865 } else if let Some(meta) = ast::Meta::cast(parent) {
866 // attribute we failed expansion for earlier, this might be a derive invocation
867 // or derive helper attribute
868 let attr = meta.parent_attr()?;
869
870 let adt = if let Some(adt) = attr.syntax().parent().and_then(ast::Adt::cast) {
871 // this might be a derive, or a derive helper on an ADT
872 let derive_call = self.with_ctx(|ctx| {
873 // so try downmapping the token into the pseudo derive expansion
874 // see [hir_expand::builtin_attr_macro] for how the pseudo derive expansion works
875 ctx.attr_to_derive_macro_call(
876 token.with_value(&adt),
877 token.with_value(attr.clone()),
878 )
879 .map(|(_, call_id, _)| call_id)
880 });
881
882 match derive_call {
883 Some(call_id) => {
884 // resolved to a derive
885 let file_id = call_id.as_file();
886 return process_expansion_for_token(
887 &mut stack,
888 file_id,
889 Some(adt.into()),
890 token.as_ref(),
891 );
892 }
893 None => Some(adt),
894 }
895 } else {
896 // Otherwise this could be a derive helper on a variant or field
897 if let Some(field) = attr.syntax().parent().and_then(ast::RecordField::cast)
898 {
899 field.syntax().ancestors().take(4).find_map(ast::Adt::cast)
900 } else if let Some(field) =
901 attr.syntax().parent().and_then(ast::TupleField::cast)
902 {
903 field.syntax().ancestors().take(4).find_map(ast::Adt::cast)
904 } else if let Some(variant) =
905 attr.syntax().parent().and_then(ast::Variant::cast)
906 {
907 variant.syntax().ancestors().nth(2).and_then(ast::Adt::cast)
908 } else {
909 None
910 }
911 }?;
912 if !self.with_ctx(|ctx| ctx.has_derives(InFile::new(token.file_id, &adt))) {
913 return None;
914 }
915 // Not an attribute, nor a derive, so it's either a builtin or a derive helper
916 // Try to resolve to a derive helper and downmap
917 let attr_name = attr.path().and_then(|it| it.as_single_name_ref())?.as_name();
918 let id = self.db.ast_id_map(token.file_id).ast_id(&adt);
919 let helpers =
920 def_map.derive_helpers_in_scope(InFile::new(token.file_id, id))?;
921 let item = Some(adt.into());
922 let mut res = None;
923 for (.., derive) in helpers.iter().filter(|(helper, ..)| *helper == attr_name) {
924 res = res.or(process_expansion_for_token(
925 &mut stack,
926 derive.as_file(),
927 item.clone(),
928 token.as_ref(),
929 ));
930 }
931 res
932 } else {
933 None
934 }
935 })()
936 .is_none();
937
938 if was_not_remapped && f(token) {
939 break;
940 }
941 }
942 }
943
944 // Note this return type is deliberate as [`find_nodes_at_offset_with_descend`] wants to stop
945 // traversing the inner iterator when it finds a node.
946 // The outer iterator is over the tokens descendants
947 // The inner iterator is the ancestors of a descendant
descend_node_at_offset( &self, node: &SyntaxNode, offset: TextSize, ) -> impl Iterator<Item = impl Iterator<Item = SyntaxNode> + '_> + '_948 fn descend_node_at_offset(
949 &self,
950 node: &SyntaxNode,
951 offset: TextSize,
952 ) -> impl Iterator<Item = impl Iterator<Item = SyntaxNode> + '_> + '_ {
953 node.token_at_offset(offset)
954 .map(move |token| self.descend_into_macros(token))
955 .map(|descendants| {
956 descendants.into_iter().map(move |it| self.token_ancestors_with_macros(it))
957 })
958 // re-order the tokens from token_at_offset by returning the ancestors with the smaller first nodes first
959 // See algo::ancestors_at_offset, which uses the same approach
960 .kmerge_by(|left, right| {
961 left.clone()
962 .map(|node| node.text_range().len())
963 .lt(right.clone().map(|node| node.text_range().len()))
964 })
965 }
966
original_range(&self, node: &SyntaxNode) -> FileRange967 fn original_range(&self, node: &SyntaxNode) -> FileRange {
968 let node = self.find_file(node);
969 node.original_file_range(self.db.upcast())
970 }
971
original_range_opt(&self, node: &SyntaxNode) -> Option<FileRange>972 fn original_range_opt(&self, node: &SyntaxNode) -> Option<FileRange> {
973 let node = self.find_file(node);
974 node.original_file_range_opt(self.db.upcast())
975 }
976
original_ast_node<N: AstNode>(&self, node: N) -> Option<N>977 fn original_ast_node<N: AstNode>(&self, node: N) -> Option<N> {
978 self.wrap_node_infile(node).original_ast_node(self.db.upcast()).map(
979 |InFile { file_id, value }| {
980 self.cache(find_root(value.syntax()), file_id);
981 value
982 },
983 )
984 }
985
original_syntax_node(&self, node: &SyntaxNode) -> Option<SyntaxNode>986 fn original_syntax_node(&self, node: &SyntaxNode) -> Option<SyntaxNode> {
987 let InFile { file_id, .. } = self.find_file(node);
988 InFile::new(file_id, node).original_syntax_node(self.db.upcast()).map(
989 |InFile { file_id, value }| {
990 self.cache(find_root(&value), file_id);
991 value
992 },
993 )
994 }
995
diagnostics_display_range(&self, src: InFile<SyntaxNodePtr>) -> FileRange996 fn diagnostics_display_range(&self, src: InFile<SyntaxNodePtr>) -> FileRange {
997 let root = self.parse_or_expand(src.file_id);
998 let node = src.map(|it| it.to_node(&root));
999 node.as_ref().original_file_range(self.db.upcast())
1000 }
1001
token_ancestors_with_macros( &self, token: SyntaxToken, ) -> impl Iterator<Item = SyntaxNode> + Clone + '_1002 fn token_ancestors_with_macros(
1003 &self,
1004 token: SyntaxToken,
1005 ) -> impl Iterator<Item = SyntaxNode> + Clone + '_ {
1006 token.parent().into_iter().flat_map(move |parent| self.ancestors_with_macros(parent))
1007 }
1008
ancestors_with_macros( &self, node: SyntaxNode, ) -> impl Iterator<Item = SyntaxNode> + Clone + '_1009 fn ancestors_with_macros(
1010 &self,
1011 node: SyntaxNode,
1012 ) -> impl Iterator<Item = SyntaxNode> + Clone + '_ {
1013 let node = self.find_file(&node);
1014 let db = self.db.upcast();
1015 iter::successors(Some(node.cloned()), move |&InFile { file_id, ref value }| {
1016 match value.parent() {
1017 Some(parent) => Some(InFile::new(file_id, parent)),
1018 None => {
1019 self.cache(value.clone(), file_id);
1020 file_id.call_node(db)
1021 }
1022 }
1023 })
1024 .map(|it| it.value)
1025 }
1026
ancestors_at_offset_with_macros( &self, node: &SyntaxNode, offset: TextSize, ) -> impl Iterator<Item = SyntaxNode> + '_1027 fn ancestors_at_offset_with_macros(
1028 &self,
1029 node: &SyntaxNode,
1030 offset: TextSize,
1031 ) -> impl Iterator<Item = SyntaxNode> + '_ {
1032 node.token_at_offset(offset)
1033 .map(|token| self.token_ancestors_with_macros(token))
1034 .kmerge_by(|node1, node2| node1.text_range().len() < node2.text_range().len())
1035 }
1036
resolve_lifetime_param(&self, lifetime: &ast::Lifetime) -> Option<LifetimeParam>1037 fn resolve_lifetime_param(&self, lifetime: &ast::Lifetime) -> Option<LifetimeParam> {
1038 let text = lifetime.text();
1039 let lifetime_param = lifetime.syntax().ancestors().find_map(|syn| {
1040 let gpl = ast::AnyHasGenericParams::cast(syn)?.generic_param_list()?;
1041 gpl.lifetime_params()
1042 .find(|tp| tp.lifetime().as_ref().map(|lt| lt.text()).as_ref() == Some(&text))
1043 })?;
1044 let src = self.wrap_node_infile(lifetime_param);
1045 ToDef::to_def(self, src)
1046 }
1047
resolve_label(&self, lifetime: &ast::Lifetime) -> Option<Label>1048 fn resolve_label(&self, lifetime: &ast::Lifetime) -> Option<Label> {
1049 let text = lifetime.text();
1050 let label = lifetime.syntax().ancestors().find_map(|syn| {
1051 let label = match_ast! {
1052 match syn {
1053 ast::ForExpr(it) => it.label(),
1054 ast::WhileExpr(it) => it.label(),
1055 ast::LoopExpr(it) => it.label(),
1056 ast::BlockExpr(it) => it.label(),
1057 _ => None,
1058 }
1059 };
1060 label.filter(|l| {
1061 l.lifetime()
1062 .and_then(|lt| lt.lifetime_ident_token())
1063 .map_or(false, |lt| lt.text() == text)
1064 })
1065 })?;
1066 let src = self.wrap_node_infile(label);
1067 ToDef::to_def(self, src)
1068 }
1069
resolve_type(&self, ty: &ast::Type) -> Option<Type>1070 fn resolve_type(&self, ty: &ast::Type) -> Option<Type> {
1071 let analyze = self.analyze(ty.syntax())?;
1072 let ctx = LowerCtx::with_file_id(self.db.upcast(), analyze.file_id);
1073 let ty = hir_ty::TyLoweringContext::new(
1074 self.db,
1075 &analyze.resolver,
1076 analyze.resolver.module().into(),
1077 )
1078 .lower_ty(&crate::TypeRef::from_ast(&ctx, ty.clone()));
1079 Some(Type::new_with_resolver(self.db, &analyze.resolver, ty))
1080 }
1081
resolve_trait(&self, path: &ast::Path) -> Option<Trait>1082 fn resolve_trait(&self, path: &ast::Path) -> Option<Trait> {
1083 let analyze = self.analyze(path.syntax())?;
1084 let hygiene = hir_expand::hygiene::Hygiene::new(self.db.upcast(), analyze.file_id);
1085 let ctx = LowerCtx::with_hygiene(self.db.upcast(), &hygiene);
1086 let hir_path = Path::from_src(path.clone(), &ctx)?;
1087 match analyze.resolver.resolve_path_in_type_ns_fully(self.db.upcast(), &hir_path)? {
1088 TypeNs::TraitId(id) => Some(Trait { id }),
1089 _ => None,
1090 }
1091 }
1092
expr_adjustments(&self, expr: &ast::Expr) -> Option<Vec<Adjustment>>1093 fn expr_adjustments(&self, expr: &ast::Expr) -> Option<Vec<Adjustment>> {
1094 let mutability = |m| match m {
1095 hir_ty::Mutability::Not => Mutability::Shared,
1096 hir_ty::Mutability::Mut => Mutability::Mut,
1097 };
1098
1099 let analyzer = self.analyze(expr.syntax())?;
1100
1101 let (mut source_ty, _) = analyzer.type_of_expr(self.db, expr)?;
1102
1103 analyzer.expr_adjustments(self.db, expr).map(|it| {
1104 it.iter()
1105 .map(|adjust| {
1106 let target =
1107 Type::new_with_resolver(self.db, &analyzer.resolver, adjust.target.clone());
1108 let kind = match adjust.kind {
1109 hir_ty::Adjust::NeverToAny => Adjust::NeverToAny,
1110 hir_ty::Adjust::Deref(Some(hir_ty::OverloadedDeref(m))) => {
1111 // FIXME: Should we handle unknown mutability better?
1112 Adjust::Deref(Some(OverloadedDeref(
1113 m.map(mutability).unwrap_or(Mutability::Shared),
1114 )))
1115 }
1116 hir_ty::Adjust::Deref(None) => Adjust::Deref(None),
1117 hir_ty::Adjust::Borrow(hir_ty::AutoBorrow::RawPtr(m)) => {
1118 Adjust::Borrow(AutoBorrow::RawPtr(mutability(m)))
1119 }
1120 hir_ty::Adjust::Borrow(hir_ty::AutoBorrow::Ref(m)) => {
1121 Adjust::Borrow(AutoBorrow::Ref(mutability(m)))
1122 }
1123 hir_ty::Adjust::Pointer(pc) => Adjust::Pointer(pc),
1124 };
1125
1126 // Update `source_ty` for the next adjustment
1127 let source = mem::replace(&mut source_ty, target.clone());
1128
1129 let adjustment = Adjustment { source, target, kind };
1130
1131 adjustment
1132 })
1133 .collect()
1134 })
1135 }
1136
type_of_expr(&self, expr: &ast::Expr) -> Option<TypeInfo>1137 fn type_of_expr(&self, expr: &ast::Expr) -> Option<TypeInfo> {
1138 self.analyze(expr.syntax())?
1139 .type_of_expr(self.db, expr)
1140 .map(|(ty, coerced)| TypeInfo { original: ty, adjusted: coerced })
1141 }
1142
type_of_pat(&self, pat: &ast::Pat) -> Option<TypeInfo>1143 fn type_of_pat(&self, pat: &ast::Pat) -> Option<TypeInfo> {
1144 self.analyze(pat.syntax())?
1145 .type_of_pat(self.db, pat)
1146 .map(|(ty, coerced)| TypeInfo { original: ty, adjusted: coerced })
1147 }
1148
type_of_binding_in_pat(&self, pat: &ast::IdentPat) -> Option<Type>1149 fn type_of_binding_in_pat(&self, pat: &ast::IdentPat) -> Option<Type> {
1150 self.analyze(pat.syntax())?.type_of_binding_in_pat(self.db, pat)
1151 }
1152
type_of_self(&self, param: &ast::SelfParam) -> Option<Type>1153 fn type_of_self(&self, param: &ast::SelfParam) -> Option<Type> {
1154 self.analyze(param.syntax())?.type_of_self(self.db, param)
1155 }
1156
pattern_adjustments(&self, pat: &ast::Pat) -> SmallVec<[Type; 1]>1157 fn pattern_adjustments(&self, pat: &ast::Pat) -> SmallVec<[Type; 1]> {
1158 self.analyze(pat.syntax())
1159 .and_then(|it| it.pattern_adjustments(self.db, pat))
1160 .unwrap_or_default()
1161 }
1162
binding_mode_of_pat(&self, pat: &ast::IdentPat) -> Option<BindingMode>1163 fn binding_mode_of_pat(&self, pat: &ast::IdentPat) -> Option<BindingMode> {
1164 self.analyze(pat.syntax())?.binding_mode_of_pat(self.db, pat)
1165 }
1166
resolve_method_call(&self, call: &ast::MethodCallExpr) -> Option<FunctionId>1167 fn resolve_method_call(&self, call: &ast::MethodCallExpr) -> Option<FunctionId> {
1168 self.analyze(call.syntax())?.resolve_method_call(self.db, call)
1169 }
1170
resolve_method_call_fallback( &self, call: &ast::MethodCallExpr, ) -> Option<Either<FunctionId, FieldId>>1171 fn resolve_method_call_fallback(
1172 &self,
1173 call: &ast::MethodCallExpr,
1174 ) -> Option<Either<FunctionId, FieldId>> {
1175 self.analyze(call.syntax())?.resolve_method_call_fallback(self.db, call)
1176 }
1177
resolve_await_to_poll(&self, await_expr: &ast::AwaitExpr) -> Option<FunctionId>1178 fn resolve_await_to_poll(&self, await_expr: &ast::AwaitExpr) -> Option<FunctionId> {
1179 self.analyze(await_expr.syntax())?.resolve_await_to_poll(self.db, await_expr)
1180 }
1181
resolve_prefix_expr(&self, prefix_expr: &ast::PrefixExpr) -> Option<FunctionId>1182 fn resolve_prefix_expr(&self, prefix_expr: &ast::PrefixExpr) -> Option<FunctionId> {
1183 self.analyze(prefix_expr.syntax())?.resolve_prefix_expr(self.db, prefix_expr)
1184 }
1185
resolve_index_expr(&self, index_expr: &ast::IndexExpr) -> Option<FunctionId>1186 fn resolve_index_expr(&self, index_expr: &ast::IndexExpr) -> Option<FunctionId> {
1187 self.analyze(index_expr.syntax())?.resolve_index_expr(self.db, index_expr)
1188 }
1189
resolve_bin_expr(&self, bin_expr: &ast::BinExpr) -> Option<FunctionId>1190 fn resolve_bin_expr(&self, bin_expr: &ast::BinExpr) -> Option<FunctionId> {
1191 self.analyze(bin_expr.syntax())?.resolve_bin_expr(self.db, bin_expr)
1192 }
1193
resolve_try_expr(&self, try_expr: &ast::TryExpr) -> Option<FunctionId>1194 fn resolve_try_expr(&self, try_expr: &ast::TryExpr) -> Option<FunctionId> {
1195 self.analyze(try_expr.syntax())?.resolve_try_expr(self.db, try_expr)
1196 }
1197
resolve_method_call_as_callable(&self, call: &ast::MethodCallExpr) -> Option<Callable>1198 fn resolve_method_call_as_callable(&self, call: &ast::MethodCallExpr) -> Option<Callable> {
1199 self.analyze(call.syntax())?.resolve_method_call_as_callable(self.db, call)
1200 }
1201
resolve_field(&self, field: &ast::FieldExpr) -> Option<Field>1202 fn resolve_field(&self, field: &ast::FieldExpr) -> Option<Field> {
1203 self.analyze(field.syntax())?.resolve_field(self.db, field)
1204 }
1205
resolve_record_field( &self, field: &ast::RecordExprField, ) -> Option<(Field, Option<Local>, Type)>1206 fn resolve_record_field(
1207 &self,
1208 field: &ast::RecordExprField,
1209 ) -> Option<(Field, Option<Local>, Type)> {
1210 self.analyze(field.syntax())?.resolve_record_field(self.db, field)
1211 }
1212
resolve_record_pat_field(&self, field: &ast::RecordPatField) -> Option<(Field, Type)>1213 fn resolve_record_pat_field(&self, field: &ast::RecordPatField) -> Option<(Field, Type)> {
1214 self.analyze(field.syntax())?.resolve_record_pat_field(self.db, field)
1215 }
1216
resolve_macro_call(&self, macro_call: &ast::MacroCall) -> Option<Macro>1217 fn resolve_macro_call(&self, macro_call: &ast::MacroCall) -> Option<Macro> {
1218 let sa = self.analyze(macro_call.syntax())?;
1219 let macro_call = self.find_file(macro_call.syntax()).with_value(macro_call);
1220 sa.resolve_macro_call(self.db, macro_call)
1221 }
1222
is_unsafe_macro_call(&self, macro_call: &ast::MacroCall) -> bool1223 fn is_unsafe_macro_call(&self, macro_call: &ast::MacroCall) -> bool {
1224 let sa = match self.analyze(macro_call.syntax()) {
1225 Some(it) => it,
1226 None => return false,
1227 };
1228 let macro_call = self.find_file(macro_call.syntax()).with_value(macro_call);
1229 sa.is_unsafe_macro_call(self.db, macro_call)
1230 }
1231
resolve_attr_macro_call(&self, item: &ast::Item) -> Option<Macro>1232 fn resolve_attr_macro_call(&self, item: &ast::Item) -> Option<Macro> {
1233 let item_in_file = self.wrap_node_infile(item.clone());
1234 let id = self.with_ctx(|ctx| {
1235 let macro_call_id = ctx.item_to_macro_call(item_in_file)?;
1236 macro_call_to_macro_id(ctx, self.db.upcast(), macro_call_id)
1237 })?;
1238 Some(Macro { id })
1239 }
1240
resolve_path(&self, path: &ast::Path) -> Option<PathResolution>1241 fn resolve_path(&self, path: &ast::Path) -> Option<PathResolution> {
1242 self.analyze(path.syntax())?.resolve_path(self.db, path)
1243 }
1244
resolve_extern_crate(&self, extern_crate: &ast::ExternCrate) -> Option<Crate>1245 fn resolve_extern_crate(&self, extern_crate: &ast::ExternCrate) -> Option<Crate> {
1246 let krate = self.scope(extern_crate.syntax())?.krate();
1247 let name = extern_crate.name_ref()?.as_name();
1248 if name == known::SELF_PARAM {
1249 return Some(krate);
1250 }
1251 krate
1252 .dependencies(self.db)
1253 .into_iter()
1254 .find_map(|dep| (dep.name == name).then_some(dep.krate))
1255 }
1256
resolve_variant(&self, record_lit: ast::RecordExpr) -> Option<VariantId>1257 fn resolve_variant(&self, record_lit: ast::RecordExpr) -> Option<VariantId> {
1258 self.analyze(record_lit.syntax())?.resolve_variant(self.db, record_lit)
1259 }
1260
resolve_bind_pat_to_const(&self, pat: &ast::IdentPat) -> Option<ModuleDef>1261 fn resolve_bind_pat_to_const(&self, pat: &ast::IdentPat) -> Option<ModuleDef> {
1262 self.analyze(pat.syntax())?.resolve_bind_pat_to_const(self.db, pat)
1263 }
1264
record_literal_missing_fields(&self, literal: &ast::RecordExpr) -> Vec<(Field, Type)>1265 fn record_literal_missing_fields(&self, literal: &ast::RecordExpr) -> Vec<(Field, Type)> {
1266 self.analyze(literal.syntax())
1267 .and_then(|it| it.record_literal_missing_fields(self.db, literal))
1268 .unwrap_or_default()
1269 }
1270
record_pattern_missing_fields(&self, pattern: &ast::RecordPat) -> Vec<(Field, Type)>1271 fn record_pattern_missing_fields(&self, pattern: &ast::RecordPat) -> Vec<(Field, Type)> {
1272 self.analyze(pattern.syntax())
1273 .and_then(|it| it.record_pattern_missing_fields(self.db, pattern))
1274 .unwrap_or_default()
1275 }
1276
with_ctx<F: FnOnce(&mut SourceToDefCtx<'_, '_>) -> T, T>(&self, f: F) -> T1277 fn with_ctx<F: FnOnce(&mut SourceToDefCtx<'_, '_>) -> T, T>(&self, f: F) -> T {
1278 let mut cache = self.s2d_cache.borrow_mut();
1279 let mut ctx = SourceToDefCtx { db: self.db, cache: &mut cache };
1280 f(&mut ctx)
1281 }
1282
to_def<T: ToDef>(&self, src: &T) -> Option<T::Def>1283 fn to_def<T: ToDef>(&self, src: &T) -> Option<T::Def> {
1284 let src = self.find_file(src.syntax()).with_value(src).cloned();
1285 T::to_def(self, src)
1286 }
1287
to_module_def(&self, file: FileId) -> impl Iterator<Item = Module>1288 fn to_module_def(&self, file: FileId) -> impl Iterator<Item = Module> {
1289 self.with_ctx(|ctx| ctx.file_to_def(file)).into_iter().map(Module::from)
1290 }
1291
scope(&self, node: &SyntaxNode) -> Option<SemanticsScope<'db>>1292 fn scope(&self, node: &SyntaxNode) -> Option<SemanticsScope<'db>> {
1293 self.analyze_no_infer(node).map(|SourceAnalyzer { file_id, resolver, .. }| SemanticsScope {
1294 db: self.db,
1295 file_id,
1296 resolver,
1297 })
1298 }
1299
scope_at_offset(&self, node: &SyntaxNode, offset: TextSize) -> Option<SemanticsScope<'db>>1300 fn scope_at_offset(&self, node: &SyntaxNode, offset: TextSize) -> Option<SemanticsScope<'db>> {
1301 self.analyze_with_offset_no_infer(node, offset).map(
1302 |SourceAnalyzer { file_id, resolver, .. }| SemanticsScope {
1303 db: self.db,
1304 file_id,
1305 resolver,
1306 },
1307 )
1308 }
1309
source<Def: HasSource>(&self, def: Def) -> Option<InFile<Def::Ast>> where Def::Ast: AstNode,1310 fn source<Def: HasSource>(&self, def: Def) -> Option<InFile<Def::Ast>>
1311 where
1312 Def::Ast: AstNode,
1313 {
1314 let res = def.source(self.db)?;
1315 self.cache(find_root(res.value.syntax()), res.file_id);
1316 Some(res)
1317 }
1318
1319 /// Returns none if the file of the node is not part of a crate.
analyze(&self, node: &SyntaxNode) -> Option<SourceAnalyzer>1320 fn analyze(&self, node: &SyntaxNode) -> Option<SourceAnalyzer> {
1321 self.analyze_impl(node, None, true)
1322 }
1323
1324 /// Returns none if the file of the node is not part of a crate.
analyze_no_infer(&self, node: &SyntaxNode) -> Option<SourceAnalyzer>1325 fn analyze_no_infer(&self, node: &SyntaxNode) -> Option<SourceAnalyzer> {
1326 self.analyze_impl(node, None, false)
1327 }
1328
analyze_with_offset_no_infer( &self, node: &SyntaxNode, offset: TextSize, ) -> Option<SourceAnalyzer>1329 fn analyze_with_offset_no_infer(
1330 &self,
1331 node: &SyntaxNode,
1332 offset: TextSize,
1333 ) -> Option<SourceAnalyzer> {
1334 self.analyze_impl(node, Some(offset), false)
1335 }
1336
analyze_impl( &self, node: &SyntaxNode, offset: Option<TextSize>, infer_body: bool, ) -> Option<SourceAnalyzer>1337 fn analyze_impl(
1338 &self,
1339 node: &SyntaxNode,
1340 offset: Option<TextSize>,
1341 infer_body: bool,
1342 ) -> Option<SourceAnalyzer> {
1343 let _p = profile::span("Semantics::analyze_impl");
1344 let node = self.find_file(node);
1345
1346 let container = self.with_ctx(|ctx| ctx.find_container(node))?;
1347
1348 let resolver = match container {
1349 ChildContainer::DefWithBodyId(def) => {
1350 return Some(if infer_body {
1351 SourceAnalyzer::new_for_body(self.db, def, node, offset)
1352 } else {
1353 SourceAnalyzer::new_for_body_no_infer(self.db, def, node, offset)
1354 })
1355 }
1356 ChildContainer::TraitId(it) => it.resolver(self.db.upcast()),
1357 ChildContainer::TraitAliasId(it) => it.resolver(self.db.upcast()),
1358 ChildContainer::ImplId(it) => it.resolver(self.db.upcast()),
1359 ChildContainer::ModuleId(it) => it.resolver(self.db.upcast()),
1360 ChildContainer::EnumId(it) => it.resolver(self.db.upcast()),
1361 ChildContainer::VariantId(it) => it.resolver(self.db.upcast()),
1362 ChildContainer::TypeAliasId(it) => it.resolver(self.db.upcast()),
1363 ChildContainer::GenericDefId(it) => it.resolver(self.db.upcast()),
1364 };
1365 Some(SourceAnalyzer::new_for_resolver(resolver, node))
1366 }
1367
cache(&self, root_node: SyntaxNode, file_id: HirFileId)1368 fn cache(&self, root_node: SyntaxNode, file_id: HirFileId) {
1369 assert!(root_node.parent().is_none());
1370 let mut cache = self.cache.borrow_mut();
1371 let prev = cache.insert(root_node, file_id);
1372 assert!(prev == None || prev == Some(file_id))
1373 }
1374
assert_contains_node(&self, node: &SyntaxNode)1375 fn assert_contains_node(&self, node: &SyntaxNode) {
1376 self.find_file(node);
1377 }
1378
lookup(&self, root_node: &SyntaxNode) -> Option<HirFileId>1379 fn lookup(&self, root_node: &SyntaxNode) -> Option<HirFileId> {
1380 let cache = self.cache.borrow();
1381 cache.get(root_node).copied()
1382 }
1383
wrap_node_infile<N: AstNode>(&self, node: N) -> InFile<N>1384 fn wrap_node_infile<N: AstNode>(&self, node: N) -> InFile<N> {
1385 let InFile { file_id, .. } = self.find_file(node.syntax());
1386 InFile::new(file_id, node)
1387 }
1388
1389 /// Wraps the node in a [`InFile`] with the file id it belongs to.
find_file<'node>(&self, node: &'node SyntaxNode) -> InFile<&'node SyntaxNode>1390 fn find_file<'node>(&self, node: &'node SyntaxNode) -> InFile<&'node SyntaxNode> {
1391 let root_node = find_root(node);
1392 let file_id = self.lookup(&root_node).unwrap_or_else(|| {
1393 panic!(
1394 "\n\nFailed to lookup {:?} in this Semantics.\n\
1395 Make sure to use only query nodes, derived from this instance of Semantics.\n\
1396 root node: {:?}\n\
1397 known nodes: {}\n\n",
1398 node,
1399 root_node,
1400 self.cache
1401 .borrow()
1402 .keys()
1403 .map(|it| format!("{it:?}"))
1404 .collect::<Vec<_>>()
1405 .join(", ")
1406 )
1407 });
1408 InFile::new(file_id, node)
1409 }
1410
is_unsafe_method_call(&self, method_call_expr: &ast::MethodCallExpr) -> bool1411 fn is_unsafe_method_call(&self, method_call_expr: &ast::MethodCallExpr) -> bool {
1412 method_call_expr
1413 .receiver()
1414 .and_then(|expr| {
1415 let field_expr = match expr {
1416 ast::Expr::FieldExpr(field_expr) => field_expr,
1417 _ => return None,
1418 };
1419 let ty = self.type_of_expr(&field_expr.expr()?)?.original;
1420 if !ty.is_packed(self.db) {
1421 return None;
1422 }
1423
1424 let func = self.resolve_method_call(method_call_expr).map(Function::from)?;
1425 let res = match func.self_param(self.db)?.access(self.db) {
1426 Access::Shared | Access::Exclusive => true,
1427 Access::Owned => false,
1428 };
1429 Some(res)
1430 })
1431 .unwrap_or(false)
1432 }
1433
is_unsafe_ref_expr(&self, ref_expr: &ast::RefExpr) -> bool1434 fn is_unsafe_ref_expr(&self, ref_expr: &ast::RefExpr) -> bool {
1435 ref_expr
1436 .expr()
1437 .and_then(|expr| {
1438 let field_expr = match expr {
1439 ast::Expr::FieldExpr(field_expr) => field_expr,
1440 _ => return None,
1441 };
1442 let expr = field_expr.expr()?;
1443 self.type_of_expr(&expr)
1444 })
1445 // Binding a reference to a packed type is possibly unsafe.
1446 .map(|ty| ty.original.is_packed(self.db))
1447 .unwrap_or(false)
1448
1449 // FIXME This needs layout computation to be correct. It will highlight
1450 // more than it should with the current implementation.
1451 }
1452
is_unsafe_ident_pat(&self, ident_pat: &ast::IdentPat) -> bool1453 fn is_unsafe_ident_pat(&self, ident_pat: &ast::IdentPat) -> bool {
1454 if ident_pat.ref_token().is_none() {
1455 return false;
1456 }
1457
1458 ident_pat
1459 .syntax()
1460 .parent()
1461 .and_then(|parent| {
1462 // `IdentPat` can live under `RecordPat` directly under `RecordPatField` or
1463 // `RecordPatFieldList`. `RecordPatField` also lives under `RecordPatFieldList`,
1464 // so this tries to lookup the `IdentPat` anywhere along that structure to the
1465 // `RecordPat` so we can get the containing type.
1466 let record_pat = ast::RecordPatField::cast(parent.clone())
1467 .and_then(|record_pat| record_pat.syntax().parent())
1468 .or_else(|| Some(parent.clone()))
1469 .and_then(|parent| {
1470 ast::RecordPatFieldList::cast(parent)?
1471 .syntax()
1472 .parent()
1473 .and_then(ast::RecordPat::cast)
1474 });
1475
1476 // If this doesn't match a `RecordPat`, fallback to a `LetStmt` to see if
1477 // this is initialized from a `FieldExpr`.
1478 if let Some(record_pat) = record_pat {
1479 self.type_of_pat(&ast::Pat::RecordPat(record_pat))
1480 } else if let Some(let_stmt) = ast::LetStmt::cast(parent) {
1481 let field_expr = match let_stmt.initializer()? {
1482 ast::Expr::FieldExpr(field_expr) => field_expr,
1483 _ => return None,
1484 };
1485
1486 self.type_of_expr(&field_expr.expr()?)
1487 } else {
1488 None
1489 }
1490 })
1491 // Binding a reference to a packed type is possibly unsafe.
1492 .map(|ty| ty.original.is_packed(self.db))
1493 .unwrap_or(false)
1494 }
1495
is_inside_unsafe(&self, expr: &ast::Expr) -> bool1496 fn is_inside_unsafe(&self, expr: &ast::Expr) -> bool {
1497 let Some(enclosing_item) = expr.syntax().ancestors().find_map(Either::<ast::Item, ast::Variant>::cast) else { return false };
1498
1499 let def = match &enclosing_item {
1500 Either::Left(ast::Item::Fn(it)) if it.unsafe_token().is_some() => return true,
1501 Either::Left(ast::Item::Fn(it)) => {
1502 self.to_def(it).map(<_>::into).map(DefWithBodyId::FunctionId)
1503 }
1504 Either::Left(ast::Item::Const(it)) => {
1505 self.to_def(it).map(<_>::into).map(DefWithBodyId::ConstId)
1506 }
1507 Either::Left(ast::Item::Static(it)) => {
1508 self.to_def(it).map(<_>::into).map(DefWithBodyId::StaticId)
1509 }
1510 Either::Left(_) => None,
1511 Either::Right(it) => self.to_def(it).map(<_>::into).map(DefWithBodyId::VariantId),
1512 };
1513 let Some(def) = def else { return false };
1514 let enclosing_node = enclosing_item.as_ref().either(|i| i.syntax(), |v| v.syntax());
1515
1516 let (body, source_map) = self.db.body_with_source_map(def);
1517
1518 let file_id = self.find_file(expr.syntax()).file_id;
1519
1520 let Some(mut parent) = expr.syntax().parent() else { return false };
1521 loop {
1522 if &parent == enclosing_node {
1523 break false;
1524 }
1525
1526 if let Some(parent) = ast::Expr::cast(parent.clone()) {
1527 if let Some(expr_id) = source_map.node_expr(InFile { file_id, value: &parent }) {
1528 if let Expr::Unsafe { .. } = body[expr_id] {
1529 break true;
1530 }
1531 }
1532 }
1533
1534 let Some(parent_) = parent.parent() else { break false };
1535 parent = parent_;
1536 }
1537 }
1538 }
1539
macro_call_to_macro_id( ctx: &mut SourceToDefCtx<'_, '_>, db: &dyn ExpandDatabase, macro_call_id: MacroCallId, ) -> Option<MacroId>1540 fn macro_call_to_macro_id(
1541 ctx: &mut SourceToDefCtx<'_, '_>,
1542 db: &dyn ExpandDatabase,
1543 macro_call_id: MacroCallId,
1544 ) -> Option<MacroId> {
1545 let loc = db.lookup_intern_macro_call(macro_call_id);
1546 match loc.def.kind {
1547 hir_expand::MacroDefKind::Declarative(it)
1548 | hir_expand::MacroDefKind::BuiltIn(_, it)
1549 | hir_expand::MacroDefKind::BuiltInAttr(_, it)
1550 | hir_expand::MacroDefKind::BuiltInDerive(_, it)
1551 | hir_expand::MacroDefKind::BuiltInEager(_, it) => {
1552 ctx.macro_to_def(InFile::new(it.file_id, it.to_node(db)))
1553 }
1554 hir_expand::MacroDefKind::ProcMacro(_, _, it) => {
1555 ctx.proc_macro_to_def(InFile::new(it.file_id, it.to_node(db)))
1556 }
1557 }
1558 }
1559
1560 pub trait ToDef: AstNode + Clone {
1561 type Def;
1562
to_def(sema: &SemanticsImpl<'_>, src: InFile<Self>) -> Option<Self::Def>1563 fn to_def(sema: &SemanticsImpl<'_>, src: InFile<Self>) -> Option<Self::Def>;
1564 }
1565
1566 macro_rules! to_def_impls {
1567 ($(($def:path, $ast:path, $meth:ident)),* ,) => {$(
1568 impl ToDef for $ast {
1569 type Def = $def;
1570 fn to_def(sema: &SemanticsImpl<'_>, src: InFile<Self>) -> Option<Self::Def> {
1571 sema.with_ctx(|ctx| ctx.$meth(src)).map(<$def>::from)
1572 }
1573 }
1574 )*}
1575 }
1576
1577 to_def_impls![
1578 (crate::Module, ast::Module, module_to_def),
1579 (crate::Module, ast::SourceFile, source_file_to_def),
1580 (crate::Struct, ast::Struct, struct_to_def),
1581 (crate::Enum, ast::Enum, enum_to_def),
1582 (crate::Union, ast::Union, union_to_def),
1583 (crate::Trait, ast::Trait, trait_to_def),
1584 (crate::TraitAlias, ast::TraitAlias, trait_alias_to_def),
1585 (crate::Impl, ast::Impl, impl_to_def),
1586 (crate::TypeAlias, ast::TypeAlias, type_alias_to_def),
1587 (crate::Const, ast::Const, const_to_def),
1588 (crate::Static, ast::Static, static_to_def),
1589 (crate::Function, ast::Fn, fn_to_def),
1590 (crate::Field, ast::RecordField, record_field_to_def),
1591 (crate::Field, ast::TupleField, tuple_field_to_def),
1592 (crate::Variant, ast::Variant, enum_variant_to_def),
1593 (crate::TypeParam, ast::TypeParam, type_param_to_def),
1594 (crate::LifetimeParam, ast::LifetimeParam, lifetime_param_to_def),
1595 (crate::ConstParam, ast::ConstParam, const_param_to_def),
1596 (crate::GenericParam, ast::GenericParam, generic_param_to_def),
1597 (crate::Macro, ast::Macro, macro_to_def),
1598 (crate::Local, ast::IdentPat, bind_pat_to_def),
1599 (crate::Local, ast::SelfParam, self_param_to_def),
1600 (crate::Label, ast::Label, label_to_def),
1601 (crate::Adt, ast::Adt, adt_to_def),
1602 ];
1603
find_root(node: &SyntaxNode) -> SyntaxNode1604 fn find_root(node: &SyntaxNode) -> SyntaxNode {
1605 node.ancestors().last().unwrap()
1606 }
1607
1608 /// `SemanticsScope` encapsulates the notion of a scope (the set of visible
1609 /// names) at a particular program point.
1610 ///
1611 /// It is a bit tricky, as scopes do not really exist inside the compiler.
1612 /// Rather, the compiler directly computes for each reference the definition it
1613 /// refers to. It might transiently compute the explicit scope map while doing
1614 /// so, but, generally, this is not something left after the analysis.
1615 ///
1616 /// However, we do very much need explicit scopes for IDE purposes --
1617 /// completion, at its core, lists the contents of the current scope. The notion
1618 /// of scope is also useful to answer questions like "what would be the meaning
1619 /// of this piece of code if we inserted it into this position?".
1620 ///
1621 /// So `SemanticsScope` is constructed from a specific program point (a syntax
1622 /// node or just a raw offset) and provides access to the set of visible names
1623 /// on a somewhat best-effort basis.
1624 ///
1625 /// Note that if you are wondering "what does this specific existing name mean?",
1626 /// you'd better use the `resolve_` family of methods.
1627 #[derive(Debug)]
1628 pub struct SemanticsScope<'a> {
1629 pub db: &'a dyn HirDatabase,
1630 file_id: HirFileId,
1631 resolver: Resolver,
1632 }
1633
1634 impl<'a> SemanticsScope<'a> {
module(&self) -> Module1635 pub fn module(&self) -> Module {
1636 Module { id: self.resolver.module() }
1637 }
1638
krate(&self) -> Crate1639 pub fn krate(&self) -> Crate {
1640 Crate { id: self.resolver.krate() }
1641 }
1642
resolver(&self) -> &Resolver1643 pub(crate) fn resolver(&self) -> &Resolver {
1644 &self.resolver
1645 }
1646
1647 /// Note: `VisibleTraits` should be treated as an opaque type, passed into `Type
visible_traits(&self) -> VisibleTraits1648 pub fn visible_traits(&self) -> VisibleTraits {
1649 let resolver = &self.resolver;
1650 VisibleTraits(resolver.traits_in_scope(self.db.upcast()))
1651 }
1652
1653 /// Calls the passed closure `f` on all names in scope.
process_all_names(&self, f: &mut dyn FnMut(Name, ScopeDef))1654 pub fn process_all_names(&self, f: &mut dyn FnMut(Name, ScopeDef)) {
1655 let scope = self.resolver.names_in_scope(self.db.upcast());
1656 for (name, entries) in scope {
1657 for entry in entries {
1658 let def = match entry {
1659 resolver::ScopeDef::ModuleDef(it) => ScopeDef::ModuleDef(it.into()),
1660 resolver::ScopeDef::Unknown => ScopeDef::Unknown,
1661 resolver::ScopeDef::ImplSelfType(it) => ScopeDef::ImplSelfType(it.into()),
1662 resolver::ScopeDef::AdtSelfType(it) => ScopeDef::AdtSelfType(it.into()),
1663 resolver::ScopeDef::GenericParam(id) => ScopeDef::GenericParam(id.into()),
1664 resolver::ScopeDef::Local(binding_id) => match self.resolver.body_owner() {
1665 Some(parent) => ScopeDef::Local(Local { parent, binding_id }),
1666 None => continue,
1667 },
1668 resolver::ScopeDef::Label(label_id) => match self.resolver.body_owner() {
1669 Some(parent) => ScopeDef::Label(Label { parent, label_id }),
1670 None => continue,
1671 },
1672 };
1673 f(name.clone(), def)
1674 }
1675 }
1676 }
1677
1678 /// Resolve a path as-if it was written at the given scope. This is
1679 /// necessary a heuristic, as it doesn't take hygiene into account.
speculative_resolve(&self, path: &ast::Path) -> Option<PathResolution>1680 pub fn speculative_resolve(&self, path: &ast::Path) -> Option<PathResolution> {
1681 let ctx = LowerCtx::with_file_id(self.db.upcast(), self.file_id);
1682 let path = Path::from_src(path.clone(), &ctx)?;
1683 resolve_hir_path(self.db, &self.resolver, &path)
1684 }
1685
1686 /// Iterates over associated types that may be specified after the given path (using
1687 /// `Ty::Assoc` syntax).
assoc_type_shorthand_candidates<R>( &self, resolution: &PathResolution, mut cb: impl FnMut(&Name, TypeAlias) -> Option<R>, ) -> Option<R>1688 pub fn assoc_type_shorthand_candidates<R>(
1689 &self,
1690 resolution: &PathResolution,
1691 mut cb: impl FnMut(&Name, TypeAlias) -> Option<R>,
1692 ) -> Option<R> {
1693 let def = self.resolver.generic_def()?;
1694 hir_ty::associated_type_shorthand_candidates(
1695 self.db,
1696 def,
1697 resolution.in_type_ns()?,
1698 |name, id| cb(name, id.into()),
1699 )
1700 }
1701 }
1702
1703 #[derive(Debug)]
1704 pub struct VisibleTraits(pub FxHashSet<TraitId>);
1705
1706 impl ops::Deref for VisibleTraits {
1707 type Target = FxHashSet<TraitId>;
1708
deref(&self) -> &Self::Target1709 fn deref(&self) -> &Self::Target {
1710 &self.0
1711 }
1712 }
1713