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