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