]> git.lizzy.rs Git - rust.git/blob - crates/hir/src/semantics.rs
Merge #10204
[rust.git] / crates / hir / src / semantics.rs
1 //! See `Semantics`.
2
3 mod source_to_def;
4
5 use std::{cell::RefCell, fmt};
6
7 use base_db::{FileId, FileRange};
8 use hir_def::{
9     body,
10     resolver::{self, HasResolver, Resolver, TypeNs},
11     AsMacroCall, FunctionId, TraitId, VariantId,
12 };
13 use hir_expand::{name::AsName, ExpansionInfo};
14 use hir_ty::{associated_type_shorthand_candidates, Interner};
15 use itertools::Itertools;
16 use rustc_hash::{FxHashMap, FxHashSet};
17 use smallvec::{smallvec, SmallVec};
18 use syntax::{
19     algo::find_node_at_offset,
20     ast::{self, GenericParamsOwner, LoopBodyOwner},
21     match_ast, AstNode, SyntaxNode, SyntaxNodePtr, SyntaxToken, TextRange, TextSize,
22 };
23
24 use crate::{
25     db::HirDatabase,
26     semantics::source_to_def::{ChildContainer, SourceToDefCache, SourceToDefCtx},
27     source_analyzer::{resolve_hir_path, SourceAnalyzer},
28     Access, AssocItem, Callable, ConstParam, Crate, Field, Function, HirFileId, Impl, InFile,
29     Label, LifetimeParam, Local, MacroDef, Module, ModuleDef, Name, Path, ScopeDef, Trait, Type,
30     TypeAlias, TypeParam, VariantDef,
31 };
32
33 #[derive(Debug, Clone, PartialEq, Eq)]
34 pub enum PathResolution {
35     /// An item
36     Def(ModuleDef),
37     /// A local binding (only value namespace)
38     Local(Local),
39     /// A type parameter
40     TypeParam(TypeParam),
41     /// A const parameter
42     ConstParam(ConstParam),
43     SelfType(Impl),
44     Macro(MacroDef),
45     AssocItem(AssocItem),
46 }
47
48 impl PathResolution {
49     fn in_type_ns(&self) -> Option<TypeNs> {
50         match self {
51             PathResolution::Def(ModuleDef::Adt(adt)) => Some(TypeNs::AdtId((*adt).into())),
52             PathResolution::Def(ModuleDef::BuiltinType(builtin)) => {
53                 Some(TypeNs::BuiltinType((*builtin).into()))
54             }
55             PathResolution::Def(
56                 ModuleDef::Const(_)
57                 | ModuleDef::Variant(_)
58                 | ModuleDef::Function(_)
59                 | ModuleDef::Module(_)
60                 | ModuleDef::Static(_)
61                 | ModuleDef::Trait(_),
62             ) => None,
63             PathResolution::Def(ModuleDef::TypeAlias(alias)) => {
64                 Some(TypeNs::TypeAliasId((*alias).into()))
65             }
66             PathResolution::Local(_) | PathResolution::Macro(_) | PathResolution::ConstParam(_) => {
67                 None
68             }
69             PathResolution::TypeParam(param) => Some(TypeNs::GenericParam((*param).into())),
70             PathResolution::SelfType(impl_def) => Some(TypeNs::SelfType((*impl_def).into())),
71             PathResolution::AssocItem(AssocItem::Const(_) | AssocItem::Function(_)) => None,
72             PathResolution::AssocItem(AssocItem::TypeAlias(alias)) => {
73                 Some(TypeNs::TypeAliasId((*alias).into()))
74             }
75         }
76     }
77
78     /// Returns an iterator over associated types that may be specified after this path (using
79     /// `Ty::Assoc` syntax).
80     pub fn assoc_type_shorthand_candidates<R>(
81         &self,
82         db: &dyn HirDatabase,
83         mut cb: impl FnMut(&Name, TypeAlias) -> Option<R>,
84     ) -> Option<R> {
85         associated_type_shorthand_candidates(db, self.in_type_ns()?, |name, _, id| {
86             cb(name, id.into())
87         })
88     }
89 }
90
91 #[derive(Debug)]
92 pub struct TypeInfo {
93     /// The original type of the expression or pattern.
94     pub original: Type,
95     /// The adjusted type, if an adjustment happened.
96     pub adjusted: Option<Type>,
97 }
98
99 impl TypeInfo {
100     pub fn original(self) -> Type {
101         self.original
102     }
103
104     pub fn has_adjustment(&self) -> bool {
105         self.adjusted.is_some()
106     }
107
108     /// The adjusted type, or the original in case no adjustments occurred.
109     pub fn adjusted(self) -> Type {
110         self.adjusted.unwrap_or(self.original)
111     }
112 }
113
114 /// Primary API to get semantic information, like types, from syntax trees.
115 pub struct Semantics<'db, DB> {
116     pub db: &'db DB,
117     imp: SemanticsImpl<'db>,
118 }
119
120 pub struct SemanticsImpl<'db> {
121     pub db: &'db dyn HirDatabase,
122     s2d_cache: RefCell<SourceToDefCache>,
123     expansion_info_cache: RefCell<FxHashMap<HirFileId, Option<ExpansionInfo>>>,
124     cache: RefCell<FxHashMap<SyntaxNode, HirFileId>>,
125 }
126
127 impl<DB> fmt::Debug for Semantics<'_, DB> {
128     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
129         write!(f, "Semantics {{ ... }}")
130     }
131 }
132
133 impl<'db, DB: HirDatabase> Semantics<'db, DB> {
134     pub fn new(db: &DB) -> Semantics<DB> {
135         let impl_ = SemanticsImpl::new(db);
136         Semantics { db, imp: impl_ }
137     }
138
139     pub fn parse(&self, file_id: FileId) -> ast::SourceFile {
140         self.imp.parse(file_id)
141     }
142
143     pub fn expand(&self, macro_call: &ast::MacroCall) -> Option<SyntaxNode> {
144         self.imp.expand(macro_call)
145     }
146
147     /// If `item` has an attribute macro attached to it, expands it.
148     pub fn expand_attr_macro(&self, item: &ast::Item) -> Option<SyntaxNode> {
149         self.imp.expand_attr_macro(item)
150     }
151
152     pub fn expand_derive_macro(&self, derive: &ast::Attr) -> Option<Vec<SyntaxNode>> {
153         self.imp.expand_derive_macro(derive)
154     }
155
156     pub fn is_attr_macro_call(&self, item: &ast::Item) -> bool {
157         self.imp.is_attr_macro_call(item)
158     }
159
160     pub fn speculative_expand(
161         &self,
162         actual_macro_call: &ast::MacroCall,
163         speculative_args: &ast::TokenTree,
164         token_to_map: SyntaxToken,
165     ) -> Option<(SyntaxNode, SyntaxToken)> {
166         self.imp.speculative_expand(actual_macro_call, speculative_args, token_to_map)
167     }
168
169     pub fn speculative_expand_attr_macro(
170         &self,
171         actual_macro_call: &ast::Item,
172         speculative_args: &ast::Item,
173         token_to_map: SyntaxToken,
174     ) -> Option<(SyntaxNode, SyntaxToken)> {
175         self.imp.speculative_expand_attr(actual_macro_call, speculative_args, token_to_map)
176     }
177
178     // FIXME: Rename to descend_into_macros_single
179     pub fn descend_into_macros(&self, token: SyntaxToken) -> SyntaxToken {
180         self.imp.descend_into_macros(token).pop().unwrap()
181     }
182
183     // FIXME: Rename to descend_into_macros
184     pub fn descend_into_macros_many(&self, token: SyntaxToken) -> SmallVec<[SyntaxToken; 1]> {
185         self.imp.descend_into_macros(token)
186     }
187
188     pub fn descend_node_at_offset<N: ast::AstNode>(
189         &self,
190         node: &SyntaxNode,
191         offset: TextSize,
192     ) -> Option<N> {
193         self.imp.descend_node_at_offset(node, offset).flatten().find_map(N::cast)
194     }
195
196     pub fn hir_file_for(&self, syntax_node: &SyntaxNode) -> HirFileId {
197         self.imp.find_file(syntax_node.clone()).file_id
198     }
199
200     pub fn original_range(&self, node: &SyntaxNode) -> FileRange {
201         self.imp.original_range(node)
202     }
203
204     pub fn diagnostics_display_range(&self, diagnostics: InFile<SyntaxNodePtr>) -> FileRange {
205         self.imp.diagnostics_display_range(diagnostics)
206     }
207
208     pub fn token_ancestors_with_macros(
209         &self,
210         token: SyntaxToken,
211     ) -> impl Iterator<Item = SyntaxNode> + '_ {
212         token.parent().into_iter().flat_map(move |it| self.ancestors_with_macros(it))
213     }
214
215     pub fn ancestors_with_macros(&self, node: SyntaxNode) -> impl Iterator<Item = SyntaxNode> + '_ {
216         self.imp.ancestors_with_macros(node)
217     }
218
219     pub fn ancestors_at_offset_with_macros(
220         &self,
221         node: &SyntaxNode,
222         offset: TextSize,
223     ) -> impl Iterator<Item = SyntaxNode> + '_ {
224         self.imp.ancestors_at_offset_with_macros(node, offset)
225     }
226
227     /// Find an AstNode by offset inside SyntaxNode, if it is inside *Macrofile*,
228     /// search up until it is of the target AstNode type
229     pub fn find_node_at_offset_with_macros<N: AstNode>(
230         &self,
231         node: &SyntaxNode,
232         offset: TextSize,
233     ) -> Option<N> {
234         self.imp.ancestors_at_offset_with_macros(node, offset).find_map(N::cast)
235     }
236
237     /// Find an AstNode by offset inside SyntaxNode, if it is inside *MacroCall*,
238     /// descend it and find again
239     pub fn find_node_at_offset_with_descend<N: AstNode>(
240         &self,
241         node: &SyntaxNode,
242         offset: TextSize,
243     ) -> Option<N> {
244         if let Some(it) = find_node_at_offset(node, offset) {
245             return Some(it);
246         }
247
248         self.imp.descend_node_at_offset(node, offset).flatten().find_map(N::cast)
249     }
250
251     /// Find an AstNode by offset inside SyntaxNode, if it is inside *MacroCall*,
252     /// descend it and find again
253     pub fn find_nodes_at_offset_with_descend<'slf, N: AstNode + 'slf>(
254         &'slf self,
255         node: &SyntaxNode,
256         offset: TextSize,
257     ) -> impl Iterator<Item = N> + 'slf {
258         self.imp.descend_node_at_offset(node, offset).filter_map(|mut it| it.find_map(N::cast))
259     }
260
261     pub fn resolve_lifetime_param(&self, lifetime: &ast::Lifetime) -> Option<LifetimeParam> {
262         self.imp.resolve_lifetime_param(lifetime)
263     }
264
265     pub fn resolve_label(&self, lifetime: &ast::Lifetime) -> Option<Label> {
266         self.imp.resolve_label(lifetime)
267     }
268
269     pub fn resolve_type(&self, ty: &ast::Type) -> Option<Type> {
270         self.imp.resolve_type(ty)
271     }
272
273     pub fn type_of_expr(&self, expr: &ast::Expr) -> Option<TypeInfo> {
274         self.imp.type_of_expr(expr)
275     }
276
277     pub fn type_of_pat(&self, pat: &ast::Pat) -> Option<TypeInfo> {
278         self.imp.type_of_pat(pat)
279     }
280
281     pub fn type_of_self(&self, param: &ast::SelfParam) -> Option<Type> {
282         self.imp.type_of_self(param)
283     }
284
285     pub fn resolve_method_call(&self, call: &ast::MethodCallExpr) -> Option<Function> {
286         self.imp.resolve_method_call(call).map(Function::from)
287     }
288
289     pub fn resolve_method_call_as_callable(&self, call: &ast::MethodCallExpr) -> Option<Callable> {
290         self.imp.resolve_method_call_as_callable(call)
291     }
292
293     pub fn resolve_field(&self, field: &ast::FieldExpr) -> Option<Field> {
294         self.imp.resolve_field(field)
295     }
296
297     pub fn resolve_record_field(
298         &self,
299         field: &ast::RecordExprField,
300     ) -> Option<(Field, Option<Local>, Type)> {
301         self.imp.resolve_record_field(field)
302     }
303
304     pub fn resolve_record_pat_field(&self, field: &ast::RecordPatField) -> Option<Field> {
305         self.imp.resolve_record_pat_field(field)
306     }
307
308     pub fn resolve_macro_call(&self, macro_call: &ast::MacroCall) -> Option<MacroDef> {
309         self.imp.resolve_macro_call(macro_call)
310     }
311
312     pub fn resolve_attr_macro_call(&self, item: &ast::Item) -> Option<MacroDef> {
313         self.imp.resolve_attr_macro_call(item)
314     }
315
316     pub fn resolve_path(&self, path: &ast::Path) -> Option<PathResolution> {
317         self.imp.resolve_path(path)
318     }
319
320     pub fn resolve_extern_crate(&self, extern_crate: &ast::ExternCrate) -> Option<Crate> {
321         self.imp.resolve_extern_crate(extern_crate)
322     }
323
324     pub fn resolve_variant(&self, record_lit: ast::RecordExpr) -> Option<VariantDef> {
325         self.imp.resolve_variant(record_lit).map(VariantDef::from)
326     }
327
328     pub fn resolve_bind_pat_to_const(&self, pat: &ast::IdentPat) -> Option<ModuleDef> {
329         self.imp.resolve_bind_pat_to_const(pat)
330     }
331
332     // FIXME: use this instead?
333     // pub fn resolve_name_ref(&self, name_ref: &ast::NameRef) -> Option<???>;
334
335     pub fn record_literal_missing_fields(&self, literal: &ast::RecordExpr) -> Vec<(Field, Type)> {
336         self.imp.record_literal_missing_fields(literal)
337     }
338
339     pub fn record_pattern_missing_fields(&self, pattern: &ast::RecordPat) -> Vec<(Field, Type)> {
340         self.imp.record_pattern_missing_fields(pattern)
341     }
342
343     pub fn to_def<T: ToDef>(&self, src: &T) -> Option<T::Def> {
344         let src = self.imp.find_file(src.syntax().clone()).with_value(src).cloned();
345         T::to_def(&self.imp, src)
346     }
347
348     pub fn to_module_def(&self, file: FileId) -> Option<Module> {
349         self.imp.to_module_def(file).next()
350     }
351
352     pub fn to_module_defs(&self, file: FileId) -> impl Iterator<Item = Module> {
353         self.imp.to_module_def(file)
354     }
355
356     pub fn scope(&self, node: &SyntaxNode) -> SemanticsScope<'db> {
357         self.imp.scope(node)
358     }
359
360     pub fn scope_at_offset(&self, token: &SyntaxToken, offset: TextSize) -> SemanticsScope<'db> {
361         self.imp.scope_at_offset(&token.parent().unwrap(), offset)
362     }
363
364     pub fn scope_for_def(&self, def: Trait) -> SemanticsScope<'db> {
365         self.imp.scope_for_def(def)
366     }
367
368     pub fn assert_contains_node(&self, node: &SyntaxNode) {
369         self.imp.assert_contains_node(node)
370     }
371
372     pub fn is_unsafe_method_call(&self, method_call_expr: &ast::MethodCallExpr) -> bool {
373         self.imp.is_unsafe_method_call(method_call_expr)
374     }
375
376     pub fn is_unsafe_ref_expr(&self, ref_expr: &ast::RefExpr) -> bool {
377         self.imp.is_unsafe_ref_expr(ref_expr)
378     }
379
380     pub fn is_unsafe_ident_pat(&self, ident_pat: &ast::IdentPat) -> bool {
381         self.imp.is_unsafe_ident_pat(ident_pat)
382     }
383 }
384
385 impl<'db> SemanticsImpl<'db> {
386     fn new(db: &'db dyn HirDatabase) -> Self {
387         SemanticsImpl {
388             db,
389             s2d_cache: Default::default(),
390             cache: Default::default(),
391             expansion_info_cache: Default::default(),
392         }
393     }
394
395     fn parse(&self, file_id: FileId) -> ast::SourceFile {
396         let tree = self.db.parse(file_id).tree();
397         self.cache(tree.syntax().clone(), file_id.into());
398         tree
399     }
400
401     fn expand(&self, macro_call: &ast::MacroCall) -> Option<SyntaxNode> {
402         let sa = self.analyze(macro_call.syntax());
403         let file_id = sa.expand(self.db, InFile::new(sa.file_id, macro_call))?;
404         let node = self.db.parse_or_expand(file_id)?;
405         self.cache(node.clone(), file_id);
406         Some(node)
407     }
408
409     fn expand_attr_macro(&self, item: &ast::Item) -> Option<SyntaxNode> {
410         let sa = self.analyze(item.syntax());
411         let src = InFile::new(sa.file_id, item.clone());
412         let macro_call_id = self.with_ctx(|ctx| ctx.item_to_macro_call(src))?;
413         let file_id = macro_call_id.as_file();
414         let node = self.db.parse_or_expand(file_id)?;
415         self.cache(node.clone(), file_id);
416         Some(node)
417     }
418
419     fn expand_derive_macro(&self, attr: &ast::Attr) -> Option<Vec<SyntaxNode>> {
420         let item = attr.syntax().parent().and_then(ast::Item::cast)?;
421         let sa = self.analyze(item.syntax());
422         let item = InFile::new(sa.file_id, &item);
423         let src = InFile::new(sa.file_id, attr.clone());
424         self.with_ctx(|ctx| {
425             let macro_call_ids = ctx.attr_to_derive_macro_call(item, src)?;
426
427             let expansions: Vec<_> = macro_call_ids
428                 .iter()
429                 .map(|call| call.as_file())
430                 .flat_map(|file_id| {
431                     let node = self.db.parse_or_expand(file_id)?;
432                     self.cache(node.clone(), file_id);
433                     Some(node)
434                 })
435                 .collect();
436             if expansions.is_empty() {
437                 None
438             } else {
439                 Some(expansions)
440             }
441         })
442     }
443
444     fn is_attr_macro_call(&self, item: &ast::Item) -> bool {
445         let sa = self.analyze(item.syntax());
446         let src = InFile::new(sa.file_id, item.clone());
447         self.with_ctx(|ctx| ctx.item_to_macro_call(src).is_some())
448     }
449
450     fn speculative_expand(
451         &self,
452         actual_macro_call: &ast::MacroCall,
453         speculative_args: &ast::TokenTree,
454         token_to_map: SyntaxToken,
455     ) -> Option<(SyntaxNode, SyntaxToken)> {
456         let sa = self.analyze(actual_macro_call.syntax());
457         let macro_call = InFile::new(sa.file_id, actual_macro_call);
458         let krate = sa.resolver.krate()?;
459         let macro_call_id = macro_call.as_call_id(self.db.upcast(), krate, |path| {
460             sa.resolver.resolve_path_as_macro(self.db.upcast(), &path)
461         })?;
462         hir_expand::db::expand_speculative(
463             self.db.upcast(),
464             macro_call_id,
465             speculative_args.syntax(),
466             token_to_map,
467         )
468     }
469
470     fn speculative_expand_attr(
471         &self,
472         actual_macro_call: &ast::Item,
473         speculative_args: &ast::Item,
474         token_to_map: SyntaxToken,
475     ) -> Option<(SyntaxNode, SyntaxToken)> {
476         let sa = self.analyze(actual_macro_call.syntax());
477         let macro_call = InFile::new(sa.file_id, actual_macro_call.clone());
478         let macro_call_id = self.with_ctx(|ctx| ctx.item_to_macro_call(macro_call))?;
479         hir_expand::db::expand_speculative(
480             self.db.upcast(),
481             macro_call_id,
482             speculative_args.syntax(),
483             token_to_map,
484         )
485     }
486
487     fn descend_into_macros(&self, token: SyntaxToken) -> SmallVec<[SyntaxToken; 1]> {
488         let _p = profile::span("descend_into_macros");
489         let parent = match token.parent() {
490             Some(it) => it,
491             None => return smallvec![token],
492         };
493         let sa = self.analyze(&parent);
494         let mut queue = vec![InFile::new(sa.file_id, token)];
495         let mut cache = self.expansion_info_cache.borrow_mut();
496         let mut res = smallvec![];
497         // Remap the next token in the queue into a macro call its in, if it is not being remapped
498         // either due to not being in a macro-call or because its unused push it into the result vec,
499         // otherwise push the remapped tokens back into the queue as they can potentially be remapped again.
500         while let Some(token) = queue.pop() {
501             self.db.unwind_if_cancelled();
502             let was_not_remapped = (|| {
503                 if let Some((call_id, item)) = token
504                     .value
505                     .ancestors()
506                     .filter_map(ast::Item::cast)
507                     .filter_map(|item| {
508                         self.with_ctx(|ctx| ctx.item_to_macro_call(token.with_value(item.clone())))
509                             .zip(Some(item))
510                     })
511                     .last()
512                 {
513                     let file_id = call_id.as_file();
514                     let tokens = cache
515                         .entry(file_id)
516                         .or_insert_with(|| file_id.expansion_info(self.db.upcast()))
517                         .as_ref()?
518                         .map_token_down(self.db.upcast(), Some(item), token.as_ref())?;
519
520                     let len = queue.len();
521                     queue.extend(tokens.inspect(|token| {
522                         if let Some(parent) = token.value.parent() {
523                             self.cache(find_root(&parent), token.file_id);
524                         }
525                     }));
526                     return (queue.len() != len).then(|| ());
527                 }
528
529                 if let Some(macro_call) = token.value.ancestors().find_map(ast::MacroCall::cast) {
530                     let tt = macro_call.token_tree()?;
531                     let l_delim = match tt.left_delimiter_token() {
532                         Some(it) => it.text_range().end(),
533                         None => tt.syntax().text_range().start(),
534                     };
535                     let r_delim = match tt.right_delimiter_token() {
536                         Some(it) => it.text_range().start(),
537                         None => tt.syntax().text_range().end(),
538                     };
539                     if !TextRange::new(l_delim, r_delim).contains_range(token.value.text_range()) {
540                         return None;
541                     }
542                     let file_id = sa.expand(self.db, token.with_value(&macro_call))?;
543                     let tokens = cache
544                         .entry(file_id)
545                         .or_insert_with(|| file_id.expansion_info(self.db.upcast()))
546                         .as_ref()?
547                         .map_token_down(self.db.upcast(), None, token.as_ref())?;
548
549                     let len = queue.len();
550                     queue.extend(tokens.inspect(|token| {
551                         if let Some(parent) = token.value.parent() {
552                             self.cache(find_root(&parent), token.file_id);
553                         }
554                     }));
555                     return (queue.len() != len).then(|| ());
556                 }
557                 None
558             })()
559             .is_none();
560
561             if was_not_remapped {
562                 res.push(token.value)
563             }
564         }
565         res
566     }
567
568     // Note this return type is deliberate as [`find_nodes_at_offset_with_descend`] wants to stop
569     // traversing the inner iterator when it finds a node.
570     fn descend_node_at_offset(
571         &self,
572         node: &SyntaxNode,
573         offset: TextSize,
574     ) -> impl Iterator<Item = impl Iterator<Item = SyntaxNode> + '_> + '_ {
575         // Handle macro token cases
576         node.token_at_offset(offset)
577             .map(move |token| self.descend_into_macros(token))
578             .map(|it| it.into_iter().map(move |it| self.token_ancestors_with_macros(it)))
579             .flatten()
580     }
581
582     fn original_range(&self, node: &SyntaxNode) -> FileRange {
583         let node = self.find_file(node.clone());
584         node.as_ref().original_file_range(self.db.upcast())
585     }
586
587     fn diagnostics_display_range(&self, src: InFile<SyntaxNodePtr>) -> FileRange {
588         let root = self.db.parse_or_expand(src.file_id).unwrap();
589         let node = src.value.to_node(&root);
590         self.cache(root, src.file_id);
591         src.with_value(&node).original_file_range(self.db.upcast())
592     }
593
594     fn token_ancestors_with_macros(
595         &self,
596         token: SyntaxToken,
597     ) -> impl Iterator<Item = SyntaxNode> + '_ {
598         token.parent().into_iter().flat_map(move |parent| self.ancestors_with_macros(parent))
599     }
600
601     fn ancestors_with_macros(&self, node: SyntaxNode) -> impl Iterator<Item = SyntaxNode> + '_ {
602         let node = self.find_file(node);
603         node.ancestors_with_macros(self.db.upcast()).map(|it| it.value)
604     }
605
606     fn ancestors_at_offset_with_macros(
607         &self,
608         node: &SyntaxNode,
609         offset: TextSize,
610     ) -> impl Iterator<Item = SyntaxNode> + '_ {
611         node.token_at_offset(offset)
612             .map(|token| self.token_ancestors_with_macros(token))
613             .kmerge_by(|node1, node2| node1.text_range().len() < node2.text_range().len())
614     }
615
616     fn resolve_lifetime_param(&self, lifetime: &ast::Lifetime) -> Option<LifetimeParam> {
617         let text = lifetime.text();
618         let lifetime_param = lifetime.syntax().ancestors().find_map(|syn| {
619             let gpl = match_ast! {
620                 match syn {
621                     ast::Fn(it) => it.generic_param_list()?,
622                     ast::TypeAlias(it) => it.generic_param_list()?,
623                     ast::Struct(it) => it.generic_param_list()?,
624                     ast::Enum(it) => it.generic_param_list()?,
625                     ast::Union(it) => it.generic_param_list()?,
626                     ast::Trait(it) => it.generic_param_list()?,
627                     ast::Impl(it) => it.generic_param_list()?,
628                     ast::WherePred(it) => it.generic_param_list()?,
629                     ast::ForType(it) => it.generic_param_list()?,
630                     _ => return None,
631                 }
632             };
633             gpl.lifetime_params()
634                 .find(|tp| tp.lifetime().as_ref().map(|lt| lt.text()).as_ref() == Some(&text))
635         })?;
636         let src = self.find_file(lifetime_param.syntax().clone()).with_value(lifetime_param);
637         ToDef::to_def(self, src)
638     }
639
640     fn resolve_label(&self, lifetime: &ast::Lifetime) -> Option<Label> {
641         let text = lifetime.text();
642         let label = lifetime.syntax().ancestors().find_map(|syn| {
643             let label = match_ast! {
644                 match syn {
645                     ast::ForExpr(it) => it.label(),
646                     ast::WhileExpr(it) => it.label(),
647                     ast::LoopExpr(it) => it.label(),
648                     ast::EffectExpr(it) => it.label(),
649                     _ => None,
650                 }
651             };
652             label.filter(|l| {
653                 l.lifetime()
654                     .and_then(|lt| lt.lifetime_ident_token())
655                     .map_or(false, |lt| lt.text() == text)
656             })
657         })?;
658         let src = self.find_file(label.syntax().clone()).with_value(label);
659         ToDef::to_def(self, src)
660     }
661
662     fn resolve_type(&self, ty: &ast::Type) -> Option<Type> {
663         let scope = self.scope(ty.syntax());
664         let ctx = body::LowerCtx::new(self.db.upcast(), scope.file_id);
665         let ty = hir_ty::TyLoweringContext::new(self.db, &scope.resolver)
666             .lower_ty(&crate::TypeRef::from_ast(&ctx, ty.clone()));
667         Type::new_with_resolver(self.db, &scope.resolver, ty)
668     }
669
670     fn type_of_expr(&self, expr: &ast::Expr) -> Option<TypeInfo> {
671         self.analyze(expr.syntax())
672             .type_of_expr(self.db, expr)
673             .map(|(ty, coerced)| TypeInfo { original: ty, adjusted: coerced })
674     }
675
676     fn type_of_pat(&self, pat: &ast::Pat) -> Option<TypeInfo> {
677         self.analyze(pat.syntax())
678             .type_of_pat(self.db, pat)
679             .map(|(ty, coerced)| TypeInfo { original: ty, adjusted: coerced })
680     }
681
682     fn type_of_self(&self, param: &ast::SelfParam) -> Option<Type> {
683         self.analyze(param.syntax()).type_of_self(self.db, param)
684     }
685
686     fn resolve_method_call(&self, call: &ast::MethodCallExpr) -> Option<FunctionId> {
687         self.analyze(call.syntax()).resolve_method_call(self.db, call).map(|(id, _)| id)
688     }
689
690     fn resolve_method_call_as_callable(&self, call: &ast::MethodCallExpr) -> Option<Callable> {
691         let (func, subst) = self.analyze(call.syntax()).resolve_method_call(self.db, call)?;
692         let ty = self.db.value_ty(func.into()).substitute(&Interner, &subst);
693         let resolver = self.analyze(call.syntax()).resolver;
694         let ty = Type::new_with_resolver(self.db, &resolver, ty)?;
695         let mut res = ty.as_callable(self.db)?;
696         res.is_bound_method = true;
697         Some(res)
698     }
699
700     fn resolve_field(&self, field: &ast::FieldExpr) -> Option<Field> {
701         self.analyze(field.syntax()).resolve_field(self.db, field)
702     }
703
704     fn resolve_record_field(
705         &self,
706         field: &ast::RecordExprField,
707     ) -> Option<(Field, Option<Local>, Type)> {
708         self.analyze(field.syntax()).resolve_record_field(self.db, field)
709     }
710
711     fn resolve_record_pat_field(&self, field: &ast::RecordPatField) -> Option<Field> {
712         self.analyze(field.syntax()).resolve_record_pat_field(self.db, field)
713     }
714
715     fn resolve_macro_call(&self, macro_call: &ast::MacroCall) -> Option<MacroDef> {
716         let sa = self.analyze(macro_call.syntax());
717         let macro_call = self.find_file(macro_call.syntax().clone()).with_value(macro_call);
718         sa.resolve_macro_call(self.db, macro_call)
719     }
720
721     fn resolve_attr_macro_call(&self, item: &ast::Item) -> Option<MacroDef> {
722         let item_in_file = self.find_file(item.syntax().clone()).with_value(item.clone());
723         let macro_call_id = self.with_ctx(|ctx| ctx.item_to_macro_call(item_in_file))?;
724         Some(MacroDef { id: self.db.lookup_intern_macro(macro_call_id).def })
725     }
726
727     fn resolve_path(&self, path: &ast::Path) -> Option<PathResolution> {
728         self.analyze(path.syntax()).resolve_path(self.db, path)
729     }
730
731     fn resolve_extern_crate(&self, extern_crate: &ast::ExternCrate) -> Option<Crate> {
732         let krate = self.scope(extern_crate.syntax()).krate()?;
733         krate.dependencies(self.db).into_iter().find_map(|dep| {
734             if dep.name == extern_crate.name_ref()?.as_name() {
735                 Some(dep.krate)
736             } else {
737                 None
738             }
739         })
740     }
741
742     fn resolve_variant(&self, record_lit: ast::RecordExpr) -> Option<VariantId> {
743         self.analyze(record_lit.syntax()).resolve_variant(self.db, record_lit)
744     }
745
746     fn resolve_bind_pat_to_const(&self, pat: &ast::IdentPat) -> Option<ModuleDef> {
747         self.analyze(pat.syntax()).resolve_bind_pat_to_const(self.db, pat)
748     }
749
750     fn record_literal_missing_fields(&self, literal: &ast::RecordExpr) -> Vec<(Field, Type)> {
751         self.analyze(literal.syntax())
752             .record_literal_missing_fields(self.db, literal)
753             .unwrap_or_default()
754     }
755
756     fn record_pattern_missing_fields(&self, pattern: &ast::RecordPat) -> Vec<(Field, Type)> {
757         self.analyze(pattern.syntax())
758             .record_pattern_missing_fields(self.db, pattern)
759             .unwrap_or_default()
760     }
761
762     fn with_ctx<F: FnOnce(&mut SourceToDefCtx) -> T, T>(&self, f: F) -> T {
763         let mut cache = self.s2d_cache.borrow_mut();
764         let mut ctx = SourceToDefCtx { db: self.db, cache: &mut *cache };
765         f(&mut ctx)
766     }
767
768     fn to_module_def(&self, file: FileId) -> impl Iterator<Item = Module> {
769         self.with_ctx(|ctx| ctx.file_to_def(file)).into_iter().map(Module::from)
770     }
771
772     fn scope(&self, node: &SyntaxNode) -> SemanticsScope<'db> {
773         let sa = self.analyze(node);
774         SemanticsScope { db: self.db, file_id: sa.file_id, resolver: sa.resolver }
775     }
776
777     fn scope_at_offset(&self, node: &SyntaxNode, offset: TextSize) -> SemanticsScope<'db> {
778         let sa = self.analyze_with_offset(node, offset);
779         SemanticsScope { db: self.db, file_id: sa.file_id, resolver: sa.resolver }
780     }
781
782     fn scope_for_def(&self, def: Trait) -> SemanticsScope<'db> {
783         let file_id = self.db.lookup_intern_trait(def.id).id.file_id();
784         let resolver = def.id.resolver(self.db.upcast());
785         SemanticsScope { db: self.db, file_id, resolver }
786     }
787
788     fn analyze(&self, node: &SyntaxNode) -> SourceAnalyzer {
789         self.analyze_impl(node, None)
790     }
791     fn analyze_with_offset(&self, node: &SyntaxNode, offset: TextSize) -> SourceAnalyzer {
792         self.analyze_impl(node, Some(offset))
793     }
794     fn analyze_impl(&self, node: &SyntaxNode, offset: Option<TextSize>) -> SourceAnalyzer {
795         let _p = profile::span("Semantics::analyze_impl");
796         let node = self.find_file(node.clone());
797         let node = node.as_ref();
798
799         let container = match self.with_ctx(|ctx| ctx.find_container(node)) {
800             Some(it) => it,
801             None => return SourceAnalyzer::new_for_resolver(Resolver::default(), node),
802         };
803
804         let resolver = match container {
805             ChildContainer::DefWithBodyId(def) => {
806                 return SourceAnalyzer::new_for_body(self.db, def, node, offset)
807             }
808             ChildContainer::TraitId(it) => it.resolver(self.db.upcast()),
809             ChildContainer::ImplId(it) => it.resolver(self.db.upcast()),
810             ChildContainer::ModuleId(it) => it.resolver(self.db.upcast()),
811             ChildContainer::EnumId(it) => it.resolver(self.db.upcast()),
812             ChildContainer::VariantId(it) => it.resolver(self.db.upcast()),
813             ChildContainer::TypeAliasId(it) => it.resolver(self.db.upcast()),
814             ChildContainer::GenericDefId(it) => it.resolver(self.db.upcast()),
815         };
816         SourceAnalyzer::new_for_resolver(resolver, node)
817     }
818
819     fn cache(&self, root_node: SyntaxNode, file_id: HirFileId) {
820         assert!(root_node.parent().is_none());
821         let mut cache = self.cache.borrow_mut();
822         let prev = cache.insert(root_node, file_id);
823         assert!(prev == None || prev == Some(file_id))
824     }
825
826     fn assert_contains_node(&self, node: &SyntaxNode) {
827         self.find_file(node.clone());
828     }
829
830     fn lookup(&self, root_node: &SyntaxNode) -> Option<HirFileId> {
831         let cache = self.cache.borrow();
832         cache.get(root_node).copied()
833     }
834
835     fn find_file(&self, node: SyntaxNode) -> InFile<SyntaxNode> {
836         let root_node = find_root(&node);
837         let file_id = self.lookup(&root_node).unwrap_or_else(|| {
838             panic!(
839                 "\n\nFailed to lookup {:?} in this Semantics.\n\
840                  Make sure to use only query nodes, derived from this instance of Semantics.\n\
841                  root node:   {:?}\n\
842                  known nodes: {}\n\n",
843                 node,
844                 root_node,
845                 self.cache
846                     .borrow()
847                     .keys()
848                     .map(|it| format!("{:?}", it))
849                     .collect::<Vec<_>>()
850                     .join(", ")
851             )
852         });
853         InFile::new(file_id, node)
854     }
855
856     fn is_unsafe_method_call(&self, method_call_expr: &ast::MethodCallExpr) -> bool {
857         method_call_expr
858             .receiver()
859             .and_then(|expr| {
860                 let field_expr = match expr {
861                     ast::Expr::FieldExpr(field_expr) => field_expr,
862                     _ => return None,
863                 };
864                 let ty = self.type_of_expr(&field_expr.expr()?)?.original;
865                 if !ty.is_packed(self.db) {
866                     return None;
867                 }
868
869                 let func = self.resolve_method_call(method_call_expr).map(Function::from)?;
870                 let res = match func.self_param(self.db)?.access(self.db) {
871                     Access::Shared | Access::Exclusive => true,
872                     Access::Owned => false,
873                 };
874                 Some(res)
875             })
876             .unwrap_or(false)
877     }
878
879     fn is_unsafe_ref_expr(&self, ref_expr: &ast::RefExpr) -> bool {
880         ref_expr
881             .expr()
882             .and_then(|expr| {
883                 let field_expr = match expr {
884                     ast::Expr::FieldExpr(field_expr) => field_expr,
885                     _ => return None,
886                 };
887                 let expr = field_expr.expr()?;
888                 self.type_of_expr(&expr)
889             })
890             // Binding a reference to a packed type is possibly unsafe.
891             .map(|ty| ty.original.is_packed(self.db))
892             .unwrap_or(false)
893
894         // FIXME This needs layout computation to be correct. It will highlight
895         // more than it should with the current implementation.
896     }
897
898     fn is_unsafe_ident_pat(&self, ident_pat: &ast::IdentPat) -> bool {
899         if ident_pat.ref_token().is_none() {
900             return false;
901         }
902
903         ident_pat
904             .syntax()
905             .parent()
906             .and_then(|parent| {
907                 // `IdentPat` can live under `RecordPat` directly under `RecordPatField` or
908                 // `RecordPatFieldList`. `RecordPatField` also lives under `RecordPatFieldList`,
909                 // so this tries to lookup the `IdentPat` anywhere along that structure to the
910                 // `RecordPat` so we can get the containing type.
911                 let record_pat = ast::RecordPatField::cast(parent.clone())
912                     .and_then(|record_pat| record_pat.syntax().parent())
913                     .or_else(|| Some(parent.clone()))
914                     .and_then(|parent| {
915                         ast::RecordPatFieldList::cast(parent)?
916                             .syntax()
917                             .parent()
918                             .and_then(ast::RecordPat::cast)
919                     });
920
921                 // If this doesn't match a `RecordPat`, fallback to a `LetStmt` to see if
922                 // this is initialized from a `FieldExpr`.
923                 if let Some(record_pat) = record_pat {
924                     self.type_of_pat(&ast::Pat::RecordPat(record_pat))
925                 } else if let Some(let_stmt) = ast::LetStmt::cast(parent) {
926                     let field_expr = match let_stmt.initializer()? {
927                         ast::Expr::FieldExpr(field_expr) => field_expr,
928                         _ => return None,
929                     };
930
931                     self.type_of_expr(&field_expr.expr()?)
932                 } else {
933                     None
934                 }
935             })
936             // Binding a reference to a packed type is possibly unsafe.
937             .map(|ty| ty.original.is_packed(self.db))
938             .unwrap_or(false)
939     }
940 }
941
942 pub trait ToDef: AstNode + Clone {
943     type Def;
944
945     fn to_def(sema: &SemanticsImpl, src: InFile<Self>) -> Option<Self::Def>;
946 }
947
948 macro_rules! to_def_impls {
949     ($(($def:path, $ast:path, $meth:ident)),* ,) => {$(
950         impl ToDef for $ast {
951             type Def = $def;
952             fn to_def(sema: &SemanticsImpl, src: InFile<Self>) -> Option<Self::Def> {
953                 sema.with_ctx(|ctx| ctx.$meth(src)).map(<$def>::from)
954             }
955         }
956     )*}
957 }
958
959 to_def_impls![
960     (crate::Module, ast::Module, module_to_def),
961     (crate::Module, ast::SourceFile, source_file_to_def),
962     (crate::Struct, ast::Struct, struct_to_def),
963     (crate::Enum, ast::Enum, enum_to_def),
964     (crate::Union, ast::Union, union_to_def),
965     (crate::Trait, ast::Trait, trait_to_def),
966     (crate::Impl, ast::Impl, impl_to_def),
967     (crate::TypeAlias, ast::TypeAlias, type_alias_to_def),
968     (crate::Const, ast::Const, const_to_def),
969     (crate::Static, ast::Static, static_to_def),
970     (crate::Function, ast::Fn, fn_to_def),
971     (crate::Field, ast::RecordField, record_field_to_def),
972     (crate::Field, ast::TupleField, tuple_field_to_def),
973     (crate::Variant, ast::Variant, enum_variant_to_def),
974     (crate::TypeParam, ast::TypeParam, type_param_to_def),
975     (crate::LifetimeParam, ast::LifetimeParam, lifetime_param_to_def),
976     (crate::ConstParam, ast::ConstParam, const_param_to_def),
977     (crate::MacroDef, ast::Macro, macro_to_def),
978     (crate::Local, ast::IdentPat, bind_pat_to_def),
979     (crate::Local, ast::SelfParam, self_param_to_def),
980     (crate::Label, ast::Label, label_to_def),
981     (crate::Adt, ast::Adt, adt_to_def),
982 ];
983
984 fn find_root(node: &SyntaxNode) -> SyntaxNode {
985     node.ancestors().last().unwrap()
986 }
987
988 /// `SemanticScope` encapsulates the notion of a scope (the set of visible
989 /// names) at a particular program point.
990 ///
991 /// It is a bit tricky, as scopes do not really exist inside the compiler.
992 /// Rather, the compiler directly computes for each reference the definition it
993 /// refers to. It might transiently compute the explicit scope map while doing
994 /// so, but, generally, this is not something left after the analysis.
995 ///
996 /// However, we do very much need explicit scopes for IDE purposes --
997 /// completion, at its core, lists the contents of the current scope. The notion
998 /// of scope is also useful to answer questions like "what would be the meaning
999 /// of this piece of code if we inserted it into this position?".
1000 ///
1001 /// So `SemanticsScope` is constructed from a specific program point (a syntax
1002 /// node or just a raw offset) and provides access to the set of visible names
1003 /// on a somewhat best-effort basis.
1004 ///
1005 /// Note that if you are wondering "what does this specific existing name mean?",
1006 /// you'd better use the `resolve_` family of methods.
1007 #[derive(Debug)]
1008 pub struct SemanticsScope<'a> {
1009     pub db: &'a dyn HirDatabase,
1010     file_id: HirFileId,
1011     resolver: Resolver,
1012 }
1013
1014 impl<'a> SemanticsScope<'a> {
1015     pub fn module(&self) -> Option<Module> {
1016         Some(Module { id: self.resolver.module()? })
1017     }
1018
1019     pub fn krate(&self) -> Option<Crate> {
1020         Some(Crate { id: self.resolver.krate()? })
1021     }
1022
1023     /// Note: `FxHashSet<TraitId>` should be treated as an opaque type, passed into `Type
1024     // FIXME: rename to visible_traits to not repeat scope?
1025     pub fn traits_in_scope(&self) -> FxHashSet<TraitId> {
1026         let resolver = &self.resolver;
1027         resolver.traits_in_scope(self.db.upcast())
1028     }
1029
1030     pub fn process_all_names(&self, f: &mut dyn FnMut(Name, ScopeDef)) {
1031         let scope = self.resolver.names_in_scope(self.db.upcast());
1032         for (name, entries) in scope {
1033             for entry in entries {
1034                 let def = match entry {
1035                     resolver::ScopeDef::ModuleDef(it) => ScopeDef::ModuleDef(it.into()),
1036                     resolver::ScopeDef::MacroDef(it) => ScopeDef::MacroDef(it.into()),
1037                     resolver::ScopeDef::Unknown => ScopeDef::Unknown,
1038                     resolver::ScopeDef::ImplSelfType(it) => ScopeDef::ImplSelfType(it.into()),
1039                     resolver::ScopeDef::AdtSelfType(it) => ScopeDef::AdtSelfType(it.into()),
1040                     resolver::ScopeDef::GenericParam(id) => ScopeDef::GenericParam(id.into()),
1041                     resolver::ScopeDef::Local(pat_id) => {
1042                         let parent = self.resolver.body_owner().unwrap();
1043                         ScopeDef::Local(Local { parent, pat_id })
1044                     }
1045                     resolver::ScopeDef::Label(label_id) => {
1046                         let parent = self.resolver.body_owner().unwrap();
1047                         ScopeDef::Label(Label { parent, label_id })
1048                     }
1049                 };
1050                 f(name.clone(), def)
1051             }
1052         }
1053     }
1054
1055     /// Resolve a path as-if it was written at the given scope. This is
1056     /// necessary a heuristic, as it doesn't take hygiene into account.
1057     pub fn speculative_resolve(&self, path: &ast::Path) -> Option<PathResolution> {
1058         let ctx = body::LowerCtx::new(self.db.upcast(), self.file_id);
1059         let path = Path::from_src(path.clone(), &ctx)?;
1060         resolve_hir_path(self.db, &self.resolver, &path)
1061     }
1062 }