diff options
Diffstat (limited to 'crates/hir/src/semantics.rs')
-rw-r--r-- | crates/hir/src/semantics.rs | 849 |
1 files changed, 849 insertions, 0 deletions
diff --git a/crates/hir/src/semantics.rs b/crates/hir/src/semantics.rs new file mode 100644 index 000000000..3953017c3 --- /dev/null +++ b/crates/hir/src/semantics.rs | |||
@@ -0,0 +1,849 @@ | |||
1 | //! See `Semantics`. | ||
2 | |||
3 | mod source_to_def; | ||
4 | |||
5 | use std::{cell::RefCell, fmt, iter::successors}; | ||
6 | |||
7 | use base_db::{FileId, FileRange}; | ||
8 | use hir_def::{ | ||
9 | resolver::{self, HasResolver, Resolver}, | ||
10 | AsMacroCall, FunctionId, TraitId, VariantId, | ||
11 | }; | ||
12 | use hir_expand::{hygiene::Hygiene, name::AsName, ExpansionInfo}; | ||
13 | use hir_ty::associated_type_shorthand_candidates; | ||
14 | use itertools::Itertools; | ||
15 | use rustc_hash::{FxHashMap, FxHashSet}; | ||
16 | use syntax::{ | ||
17 | algo::{find_node_at_offset, skip_trivia_token}, | ||
18 | ast, AstNode, Direction, SyntaxNode, SyntaxToken, TextRange, TextSize, | ||
19 | }; | ||
20 | |||
21 | use crate::{ | ||
22 | db::HirDatabase, | ||
23 | diagnostics::Diagnostic, | ||
24 | semantics::source_to_def::{ChildContainer, SourceToDefCache, SourceToDefCtx}, | ||
25 | source_analyzer::{resolve_hir_path, resolve_hir_path_qualifier, SourceAnalyzer}, | ||
26 | AssocItem, Callable, Crate, Field, Function, HirFileId, ImplDef, InFile, Local, MacroDef, | ||
27 | Module, ModuleDef, Name, Origin, Path, ScopeDef, Trait, Type, TypeAlias, TypeParam, TypeRef, | ||
28 | VariantDef, | ||
29 | }; | ||
30 | use resolver::TypeNs; | ||
31 | |||
32 | #[derive(Debug, Clone, PartialEq, Eq)] | ||
33 | pub enum PathResolution { | ||
34 | /// An item | ||
35 | Def(ModuleDef), | ||
36 | /// A local binding (only value namespace) | ||
37 | Local(Local), | ||
38 | /// A generic parameter | ||
39 | TypeParam(TypeParam), | ||
40 | SelfType(ImplDef), | ||
41 | Macro(MacroDef), | ||
42 | AssocItem(AssocItem), | ||
43 | } | ||
44 | |||
45 | impl PathResolution { | ||
46 | fn in_type_ns(&self) -> Option<TypeNs> { | ||
47 | match self { | ||
48 | PathResolution::Def(ModuleDef::Adt(adt)) => Some(TypeNs::AdtId((*adt).into())), | ||
49 | PathResolution::Def(ModuleDef::BuiltinType(builtin)) => { | ||
50 | Some(TypeNs::BuiltinType(*builtin)) | ||
51 | } | ||
52 | PathResolution::Def(ModuleDef::Const(_)) | ||
53 | | PathResolution::Def(ModuleDef::EnumVariant(_)) | ||
54 | | PathResolution::Def(ModuleDef::Function(_)) | ||
55 | | PathResolution::Def(ModuleDef::Module(_)) | ||
56 | | PathResolution::Def(ModuleDef::Static(_)) | ||
57 | | PathResolution::Def(ModuleDef::Trait(_)) => None, | ||
58 | PathResolution::Def(ModuleDef::TypeAlias(alias)) => { | ||
59 | Some(TypeNs::TypeAliasId((*alias).into())) | ||
60 | } | ||
61 | PathResolution::Local(_) | PathResolution::Macro(_) => None, | ||
62 | PathResolution::TypeParam(param) => Some(TypeNs::GenericParam((*param).into())), | ||
63 | PathResolution::SelfType(impl_def) => Some(TypeNs::SelfType((*impl_def).into())), | ||
64 | PathResolution::AssocItem(AssocItem::Const(_)) | ||
65 | | PathResolution::AssocItem(AssocItem::Function(_)) => None, | ||
66 | PathResolution::AssocItem(AssocItem::TypeAlias(alias)) => { | ||
67 | Some(TypeNs::TypeAliasId((*alias).into())) | ||
68 | } | ||
69 | } | ||
70 | } | ||
71 | |||
72 | /// Returns an iterator over associated types that may be specified after this path (using | ||
73 | /// `Ty::Assoc` syntax). | ||
74 | pub fn assoc_type_shorthand_candidates<R>( | ||
75 | &self, | ||
76 | db: &dyn HirDatabase, | ||
77 | mut cb: impl FnMut(TypeAlias) -> Option<R>, | ||
78 | ) -> Option<R> { | ||
79 | associated_type_shorthand_candidates(db, self.in_type_ns()?, |_, _, id| cb(id.into())) | ||
80 | } | ||
81 | } | ||
82 | |||
83 | /// Primary API to get semantic information, like types, from syntax trees. | ||
84 | pub struct Semantics<'db, DB> { | ||
85 | pub db: &'db DB, | ||
86 | imp: SemanticsImpl<'db>, | ||
87 | } | ||
88 | |||
89 | pub struct SemanticsImpl<'db> { | ||
90 | pub db: &'db dyn HirDatabase, | ||
91 | s2d_cache: RefCell<SourceToDefCache>, | ||
92 | expansion_info_cache: RefCell<FxHashMap<HirFileId, Option<ExpansionInfo>>>, | ||
93 | cache: RefCell<FxHashMap<SyntaxNode, HirFileId>>, | ||
94 | } | ||
95 | |||
96 | impl<DB> fmt::Debug for Semantics<'_, DB> { | ||
97 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
98 | write!(f, "Semantics {{ ... }}") | ||
99 | } | ||
100 | } | ||
101 | |||
102 | impl<'db, DB: HirDatabase> Semantics<'db, DB> { | ||
103 | pub fn new(db: &DB) -> Semantics<DB> { | ||
104 | let impl_ = SemanticsImpl::new(db); | ||
105 | Semantics { db, imp: impl_ } | ||
106 | } | ||
107 | |||
108 | pub fn parse(&self, file_id: FileId) -> ast::SourceFile { | ||
109 | self.imp.parse(file_id) | ||
110 | } | ||
111 | |||
112 | pub fn expand(&self, macro_call: &ast::MacroCall) -> Option<SyntaxNode> { | ||
113 | self.imp.expand(macro_call) | ||
114 | } | ||
115 | pub fn speculative_expand( | ||
116 | &self, | ||
117 | actual_macro_call: &ast::MacroCall, | ||
118 | hypothetical_args: &ast::TokenTree, | ||
119 | token_to_map: SyntaxToken, | ||
120 | ) -> Option<(SyntaxNode, SyntaxToken)> { | ||
121 | self.imp.speculative_expand(actual_macro_call, hypothetical_args, token_to_map) | ||
122 | } | ||
123 | |||
124 | pub fn descend_into_macros(&self, token: SyntaxToken) -> SyntaxToken { | ||
125 | self.imp.descend_into_macros(token) | ||
126 | } | ||
127 | |||
128 | pub fn descend_node_at_offset<N: ast::AstNode>( | ||
129 | &self, | ||
130 | node: &SyntaxNode, | ||
131 | offset: TextSize, | ||
132 | ) -> Option<N> { | ||
133 | self.imp.descend_node_at_offset(node, offset).find_map(N::cast) | ||
134 | } | ||
135 | |||
136 | pub fn original_range(&self, node: &SyntaxNode) -> FileRange { | ||
137 | self.imp.original_range(node) | ||
138 | } | ||
139 | |||
140 | pub fn diagnostics_display_range(&self, diagnostics: &dyn Diagnostic) -> FileRange { | ||
141 | self.imp.diagnostics_display_range(diagnostics) | ||
142 | } | ||
143 | |||
144 | pub fn ancestors_with_macros(&self, node: SyntaxNode) -> impl Iterator<Item = SyntaxNode> + '_ { | ||
145 | self.imp.ancestors_with_macros(node) | ||
146 | } | ||
147 | |||
148 | pub fn ancestors_at_offset_with_macros( | ||
149 | &self, | ||
150 | node: &SyntaxNode, | ||
151 | offset: TextSize, | ||
152 | ) -> impl Iterator<Item = SyntaxNode> + '_ { | ||
153 | self.imp.ancestors_at_offset_with_macros(node, offset) | ||
154 | } | ||
155 | |||
156 | /// Find a AstNode by offset inside SyntaxNode, if it is inside *Macrofile*, | ||
157 | /// search up until it is of the target AstNode type | ||
158 | pub fn find_node_at_offset_with_macros<N: AstNode>( | ||
159 | &self, | ||
160 | node: &SyntaxNode, | ||
161 | offset: TextSize, | ||
162 | ) -> Option<N> { | ||
163 | self.imp.ancestors_at_offset_with_macros(node, offset).find_map(N::cast) | ||
164 | } | ||
165 | |||
166 | /// Find a AstNode by offset inside SyntaxNode, if it is inside *MacroCall*, | ||
167 | /// descend it and find again | ||
168 | pub fn find_node_at_offset_with_descend<N: AstNode>( | ||
169 | &self, | ||
170 | node: &SyntaxNode, | ||
171 | offset: TextSize, | ||
172 | ) -> Option<N> { | ||
173 | if let Some(it) = find_node_at_offset(&node, offset) { | ||
174 | return Some(it); | ||
175 | } | ||
176 | |||
177 | self.imp.descend_node_at_offset(node, offset).find_map(N::cast) | ||
178 | } | ||
179 | |||
180 | pub fn type_of_expr(&self, expr: &ast::Expr) -> Option<Type> { | ||
181 | self.imp.type_of_expr(expr) | ||
182 | } | ||
183 | |||
184 | pub fn type_of_pat(&self, pat: &ast::Pat) -> Option<Type> { | ||
185 | self.imp.type_of_pat(pat) | ||
186 | } | ||
187 | |||
188 | pub fn type_of_self(&self, param: &ast::SelfParam) -> Option<Type> { | ||
189 | self.imp.type_of_self(param) | ||
190 | } | ||
191 | |||
192 | pub fn resolve_method_call(&self, call: &ast::MethodCallExpr) -> Option<Function> { | ||
193 | self.imp.resolve_method_call(call).map(Function::from) | ||
194 | } | ||
195 | |||
196 | pub fn resolve_method_call_as_callable(&self, call: &ast::MethodCallExpr) -> Option<Callable> { | ||
197 | self.imp.resolve_method_call_as_callable(call) | ||
198 | } | ||
199 | |||
200 | pub fn resolve_field(&self, field: &ast::FieldExpr) -> Option<Field> { | ||
201 | self.imp.resolve_field(field) | ||
202 | } | ||
203 | |||
204 | pub fn resolve_record_field( | ||
205 | &self, | ||
206 | field: &ast::RecordExprField, | ||
207 | ) -> Option<(Field, Option<Local>)> { | ||
208 | self.imp.resolve_record_field(field) | ||
209 | } | ||
210 | |||
211 | pub fn resolve_record_field_pat(&self, field: &ast::RecordPatField) -> Option<Field> { | ||
212 | self.imp.resolve_record_field_pat(field) | ||
213 | } | ||
214 | |||
215 | pub fn resolve_macro_call(&self, macro_call: &ast::MacroCall) -> Option<MacroDef> { | ||
216 | self.imp.resolve_macro_call(macro_call) | ||
217 | } | ||
218 | |||
219 | pub fn resolve_path(&self, path: &ast::Path) -> Option<PathResolution> { | ||
220 | self.imp.resolve_path(path) | ||
221 | } | ||
222 | |||
223 | pub fn resolve_extern_crate(&self, extern_crate: &ast::ExternCrate) -> Option<Crate> { | ||
224 | self.imp.resolve_extern_crate(extern_crate) | ||
225 | } | ||
226 | |||
227 | pub fn resolve_variant(&self, record_lit: ast::RecordExpr) -> Option<VariantDef> { | ||
228 | self.imp.resolve_variant(record_lit).map(VariantDef::from) | ||
229 | } | ||
230 | |||
231 | pub fn lower_path(&self, path: &ast::Path) -> Option<Path> { | ||
232 | self.imp.lower_path(path) | ||
233 | } | ||
234 | |||
235 | pub fn resolve_bind_pat_to_const(&self, pat: &ast::IdentPat) -> Option<ModuleDef> { | ||
236 | self.imp.resolve_bind_pat_to_const(pat) | ||
237 | } | ||
238 | |||
239 | // FIXME: use this instead? | ||
240 | // pub fn resolve_name_ref(&self, name_ref: &ast::NameRef) -> Option<???>; | ||
241 | |||
242 | pub fn record_literal_missing_fields(&self, literal: &ast::RecordExpr) -> Vec<(Field, Type)> { | ||
243 | self.imp.record_literal_missing_fields(literal) | ||
244 | } | ||
245 | |||
246 | pub fn record_pattern_missing_fields(&self, pattern: &ast::RecordPat) -> Vec<(Field, Type)> { | ||
247 | self.imp.record_pattern_missing_fields(pattern) | ||
248 | } | ||
249 | |||
250 | pub fn to_def<T: ToDef>(&self, src: &T) -> Option<T::Def> { | ||
251 | let src = self.imp.find_file(src.syntax().clone()).with_value(src).cloned(); | ||
252 | T::to_def(&self.imp, src) | ||
253 | } | ||
254 | |||
255 | pub fn to_module_def(&self, file: FileId) -> Option<Module> { | ||
256 | self.imp.to_module_def(file) | ||
257 | } | ||
258 | |||
259 | pub fn scope(&self, node: &SyntaxNode) -> SemanticsScope<'db> { | ||
260 | self.imp.scope(node) | ||
261 | } | ||
262 | |||
263 | pub fn scope_at_offset(&self, node: &SyntaxNode, offset: TextSize) -> SemanticsScope<'db> { | ||
264 | self.imp.scope_at_offset(node, offset) | ||
265 | } | ||
266 | |||
267 | pub fn scope_for_def(&self, def: Trait) -> SemanticsScope<'db> { | ||
268 | self.imp.scope_for_def(def) | ||
269 | } | ||
270 | |||
271 | pub fn assert_contains_node(&self, node: &SyntaxNode) { | ||
272 | self.imp.assert_contains_node(node) | ||
273 | } | ||
274 | |||
275 | pub fn is_unsafe_method_call(&self, method_call_expr: ast::MethodCallExpr) -> bool { | ||
276 | self.imp.is_unsafe_method_call(method_call_expr) | ||
277 | } | ||
278 | |||
279 | pub fn is_unsafe_ref_expr(&self, ref_expr: &ast::RefExpr) -> bool { | ||
280 | self.imp.is_unsafe_ref_expr(ref_expr) | ||
281 | } | ||
282 | |||
283 | pub fn is_unsafe_ident_pat(&self, ident_pat: &ast::IdentPat) -> bool { | ||
284 | self.imp.is_unsafe_ident_pat(ident_pat) | ||
285 | } | ||
286 | } | ||
287 | |||
288 | impl<'db> SemanticsImpl<'db> { | ||
289 | fn new(db: &'db dyn HirDatabase) -> Self { | ||
290 | SemanticsImpl { | ||
291 | db, | ||
292 | s2d_cache: Default::default(), | ||
293 | cache: Default::default(), | ||
294 | expansion_info_cache: Default::default(), | ||
295 | } | ||
296 | } | ||
297 | |||
298 | fn parse(&self, file_id: FileId) -> ast::SourceFile { | ||
299 | let tree = self.db.parse(file_id).tree(); | ||
300 | self.cache(tree.syntax().clone(), file_id.into()); | ||
301 | tree | ||
302 | } | ||
303 | |||
304 | fn expand(&self, macro_call: &ast::MacroCall) -> Option<SyntaxNode> { | ||
305 | let macro_call = self.find_file(macro_call.syntax().clone()).with_value(macro_call); | ||
306 | let sa = self.analyze2(macro_call.map(|it| it.syntax()), None); | ||
307 | let file_id = sa.expand(self.db, macro_call)?; | ||
308 | let node = self.db.parse_or_expand(file_id)?; | ||
309 | self.cache(node.clone(), file_id); | ||
310 | Some(node) | ||
311 | } | ||
312 | |||
313 | fn speculative_expand( | ||
314 | &self, | ||
315 | actual_macro_call: &ast::MacroCall, | ||
316 | hypothetical_args: &ast::TokenTree, | ||
317 | token_to_map: SyntaxToken, | ||
318 | ) -> Option<(SyntaxNode, SyntaxToken)> { | ||
319 | let macro_call = | ||
320 | self.find_file(actual_macro_call.syntax().clone()).with_value(actual_macro_call); | ||
321 | let sa = self.analyze2(macro_call.map(|it| it.syntax()), None); | ||
322 | let krate = sa.resolver.krate()?; | ||
323 | let macro_call_id = macro_call.as_call_id(self.db.upcast(), krate, |path| { | ||
324 | sa.resolver.resolve_path_as_macro(self.db.upcast(), &path) | ||
325 | })?; | ||
326 | hir_expand::db::expand_hypothetical( | ||
327 | self.db.upcast(), | ||
328 | macro_call_id, | ||
329 | hypothetical_args, | ||
330 | token_to_map, | ||
331 | ) | ||
332 | } | ||
333 | |||
334 | fn descend_into_macros(&self, token: SyntaxToken) -> SyntaxToken { | ||
335 | let _p = profile::span("descend_into_macros"); | ||
336 | let parent = token.parent(); | ||
337 | let parent = self.find_file(parent); | ||
338 | let sa = self.analyze2(parent.as_ref(), None); | ||
339 | |||
340 | let token = successors(Some(parent.with_value(token)), |token| { | ||
341 | self.db.check_canceled(); | ||
342 | let macro_call = token.value.ancestors().find_map(ast::MacroCall::cast)?; | ||
343 | let tt = macro_call.token_tree()?; | ||
344 | if !tt.syntax().text_range().contains_range(token.value.text_range()) { | ||
345 | return None; | ||
346 | } | ||
347 | let file_id = sa.expand(self.db, token.with_value(¯o_call))?; | ||
348 | let token = self | ||
349 | .expansion_info_cache | ||
350 | .borrow_mut() | ||
351 | .entry(file_id) | ||
352 | .or_insert_with(|| file_id.expansion_info(self.db.upcast())) | ||
353 | .as_ref()? | ||
354 | .map_token_down(token.as_ref())?; | ||
355 | |||
356 | self.cache(find_root(&token.value.parent()), token.file_id); | ||
357 | |||
358 | Some(token) | ||
359 | }) | ||
360 | .last() | ||
361 | .unwrap(); | ||
362 | |||
363 | token.value | ||
364 | } | ||
365 | |||
366 | fn descend_node_at_offset( | ||
367 | &self, | ||
368 | node: &SyntaxNode, | ||
369 | offset: TextSize, | ||
370 | ) -> impl Iterator<Item = SyntaxNode> + '_ { | ||
371 | // Handle macro token cases | ||
372 | node.token_at_offset(offset) | ||
373 | .map(|token| self.descend_into_macros(token)) | ||
374 | .map(|it| self.ancestors_with_macros(it.parent())) | ||
375 | .flatten() | ||
376 | } | ||
377 | |||
378 | fn original_range(&self, node: &SyntaxNode) -> FileRange { | ||
379 | let node = self.find_file(node.clone()); | ||
380 | original_range(self.db, node.as_ref()) | ||
381 | } | ||
382 | |||
383 | fn diagnostics_display_range(&self, diagnostics: &dyn Diagnostic) -> FileRange { | ||
384 | let src = diagnostics.display_source(); | ||
385 | let root = self.db.parse_or_expand(src.file_id).unwrap(); | ||
386 | let node = src.value.to_node(&root); | ||
387 | self.cache(root, src.file_id); | ||
388 | original_range(self.db, src.with_value(&node)) | ||
389 | } | ||
390 | |||
391 | fn ancestors_with_macros(&self, node: SyntaxNode) -> impl Iterator<Item = SyntaxNode> + '_ { | ||
392 | let node = self.find_file(node); | ||
393 | node.ancestors_with_macros(self.db.upcast()).map(|it| it.value) | ||
394 | } | ||
395 | |||
396 | fn ancestors_at_offset_with_macros( | ||
397 | &self, | ||
398 | node: &SyntaxNode, | ||
399 | offset: TextSize, | ||
400 | ) -> impl Iterator<Item = SyntaxNode> + '_ { | ||
401 | node.token_at_offset(offset) | ||
402 | .map(|token| self.ancestors_with_macros(token.parent())) | ||
403 | .kmerge_by(|node1, node2| node1.text_range().len() < node2.text_range().len()) | ||
404 | } | ||
405 | |||
406 | fn type_of_expr(&self, expr: &ast::Expr) -> Option<Type> { | ||
407 | self.analyze(expr.syntax()).type_of_expr(self.db, &expr) | ||
408 | } | ||
409 | |||
410 | fn type_of_pat(&self, pat: &ast::Pat) -> Option<Type> { | ||
411 | self.analyze(pat.syntax()).type_of_pat(self.db, &pat) | ||
412 | } | ||
413 | |||
414 | fn type_of_self(&self, param: &ast::SelfParam) -> Option<Type> { | ||
415 | self.analyze(param.syntax()).type_of_self(self.db, ¶m) | ||
416 | } | ||
417 | |||
418 | fn resolve_method_call(&self, call: &ast::MethodCallExpr) -> Option<FunctionId> { | ||
419 | self.analyze(call.syntax()).resolve_method_call(self.db, call) | ||
420 | } | ||
421 | |||
422 | fn resolve_method_call_as_callable(&self, call: &ast::MethodCallExpr) -> Option<Callable> { | ||
423 | // FIXME: this erases Substs | ||
424 | let func = self.resolve_method_call(call)?; | ||
425 | let ty = self.db.value_ty(func.into()); | ||
426 | let resolver = self.analyze(call.syntax()).resolver; | ||
427 | let ty = Type::new_with_resolver(self.db, &resolver, ty.value)?; | ||
428 | let mut res = ty.as_callable(self.db)?; | ||
429 | res.is_bound_method = true; | ||
430 | Some(res) | ||
431 | } | ||
432 | |||
433 | fn resolve_field(&self, field: &ast::FieldExpr) -> Option<Field> { | ||
434 | self.analyze(field.syntax()).resolve_field(self.db, field) | ||
435 | } | ||
436 | |||
437 | fn resolve_record_field(&self, field: &ast::RecordExprField) -> Option<(Field, Option<Local>)> { | ||
438 | self.analyze(field.syntax()).resolve_record_field(self.db, field) | ||
439 | } | ||
440 | |||
441 | fn resolve_record_field_pat(&self, field: &ast::RecordPatField) -> Option<Field> { | ||
442 | self.analyze(field.syntax()).resolve_record_field_pat(self.db, field) | ||
443 | } | ||
444 | |||
445 | fn resolve_macro_call(&self, macro_call: &ast::MacroCall) -> Option<MacroDef> { | ||
446 | let sa = self.analyze(macro_call.syntax()); | ||
447 | let macro_call = self.find_file(macro_call.syntax().clone()).with_value(macro_call); | ||
448 | sa.resolve_macro_call(self.db, macro_call) | ||
449 | } | ||
450 | |||
451 | fn resolve_path(&self, path: &ast::Path) -> Option<PathResolution> { | ||
452 | self.analyze(path.syntax()).resolve_path(self.db, path) | ||
453 | } | ||
454 | |||
455 | fn resolve_extern_crate(&self, extern_crate: &ast::ExternCrate) -> Option<Crate> { | ||
456 | let krate = self.scope(extern_crate.syntax()).krate()?; | ||
457 | krate.dependencies(self.db).into_iter().find_map(|dep| { | ||
458 | if dep.name == extern_crate.name_ref()?.as_name() { | ||
459 | Some(dep.krate) | ||
460 | } else { | ||
461 | None | ||
462 | } | ||
463 | }) | ||
464 | } | ||
465 | |||
466 | fn resolve_variant(&self, record_lit: ast::RecordExpr) -> Option<VariantId> { | ||
467 | self.analyze(record_lit.syntax()).resolve_variant(self.db, record_lit) | ||
468 | } | ||
469 | |||
470 | fn lower_path(&self, path: &ast::Path) -> Option<Path> { | ||
471 | let src = self.find_file(path.syntax().clone()); | ||
472 | Path::from_src(path.clone(), &Hygiene::new(self.db.upcast(), src.file_id.into())) | ||
473 | } | ||
474 | |||
475 | fn resolve_bind_pat_to_const(&self, pat: &ast::IdentPat) -> Option<ModuleDef> { | ||
476 | self.analyze(pat.syntax()).resolve_bind_pat_to_const(self.db, pat) | ||
477 | } | ||
478 | |||
479 | fn record_literal_missing_fields(&self, literal: &ast::RecordExpr) -> Vec<(Field, Type)> { | ||
480 | self.analyze(literal.syntax()) | ||
481 | .record_literal_missing_fields(self.db, literal) | ||
482 | .unwrap_or_default() | ||
483 | } | ||
484 | |||
485 | fn record_pattern_missing_fields(&self, pattern: &ast::RecordPat) -> Vec<(Field, Type)> { | ||
486 | self.analyze(pattern.syntax()) | ||
487 | .record_pattern_missing_fields(self.db, pattern) | ||
488 | .unwrap_or_default() | ||
489 | } | ||
490 | |||
491 | fn with_ctx<F: FnOnce(&mut SourceToDefCtx) -> T, T>(&self, f: F) -> T { | ||
492 | let mut cache = self.s2d_cache.borrow_mut(); | ||
493 | let mut ctx = SourceToDefCtx { db: self.db, cache: &mut *cache }; | ||
494 | f(&mut ctx) | ||
495 | } | ||
496 | |||
497 | fn to_module_def(&self, file: FileId) -> Option<Module> { | ||
498 | self.with_ctx(|ctx| ctx.file_to_def(file)).map(Module::from) | ||
499 | } | ||
500 | |||
501 | fn scope(&self, node: &SyntaxNode) -> SemanticsScope<'db> { | ||
502 | let node = self.find_file(node.clone()); | ||
503 | let resolver = self.analyze2(node.as_ref(), None).resolver; | ||
504 | SemanticsScope { db: self.db, file_id: node.file_id, resolver } | ||
505 | } | ||
506 | |||
507 | fn scope_at_offset(&self, node: &SyntaxNode, offset: TextSize) -> SemanticsScope<'db> { | ||
508 | let node = self.find_file(node.clone()); | ||
509 | let resolver = self.analyze2(node.as_ref(), Some(offset)).resolver; | ||
510 | SemanticsScope { db: self.db, file_id: node.file_id, resolver } | ||
511 | } | ||
512 | |||
513 | fn scope_for_def(&self, def: Trait) -> SemanticsScope<'db> { | ||
514 | let file_id = self.db.lookup_intern_trait(def.id).id.file_id; | ||
515 | let resolver = def.id.resolver(self.db.upcast()); | ||
516 | SemanticsScope { db: self.db, file_id, resolver } | ||
517 | } | ||
518 | |||
519 | fn analyze(&self, node: &SyntaxNode) -> SourceAnalyzer { | ||
520 | let src = self.find_file(node.clone()); | ||
521 | self.analyze2(src.as_ref(), None) | ||
522 | } | ||
523 | |||
524 | fn analyze2(&self, src: InFile<&SyntaxNode>, offset: Option<TextSize>) -> SourceAnalyzer { | ||
525 | let _p = profile::span("Semantics::analyze2"); | ||
526 | |||
527 | let container = match self.with_ctx(|ctx| ctx.find_container(src)) { | ||
528 | Some(it) => it, | ||
529 | None => return SourceAnalyzer::new_for_resolver(Resolver::default(), src), | ||
530 | }; | ||
531 | |||
532 | let resolver = match container { | ||
533 | ChildContainer::DefWithBodyId(def) => { | ||
534 | return SourceAnalyzer::new_for_body(self.db, def, src, offset) | ||
535 | } | ||
536 | ChildContainer::TraitId(it) => it.resolver(self.db.upcast()), | ||
537 | ChildContainer::ImplId(it) => it.resolver(self.db.upcast()), | ||
538 | ChildContainer::ModuleId(it) => it.resolver(self.db.upcast()), | ||
539 | ChildContainer::EnumId(it) => it.resolver(self.db.upcast()), | ||
540 | ChildContainer::VariantId(it) => it.resolver(self.db.upcast()), | ||
541 | ChildContainer::TypeAliasId(it) => it.resolver(self.db.upcast()), | ||
542 | ChildContainer::GenericDefId(it) => it.resolver(self.db.upcast()), | ||
543 | }; | ||
544 | SourceAnalyzer::new_for_resolver(resolver, src) | ||
545 | } | ||
546 | |||
547 | fn cache(&self, root_node: SyntaxNode, file_id: HirFileId) { | ||
548 | assert!(root_node.parent().is_none()); | ||
549 | let mut cache = self.cache.borrow_mut(); | ||
550 | let prev = cache.insert(root_node, file_id); | ||
551 | assert!(prev == None || prev == Some(file_id)) | ||
552 | } | ||
553 | |||
554 | fn assert_contains_node(&self, node: &SyntaxNode) { | ||
555 | self.find_file(node.clone()); | ||
556 | } | ||
557 | |||
558 | fn lookup(&self, root_node: &SyntaxNode) -> Option<HirFileId> { | ||
559 | let cache = self.cache.borrow(); | ||
560 | cache.get(root_node).copied() | ||
561 | } | ||
562 | |||
563 | fn find_file(&self, node: SyntaxNode) -> InFile<SyntaxNode> { | ||
564 | let root_node = find_root(&node); | ||
565 | let file_id = self.lookup(&root_node).unwrap_or_else(|| { | ||
566 | panic!( | ||
567 | "\n\nFailed to lookup {:?} in this Semantics.\n\ | ||
568 | Make sure to use only query nodes, derived from this instance of Semantics.\n\ | ||
569 | root node: {:?}\n\ | ||
570 | known nodes: {}\n\n", | ||
571 | node, | ||
572 | root_node, | ||
573 | self.cache | ||
574 | .borrow() | ||
575 | .keys() | ||
576 | .map(|it| format!("{:?}", it)) | ||
577 | .collect::<Vec<_>>() | ||
578 | .join(", ") | ||
579 | ) | ||
580 | }); | ||
581 | InFile::new(file_id, node) | ||
582 | } | ||
583 | |||
584 | pub fn is_unsafe_method_call(&self, method_call_expr: ast::MethodCallExpr) -> bool { | ||
585 | method_call_expr | ||
586 | .expr() | ||
587 | .and_then(|expr| { | ||
588 | let field_expr = if let ast::Expr::FieldExpr(field_expr) = expr { | ||
589 | field_expr | ||
590 | } else { | ||
591 | return None; | ||
592 | }; | ||
593 | let ty = self.type_of_expr(&field_expr.expr()?)?; | ||
594 | if !ty.is_packed(self.db) { | ||
595 | return None; | ||
596 | } | ||
597 | |||
598 | let func = self.resolve_method_call(&method_call_expr).map(Function::from)?; | ||
599 | let is_unsafe = func.has_self_param(self.db) | ||
600 | && matches!(func.params(self.db).first(), Some(TypeRef::Reference(..))); | ||
601 | Some(is_unsafe) | ||
602 | }) | ||
603 | .unwrap_or(false) | ||
604 | } | ||
605 | |||
606 | pub fn is_unsafe_ref_expr(&self, ref_expr: &ast::RefExpr) -> bool { | ||
607 | ref_expr | ||
608 | .expr() | ||
609 | .and_then(|expr| { | ||
610 | let field_expr = match expr { | ||
611 | ast::Expr::FieldExpr(field_expr) => field_expr, | ||
612 | _ => return None, | ||
613 | }; | ||
614 | let expr = field_expr.expr()?; | ||
615 | self.type_of_expr(&expr) | ||
616 | }) | ||
617 | // Binding a reference to a packed type is possibly unsafe. | ||
618 | .map(|ty| ty.is_packed(self.db)) | ||
619 | .unwrap_or(false) | ||
620 | |||
621 | // FIXME This needs layout computation to be correct. It will highlight | ||
622 | // more than it should with the current implementation. | ||
623 | } | ||
624 | |||
625 | pub fn is_unsafe_ident_pat(&self, ident_pat: &ast::IdentPat) -> bool { | ||
626 | if !ident_pat.ref_token().is_some() { | ||
627 | return false; | ||
628 | } | ||
629 | |||
630 | ident_pat | ||
631 | .syntax() | ||
632 | .parent() | ||
633 | .and_then(|parent| { | ||
634 | // `IdentPat` can live under `RecordPat` directly under `RecordPatField` or | ||
635 | // `RecordPatFieldList`. `RecordPatField` also lives under `RecordPatFieldList`, | ||
636 | // so this tries to lookup the `IdentPat` anywhere along that structure to the | ||
637 | // `RecordPat` so we can get the containing type. | ||
638 | let record_pat = ast::RecordPatField::cast(parent.clone()) | ||
639 | .and_then(|record_pat| record_pat.syntax().parent()) | ||
640 | .or_else(|| Some(parent.clone())) | ||
641 | .and_then(|parent| { | ||
642 | ast::RecordPatFieldList::cast(parent)? | ||
643 | .syntax() | ||
644 | .parent() | ||
645 | .and_then(ast::RecordPat::cast) | ||
646 | }); | ||
647 | |||
648 | // If this doesn't match a `RecordPat`, fallback to a `LetStmt` to see if | ||
649 | // this is initialized from a `FieldExpr`. | ||
650 | if let Some(record_pat) = record_pat { | ||
651 | self.type_of_pat(&ast::Pat::RecordPat(record_pat)) | ||
652 | } else if let Some(let_stmt) = ast::LetStmt::cast(parent) { | ||
653 | let field_expr = match let_stmt.initializer()? { | ||
654 | ast::Expr::FieldExpr(field_expr) => field_expr, | ||
655 | _ => return None, | ||
656 | }; | ||
657 | |||
658 | self.type_of_expr(&field_expr.expr()?) | ||
659 | } else { | ||
660 | None | ||
661 | } | ||
662 | }) | ||
663 | // Binding a reference to a packed type is possibly unsafe. | ||
664 | .map(|ty| ty.is_packed(self.db)) | ||
665 | .unwrap_or(false) | ||
666 | } | ||
667 | } | ||
668 | |||
669 | pub trait ToDef: AstNode + Clone { | ||
670 | type Def; | ||
671 | |||
672 | fn to_def(sema: &SemanticsImpl, src: InFile<Self>) -> Option<Self::Def>; | ||
673 | } | ||
674 | |||
675 | macro_rules! to_def_impls { | ||
676 | ($(($def:path, $ast:path, $meth:ident)),* ,) => {$( | ||
677 | impl ToDef for $ast { | ||
678 | type Def = $def; | ||
679 | fn to_def(sema: &SemanticsImpl, src: InFile<Self>) -> Option<Self::Def> { | ||
680 | sema.with_ctx(|ctx| ctx.$meth(src)).map(<$def>::from) | ||
681 | } | ||
682 | } | ||
683 | )*} | ||
684 | } | ||
685 | |||
686 | to_def_impls![ | ||
687 | (crate::Module, ast::Module, module_to_def), | ||
688 | (crate::Struct, ast::Struct, struct_to_def), | ||
689 | (crate::Enum, ast::Enum, enum_to_def), | ||
690 | (crate::Union, ast::Union, union_to_def), | ||
691 | (crate::Trait, ast::Trait, trait_to_def), | ||
692 | (crate::ImplDef, ast::Impl, impl_to_def), | ||
693 | (crate::TypeAlias, ast::TypeAlias, type_alias_to_def), | ||
694 | (crate::Const, ast::Const, const_to_def), | ||
695 | (crate::Static, ast::Static, static_to_def), | ||
696 | (crate::Function, ast::Fn, fn_to_def), | ||
697 | (crate::Field, ast::RecordField, record_field_to_def), | ||
698 | (crate::Field, ast::TupleField, tuple_field_to_def), | ||
699 | (crate::EnumVariant, ast::Variant, enum_variant_to_def), | ||
700 | (crate::TypeParam, ast::TypeParam, type_param_to_def), | ||
701 | (crate::MacroDef, ast::MacroCall, macro_call_to_def), // this one is dubious, not all calls are macros | ||
702 | (crate::Local, ast::IdentPat, bind_pat_to_def), | ||
703 | ]; | ||
704 | |||
705 | fn find_root(node: &SyntaxNode) -> SyntaxNode { | ||
706 | node.ancestors().last().unwrap() | ||
707 | } | ||
708 | |||
709 | #[derive(Debug)] | ||
710 | pub struct SemanticsScope<'a> { | ||
711 | pub db: &'a dyn HirDatabase, | ||
712 | file_id: HirFileId, | ||
713 | resolver: Resolver, | ||
714 | } | ||
715 | |||
716 | impl<'a> SemanticsScope<'a> { | ||
717 | pub fn module(&self) -> Option<Module> { | ||
718 | Some(Module { id: self.resolver.module()? }) | ||
719 | } | ||
720 | |||
721 | pub fn krate(&self) -> Option<Crate> { | ||
722 | Some(Crate { id: self.resolver.krate()? }) | ||
723 | } | ||
724 | |||
725 | /// Note: `FxHashSet<TraitId>` should be treated as an opaque type, passed into `Type | ||
726 | // FIXME: rename to visible_traits to not repeat scope? | ||
727 | pub fn traits_in_scope(&self) -> FxHashSet<TraitId> { | ||
728 | let resolver = &self.resolver; | ||
729 | resolver.traits_in_scope(self.db.upcast()) | ||
730 | } | ||
731 | |||
732 | pub fn process_all_names(&self, f: &mut dyn FnMut(Name, ScopeDef)) { | ||
733 | let resolver = &self.resolver; | ||
734 | |||
735 | resolver.process_all_names(self.db.upcast(), &mut |name, def| { | ||
736 | let def = match def { | ||
737 | resolver::ScopeDef::PerNs(it) => { | ||
738 | let items = ScopeDef::all_items(it); | ||
739 | for item in items { | ||
740 | f(name.clone(), item); | ||
741 | } | ||
742 | return; | ||
743 | } | ||
744 | resolver::ScopeDef::ImplSelfType(it) => ScopeDef::ImplSelfType(it.into()), | ||
745 | resolver::ScopeDef::AdtSelfType(it) => ScopeDef::AdtSelfType(it.into()), | ||
746 | resolver::ScopeDef::GenericParam(id) => ScopeDef::GenericParam(TypeParam { id }), | ||
747 | resolver::ScopeDef::Local(pat_id) => { | ||
748 | let parent = resolver.body_owner().unwrap().into(); | ||
749 | ScopeDef::Local(Local { parent, pat_id }) | ||
750 | } | ||
751 | }; | ||
752 | f(name, def) | ||
753 | }) | ||
754 | } | ||
755 | |||
756 | /// Resolve a path as-if it was written at the given scope. This is | ||
757 | /// necessary a heuristic, as it doesn't take hygiene into account. | ||
758 | pub fn speculative_resolve(&self, path: &ast::Path) -> Option<PathResolution> { | ||
759 | let hygiene = Hygiene::new(self.db.upcast(), self.file_id); | ||
760 | let path = Path::from_src(path.clone(), &hygiene)?; | ||
761 | self.resolve_hir_path(&path) | ||
762 | } | ||
763 | |||
764 | pub fn resolve_hir_path(&self, path: &Path) -> Option<PathResolution> { | ||
765 | resolve_hir_path(self.db, &self.resolver, path) | ||
766 | } | ||
767 | |||
768 | /// Resolves a path where we know it is a qualifier of another path. | ||
769 | /// | ||
770 | /// For example, if we have: | ||
771 | /// ``` | ||
772 | /// mod my { | ||
773 | /// pub mod foo { | ||
774 | /// struct Bar; | ||
775 | /// } | ||
776 | /// | ||
777 | /// pub fn foo() {} | ||
778 | /// } | ||
779 | /// ``` | ||
780 | /// then we know that `foo` in `my::foo::Bar` refers to the module, not the function. | ||
781 | pub fn resolve_hir_path_qualifier(&self, path: &Path) -> Option<PathResolution> { | ||
782 | resolve_hir_path_qualifier(self.db, &self.resolver, path) | ||
783 | } | ||
784 | } | ||
785 | |||
786 | // FIXME: Change `HasSource` trait to work with `Semantics` and remove this? | ||
787 | pub fn original_range(db: &dyn HirDatabase, node: InFile<&SyntaxNode>) -> FileRange { | ||
788 | if let Some(range) = original_range_opt(db, node) { | ||
789 | let original_file = range.file_id.original_file(db.upcast()); | ||
790 | if range.file_id == original_file.into() { | ||
791 | return FileRange { file_id: original_file, range: range.value }; | ||
792 | } | ||
793 | |||
794 | log::error!("Fail to mapping up more for {:?}", range); | ||
795 | return FileRange { file_id: range.file_id.original_file(db.upcast()), range: range.value }; | ||
796 | } | ||
797 | |||
798 | // Fall back to whole macro call | ||
799 | if let Some(expansion) = node.file_id.expansion_info(db.upcast()) { | ||
800 | if let Some(call_node) = expansion.call_node() { | ||
801 | return FileRange { | ||
802 | file_id: call_node.file_id.original_file(db.upcast()), | ||
803 | range: call_node.value.text_range(), | ||
804 | }; | ||
805 | } | ||
806 | } | ||
807 | |||
808 | FileRange { file_id: node.file_id.original_file(db.upcast()), range: node.value.text_range() } | ||
809 | } | ||
810 | |||
811 | fn original_range_opt( | ||
812 | db: &dyn HirDatabase, | ||
813 | node: InFile<&SyntaxNode>, | ||
814 | ) -> Option<InFile<TextRange>> { | ||
815 | let expansion = node.file_id.expansion_info(db.upcast())?; | ||
816 | |||
817 | // the input node has only one token ? | ||
818 | let single = skip_trivia_token(node.value.first_token()?, Direction::Next)? | ||
819 | == skip_trivia_token(node.value.last_token()?, Direction::Prev)?; | ||
820 | |||
821 | Some(node.value.descendants().find_map(|it| { | ||
822 | let first = skip_trivia_token(it.first_token()?, Direction::Next)?; | ||
823 | let first = ascend_call_token(db, &expansion, node.with_value(first))?; | ||
824 | |||
825 | let last = skip_trivia_token(it.last_token()?, Direction::Prev)?; | ||
826 | let last = ascend_call_token(db, &expansion, node.with_value(last))?; | ||
827 | |||
828 | if (!single && first == last) || (first.file_id != last.file_id) { | ||
829 | return None; | ||
830 | } | ||
831 | |||
832 | Some(first.with_value(first.value.text_range().cover(last.value.text_range()))) | ||
833 | })?) | ||
834 | } | ||
835 | |||
836 | fn ascend_call_token( | ||
837 | db: &dyn HirDatabase, | ||
838 | expansion: &ExpansionInfo, | ||
839 | token: InFile<SyntaxToken>, | ||
840 | ) -> Option<InFile<SyntaxToken>> { | ||
841 | let (mapped, origin) = expansion.map_token_up(token.as_ref())?; | ||
842 | if origin != Origin::Call { | ||
843 | return None; | ||
844 | } | ||
845 | if let Some(info) = mapped.file_id.expansion_info(db.upcast()) { | ||
846 | return ascend_call_token(db, &info, mapped); | ||
847 | } | ||
848 | Some(mapped) | ||
849 | } | ||