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