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