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