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