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