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