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