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