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