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