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