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