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