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