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