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