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