]> git.lizzy.rs Git - rust.git/blob - src/tools/rust-analyzer/crates/hir-def/src/body/lower.rs
Rollup merge of #101492 - TaKO8Ki:suggest-adding-array-length-to-ref-to-array, r...
[rust.git] / src / tools / rust-analyzer / crates / hir-def / src / body / lower.rs
1 //! Transforms `ast::Expr` into an equivalent `hir_def::expr::Expr`
2 //! representation.
3
4 use std::{mem, sync::Arc};
5
6 use either::Either;
7 use hir_expand::{
8     ast_id_map::AstIdMap,
9     hygiene::Hygiene,
10     name::{name, AsName, Name},
11     AstId, ExpandError, HirFileId, InFile,
12 };
13 use la_arena::Arena;
14 use once_cell::unsync::OnceCell;
15 use profile::Count;
16 use rustc_hash::FxHashMap;
17 use syntax::{
18     ast::{
19         self, ArrayExprKind, AstChildren, HasArgList, HasLoopBody, HasName, LiteralKind,
20         SlicePatComponents,
21     },
22     AstNode, AstPtr, SyntaxNodePtr,
23 };
24
25 use crate::{
26     adt::StructKind,
27     body::{Body, BodySourceMap, Expander, ExprPtr, LabelPtr, LabelSource, PatPtr},
28     body::{BodyDiagnostic, ExprSource, PatSource},
29     builtin_type::{BuiltinFloat, BuiltinInt, BuiltinUint},
30     db::DefDatabase,
31     expr::{
32         dummy_expr_id, Array, BindingAnnotation, Expr, ExprId, FloatTypeWrapper, Label, LabelId,
33         Literal, MatchArm, Pat, PatId, RecordFieldPat, RecordLitField, Statement,
34     },
35     intern::Interned,
36     item_scope::BuiltinShadowMode,
37     path::{GenericArgs, Path},
38     type_ref::{Mutability, Rawness, TypeRef},
39     AdtId, BlockLoc, ModuleDefId, UnresolvedMacro,
40 };
41
42 pub struct LowerCtx<'a> {
43     pub db: &'a dyn DefDatabase,
44     hygiene: Hygiene,
45     ast_id_map: Option<(HirFileId, OnceCell<Arc<AstIdMap>>)>,
46 }
47
48 impl<'a> LowerCtx<'a> {
49     pub fn new(db: &'a dyn DefDatabase, file_id: HirFileId) -> Self {
50         LowerCtx {
51             db,
52             hygiene: Hygiene::new(db.upcast(), file_id),
53             ast_id_map: Some((file_id, OnceCell::new())),
54         }
55     }
56
57     pub fn with_hygiene(db: &'a dyn DefDatabase, hygiene: &Hygiene) -> Self {
58         LowerCtx { db, hygiene: hygiene.clone(), ast_id_map: None }
59     }
60
61     pub(crate) fn hygiene(&self) -> &Hygiene {
62         &self.hygiene
63     }
64
65     pub(crate) fn lower_path(&self, ast: ast::Path) -> Option<Path> {
66         Path::from_src(ast, self)
67     }
68
69     pub(crate) fn ast_id<N: AstNode>(&self, db: &dyn DefDatabase, item: &N) -> Option<AstId<N>> {
70         let &(file_id, ref ast_id_map) = self.ast_id_map.as_ref()?;
71         let ast_id_map = ast_id_map.get_or_init(|| db.ast_id_map(file_id));
72         Some(InFile::new(file_id, ast_id_map.ast_id(item)))
73     }
74 }
75
76 pub(super) fn lower(
77     db: &dyn DefDatabase,
78     expander: Expander,
79     params: Option<ast::ParamList>,
80     body: Option<ast::Expr>,
81 ) -> (Body, BodySourceMap) {
82     ExprCollector {
83         db,
84         source_map: BodySourceMap::default(),
85         ast_id_map: db.ast_id_map(expander.current_file_id),
86         body: Body {
87             exprs: Arena::default(),
88             pats: Arena::default(),
89             labels: Arena::default(),
90             params: Vec::new(),
91             body_expr: dummy_expr_id(),
92             block_scopes: Vec::new(),
93             _c: Count::new(),
94             or_pats: Default::default(),
95         },
96         expander,
97         name_to_pat_grouping: Default::default(),
98         is_lowering_inside_or_pat: false,
99         is_lowering_assignee_expr: false,
100     }
101     .collect(params, body)
102 }
103
104 struct ExprCollector<'a> {
105     db: &'a dyn DefDatabase,
106     expander: Expander,
107     ast_id_map: Arc<AstIdMap>,
108     body: Body,
109     source_map: BodySourceMap,
110     // a poor-mans union-find?
111     name_to_pat_grouping: FxHashMap<Name, Vec<PatId>>,
112     is_lowering_inside_or_pat: bool,
113     is_lowering_assignee_expr: bool,
114 }
115
116 impl ExprCollector<'_> {
117     fn collect(
118         mut self,
119         param_list: Option<ast::ParamList>,
120         body: Option<ast::Expr>,
121     ) -> (Body, BodySourceMap) {
122         if let Some(param_list) = param_list {
123             if let Some(self_param) = param_list.self_param() {
124                 let ptr = AstPtr::new(&self_param);
125                 let param_pat = self.alloc_pat(
126                     Pat::Bind {
127                         name: name![self],
128                         mode: BindingAnnotation::new(
129                             self_param.mut_token().is_some() && self_param.amp_token().is_none(),
130                             false,
131                         ),
132                         subpat: None,
133                     },
134                     Either::Right(ptr),
135                 );
136                 self.body.params.push(param_pat);
137             }
138
139             for pat in param_list.params().filter_map(|param| param.pat()) {
140                 let param_pat = self.collect_pat(pat);
141                 self.body.params.push(param_pat);
142             }
143         };
144
145         self.body.body_expr = self.collect_expr_opt(body);
146         (self.body, self.source_map)
147     }
148
149     fn ctx(&self) -> LowerCtx<'_> {
150         LowerCtx::new(self.db, self.expander.current_file_id)
151     }
152
153     fn alloc_expr(&mut self, expr: Expr, ptr: ExprPtr) -> ExprId {
154         let src = self.expander.to_source(ptr);
155         let id = self.make_expr(expr, src.clone());
156         self.source_map.expr_map.insert(src, id);
157         id
158     }
159     // desugared exprs don't have ptr, that's wrong and should be fixed
160     // somehow.
161     fn alloc_expr_desugared(&mut self, expr: Expr) -> ExprId {
162         self.body.exprs.alloc(expr)
163     }
164     fn missing_expr(&mut self) -> ExprId {
165         self.alloc_expr_desugared(Expr::Missing)
166     }
167     fn make_expr(&mut self, expr: Expr, src: ExprSource) -> ExprId {
168         let id = self.body.exprs.alloc(expr);
169         self.source_map.expr_map_back.insert(id, src);
170         id
171     }
172
173     fn alloc_pat(&mut self, pat: Pat, ptr: PatPtr) -> PatId {
174         let src = self.expander.to_source(ptr);
175         let id = self.make_pat(pat, src.clone());
176         self.source_map.pat_map.insert(src, id);
177         id
178     }
179     fn missing_pat(&mut self) -> PatId {
180         self.body.pats.alloc(Pat::Missing)
181     }
182     fn make_pat(&mut self, pat: Pat, src: PatSource) -> PatId {
183         let id = self.body.pats.alloc(pat);
184         self.source_map.pat_map_back.insert(id, src);
185         id
186     }
187
188     fn alloc_label(&mut self, label: Label, ptr: LabelPtr) -> LabelId {
189         let src = self.expander.to_source(ptr);
190         let id = self.make_label(label, src.clone());
191         self.source_map.label_map.insert(src, id);
192         id
193     }
194     fn make_label(&mut self, label: Label, src: LabelSource) -> LabelId {
195         let id = self.body.labels.alloc(label);
196         self.source_map.label_map_back.insert(id, src);
197         id
198     }
199
200     fn collect_expr(&mut self, expr: ast::Expr) -> ExprId {
201         self.maybe_collect_expr(expr).unwrap_or_else(|| self.missing_expr())
202     }
203
204     /// Returns `None` if and only if the expression is `#[cfg]`d out.
205     fn maybe_collect_expr(&mut self, expr: ast::Expr) -> Option<ExprId> {
206         let syntax_ptr = AstPtr::new(&expr);
207         self.check_cfg(&expr)?;
208
209         Some(match expr {
210             ast::Expr::IfExpr(e) => {
211                 let then_branch = self.collect_block_opt(e.then_branch());
212
213                 let else_branch = e.else_branch().map(|b| match b {
214                     ast::ElseBranch::Block(it) => self.collect_block(it),
215                     ast::ElseBranch::IfExpr(elif) => {
216                         let expr: ast::Expr = ast::Expr::cast(elif.syntax().clone()).unwrap();
217                         self.collect_expr(expr)
218                     }
219                 });
220
221                 let condition = self.collect_expr_opt(e.condition());
222
223                 self.alloc_expr(Expr::If { condition, then_branch, else_branch }, syntax_ptr)
224             }
225             ast::Expr::LetExpr(e) => {
226                 let pat = self.collect_pat_opt(e.pat());
227                 let expr = self.collect_expr_opt(e.expr());
228                 self.alloc_expr(Expr::Let { pat, expr }, syntax_ptr)
229             }
230             ast::Expr::BlockExpr(e) => match e.modifier() {
231                 Some(ast::BlockModifier::Try(_)) => {
232                     let body = self.collect_block(e);
233                     self.alloc_expr(Expr::TryBlock { body }, syntax_ptr)
234                 }
235                 Some(ast::BlockModifier::Unsafe(_)) => {
236                     let body = self.collect_block(e);
237                     self.alloc_expr(Expr::Unsafe { body }, syntax_ptr)
238                 }
239                 // FIXME: we need to record these effects somewhere...
240                 Some(ast::BlockModifier::Label(label)) => {
241                     let label = self.collect_label(label);
242                     let res = self.collect_block(e);
243                     match &mut self.body.exprs[res] {
244                         Expr::Block { label: block_label, .. } => {
245                             *block_label = Some(label);
246                         }
247                         _ => unreachable!(),
248                     }
249                     res
250                 }
251                 Some(ast::BlockModifier::Async(_)) => {
252                     let body = self.collect_block(e);
253                     self.alloc_expr(Expr::Async { body }, syntax_ptr)
254                 }
255                 Some(ast::BlockModifier::Const(_)) => {
256                     let body = self.collect_block(e);
257                     self.alloc_expr(Expr::Const { body }, syntax_ptr)
258                 }
259                 None => self.collect_block(e),
260             },
261             ast::Expr::LoopExpr(e) => {
262                 let label = e.label().map(|label| self.collect_label(label));
263                 let body = self.collect_block_opt(e.loop_body());
264                 self.alloc_expr(Expr::Loop { body, label }, syntax_ptr)
265             }
266             ast::Expr::WhileExpr(e) => {
267                 let label = e.label().map(|label| self.collect_label(label));
268                 let body = self.collect_block_opt(e.loop_body());
269
270                 let condition = self.collect_expr_opt(e.condition());
271
272                 self.alloc_expr(Expr::While { condition, body, label }, syntax_ptr)
273             }
274             ast::Expr::ForExpr(e) => {
275                 let label = e.label().map(|label| self.collect_label(label));
276                 let iterable = self.collect_expr_opt(e.iterable());
277                 let pat = self.collect_pat_opt(e.pat());
278                 let body = self.collect_block_opt(e.loop_body());
279                 self.alloc_expr(Expr::For { iterable, pat, body, label }, syntax_ptr)
280             }
281             ast::Expr::CallExpr(e) => {
282                 let callee = self.collect_expr_opt(e.expr());
283                 let args = if let Some(arg_list) = e.arg_list() {
284                     arg_list.args().filter_map(|e| self.maybe_collect_expr(e)).collect()
285                 } else {
286                     Box::default()
287                 };
288                 self.alloc_expr(
289                     Expr::Call { callee, args, is_assignee_expr: self.is_lowering_assignee_expr },
290                     syntax_ptr,
291                 )
292             }
293             ast::Expr::MethodCallExpr(e) => {
294                 let receiver = self.collect_expr_opt(e.receiver());
295                 let args = if let Some(arg_list) = e.arg_list() {
296                     arg_list.args().filter_map(|e| self.maybe_collect_expr(e)).collect()
297                 } else {
298                     Box::default()
299                 };
300                 let method_name = e.name_ref().map(|nr| nr.as_name()).unwrap_or_else(Name::missing);
301                 let generic_args = e
302                     .generic_arg_list()
303                     .and_then(|it| GenericArgs::from_ast(&self.ctx(), it))
304                     .map(Box::new);
305                 self.alloc_expr(
306                     Expr::MethodCall { receiver, method_name, args, generic_args },
307                     syntax_ptr,
308                 )
309             }
310             ast::Expr::MatchExpr(e) => {
311                 let expr = self.collect_expr_opt(e.expr());
312                 let arms = if let Some(match_arm_list) = e.match_arm_list() {
313                     match_arm_list
314                         .arms()
315                         .filter_map(|arm| {
316                             self.check_cfg(&arm).map(|()| MatchArm {
317                                 pat: self.collect_pat_opt(arm.pat()),
318                                 expr: self.collect_expr_opt(arm.expr()),
319                                 guard: arm
320                                     .guard()
321                                     .map(|guard| self.collect_expr_opt(guard.condition())),
322                             })
323                         })
324                         .collect()
325                 } else {
326                     Box::default()
327                 };
328                 self.alloc_expr(Expr::Match { expr, arms }, syntax_ptr)
329             }
330             ast::Expr::PathExpr(e) => {
331                 let path = e
332                     .path()
333                     .and_then(|path| self.expander.parse_path(self.db, path))
334                     .map(Expr::Path)
335                     .unwrap_or(Expr::Missing);
336                 self.alloc_expr(path, syntax_ptr)
337             }
338             ast::Expr::ContinueExpr(e) => self.alloc_expr(
339                 Expr::Continue { label: e.lifetime().map(|l| Name::new_lifetime(&l)) },
340                 syntax_ptr,
341             ),
342             ast::Expr::BreakExpr(e) => {
343                 let expr = e.expr().map(|e| self.collect_expr(e));
344                 self.alloc_expr(
345                     Expr::Break { expr, label: e.lifetime().map(|l| Name::new_lifetime(&l)) },
346                     syntax_ptr,
347                 )
348             }
349             ast::Expr::ParenExpr(e) => {
350                 let inner = self.collect_expr_opt(e.expr());
351                 // make the paren expr point to the inner expression as well
352                 let src = self.expander.to_source(syntax_ptr);
353                 self.source_map.expr_map.insert(src, inner);
354                 inner
355             }
356             ast::Expr::ReturnExpr(e) => {
357                 let expr = e.expr().map(|e| self.collect_expr(e));
358                 self.alloc_expr(Expr::Return { expr }, syntax_ptr)
359             }
360             ast::Expr::YieldExpr(e) => {
361                 let expr = e.expr().map(|e| self.collect_expr(e));
362                 self.alloc_expr(Expr::Yield { expr }, syntax_ptr)
363             }
364             ast::Expr::RecordExpr(e) => {
365                 let path =
366                     e.path().and_then(|path| self.expander.parse_path(self.db, path)).map(Box::new);
367                 let is_assignee_expr = self.is_lowering_assignee_expr;
368                 let record_lit = if let Some(nfl) = e.record_expr_field_list() {
369                     let fields = nfl
370                         .fields()
371                         .filter_map(|field| {
372                             self.check_cfg(&field)?;
373
374                             let name = field.field_name()?.as_name();
375
376                             let expr = match field.expr() {
377                                 Some(e) => self.collect_expr(e),
378                                 None => self.missing_expr(),
379                             };
380                             let src = self.expander.to_source(AstPtr::new(&field));
381                             self.source_map.field_map.insert(src.clone(), expr);
382                             self.source_map.field_map_back.insert(expr, src);
383                             Some(RecordLitField { name, expr })
384                         })
385                         .collect();
386                     let spread = nfl.spread().map(|s| self.collect_expr(s));
387                     let ellipsis = nfl.dotdot_token().is_some();
388                     Expr::RecordLit { path, fields, spread, ellipsis, is_assignee_expr }
389                 } else {
390                     Expr::RecordLit {
391                         path,
392                         fields: Box::default(),
393                         spread: None,
394                         ellipsis: false,
395                         is_assignee_expr,
396                     }
397                 };
398
399                 self.alloc_expr(record_lit, syntax_ptr)
400             }
401             ast::Expr::FieldExpr(e) => {
402                 let expr = self.collect_expr_opt(e.expr());
403                 let name = match e.field_access() {
404                     Some(kind) => kind.as_name(),
405                     _ => Name::missing(),
406                 };
407                 self.alloc_expr(Expr::Field { expr, name }, syntax_ptr)
408             }
409             ast::Expr::AwaitExpr(e) => {
410                 let expr = self.collect_expr_opt(e.expr());
411                 self.alloc_expr(Expr::Await { expr }, syntax_ptr)
412             }
413             ast::Expr::TryExpr(e) => {
414                 let expr = self.collect_expr_opt(e.expr());
415                 self.alloc_expr(Expr::Try { expr }, syntax_ptr)
416             }
417             ast::Expr::CastExpr(e) => {
418                 let expr = self.collect_expr_opt(e.expr());
419                 let type_ref = Interned::new(TypeRef::from_ast_opt(&self.ctx(), e.ty()));
420                 self.alloc_expr(Expr::Cast { expr, type_ref }, syntax_ptr)
421             }
422             ast::Expr::RefExpr(e) => {
423                 let expr = self.collect_expr_opt(e.expr());
424                 let raw_tok = e.raw_token().is_some();
425                 let mutability = if raw_tok {
426                     if e.mut_token().is_some() {
427                         Mutability::Mut
428                     } else if e.const_token().is_some() {
429                         Mutability::Shared
430                     } else {
431                         unreachable!("parser only remaps to raw_token() if matching mutability token follows")
432                     }
433                 } else {
434                     Mutability::from_mutable(e.mut_token().is_some())
435                 };
436                 let rawness = Rawness::from_raw(raw_tok);
437                 self.alloc_expr(Expr::Ref { expr, rawness, mutability }, syntax_ptr)
438             }
439             ast::Expr::PrefixExpr(e) => {
440                 let expr = self.collect_expr_opt(e.expr());
441                 match e.op_kind() {
442                     Some(op) => self.alloc_expr(Expr::UnaryOp { expr, op }, syntax_ptr),
443                     None => self.alloc_expr(Expr::Missing, syntax_ptr),
444                 }
445             }
446             ast::Expr::ClosureExpr(e) => {
447                 let mut args = Vec::new();
448                 let mut arg_types = Vec::new();
449                 if let Some(pl) = e.param_list() {
450                     for param in pl.params() {
451                         let pat = self.collect_pat_opt(param.pat());
452                         let type_ref =
453                             param.ty().map(|it| Interned::new(TypeRef::from_ast(&self.ctx(), it)));
454                         args.push(pat);
455                         arg_types.push(type_ref);
456                     }
457                 }
458                 let ret_type = e
459                     .ret_type()
460                     .and_then(|r| r.ty())
461                     .map(|it| Interned::new(TypeRef::from_ast(&self.ctx(), it)));
462                 let body = self.collect_expr_opt(e.body());
463                 self.alloc_expr(
464                     Expr::Closure {
465                         args: args.into(),
466                         arg_types: arg_types.into(),
467                         ret_type,
468                         body,
469                     },
470                     syntax_ptr,
471                 )
472             }
473             ast::Expr::BinExpr(e) => {
474                 let op = e.op_kind();
475                 if let Some(ast::BinaryOp::Assignment { op: None }) = op {
476                     self.is_lowering_assignee_expr = true;
477                 }
478                 let lhs = self.collect_expr_opt(e.lhs());
479                 self.is_lowering_assignee_expr = false;
480                 let rhs = self.collect_expr_opt(e.rhs());
481                 self.alloc_expr(Expr::BinaryOp { lhs, rhs, op }, syntax_ptr)
482             }
483             ast::Expr::TupleExpr(e) => {
484                 let exprs = e.fields().map(|expr| self.collect_expr(expr)).collect();
485                 self.alloc_expr(
486                     Expr::Tuple { exprs, is_assignee_expr: self.is_lowering_assignee_expr },
487                     syntax_ptr,
488                 )
489             }
490             ast::Expr::BoxExpr(e) => {
491                 let expr = self.collect_expr_opt(e.expr());
492                 self.alloc_expr(Expr::Box { expr }, syntax_ptr)
493             }
494
495             ast::Expr::ArrayExpr(e) => {
496                 let kind = e.kind();
497
498                 match kind {
499                     ArrayExprKind::ElementList(e) => {
500                         let elements = e.map(|expr| self.collect_expr(expr)).collect();
501                         self.alloc_expr(
502                             Expr::Array(Array::ElementList {
503                                 elements,
504                                 is_assignee_expr: self.is_lowering_assignee_expr,
505                             }),
506                             syntax_ptr,
507                         )
508                     }
509                     ArrayExprKind::Repeat { initializer, repeat } => {
510                         let initializer = self.collect_expr_opt(initializer);
511                         let repeat = self.collect_expr_opt(repeat);
512                         self.alloc_expr(
513                             Expr::Array(Array::Repeat { initializer, repeat }),
514                             syntax_ptr,
515                         )
516                     }
517                 }
518             }
519
520             ast::Expr::Literal(e) => self.alloc_expr(Expr::Literal(e.kind().into()), syntax_ptr),
521             ast::Expr::IndexExpr(e) => {
522                 let base = self.collect_expr_opt(e.base());
523                 let index = self.collect_expr_opt(e.index());
524                 self.alloc_expr(Expr::Index { base, index }, syntax_ptr)
525             }
526             ast::Expr::RangeExpr(e) => {
527                 let lhs = e.start().map(|lhs| self.collect_expr(lhs));
528                 let rhs = e.end().map(|rhs| self.collect_expr(rhs));
529                 match e.op_kind() {
530                     Some(range_type) => {
531                         self.alloc_expr(Expr::Range { lhs, rhs, range_type }, syntax_ptr)
532                     }
533                     None => self.alloc_expr(Expr::Missing, syntax_ptr),
534                 }
535             }
536             ast::Expr::MacroExpr(e) => {
537                 let e = e.macro_call()?;
538                 let macro_ptr = AstPtr::new(&e);
539                 let id = self.collect_macro_call(e, macro_ptr, true, |this, expansion| {
540                     expansion.map(|it| this.collect_expr(it))
541                 });
542                 match id {
543                     Some(id) => {
544                         // Make the macro-call point to its expanded expression so we can query
545                         // semantics on syntax pointers to the macro
546                         let src = self.expander.to_source(syntax_ptr);
547                         self.source_map.expr_map.insert(src, id);
548                         id
549                     }
550                     None => self.alloc_expr(Expr::Missing, syntax_ptr),
551                 }
552             }
553             ast::Expr::UnderscoreExpr(_) => self.alloc_expr(Expr::Underscore, syntax_ptr),
554         })
555     }
556
557     fn collect_macro_call<F, T, U>(
558         &mut self,
559         mcall: ast::MacroCall,
560         syntax_ptr: AstPtr<ast::MacroCall>,
561         record_diagnostics: bool,
562         collector: F,
563     ) -> U
564     where
565         F: FnOnce(&mut Self, Option<T>) -> U,
566         T: ast::AstNode,
567     {
568         // File containing the macro call. Expansion errors will be attached here.
569         let outer_file = self.expander.current_file_id;
570
571         let macro_call_ptr = self.expander.to_source(AstPtr::new(&mcall));
572         let res = self.expander.enter_expand(self.db, mcall);
573
574         let res = match res {
575             Ok(res) => res,
576             Err(UnresolvedMacro { path }) => {
577                 if record_diagnostics {
578                     self.source_map.diagnostics.push(BodyDiagnostic::UnresolvedMacroCall {
579                         node: InFile::new(outer_file, syntax_ptr),
580                         path,
581                     });
582                 }
583                 return collector(self, None);
584             }
585         };
586
587         if record_diagnostics {
588             match &res.err {
589                 Some(ExpandError::UnresolvedProcMacro(krate)) => {
590                     self.source_map.diagnostics.push(BodyDiagnostic::UnresolvedProcMacro {
591                         node: InFile::new(outer_file, syntax_ptr),
592                         krate: *krate,
593                     });
594                 }
595                 Some(err) => {
596                     self.source_map.diagnostics.push(BodyDiagnostic::MacroError {
597                         node: InFile::new(outer_file, syntax_ptr),
598                         message: err.to_string(),
599                     });
600                 }
601                 None => {}
602             }
603         }
604
605         match res.value {
606             Some((mark, expansion)) => {
607                 self.source_map.expansions.insert(macro_call_ptr, self.expander.current_file_id);
608                 let prev_ast_id_map = mem::replace(
609                     &mut self.ast_id_map,
610                     self.db.ast_id_map(self.expander.current_file_id),
611                 );
612
613                 let id = collector(self, Some(expansion));
614                 self.ast_id_map = prev_ast_id_map;
615                 self.expander.exit(self.db, mark);
616                 id
617             }
618             None => collector(self, None),
619         }
620     }
621
622     fn collect_expr_opt(&mut self, expr: Option<ast::Expr>) -> ExprId {
623         match expr {
624             Some(expr) => self.collect_expr(expr),
625             None => self.missing_expr(),
626         }
627     }
628
629     fn collect_macro_as_stmt(
630         &mut self,
631         statements: &mut Vec<Statement>,
632         mac: ast::MacroExpr,
633     ) -> Option<ExprId> {
634         let mac_call = mac.macro_call()?;
635         let syntax_ptr = AstPtr::new(&ast::Expr::from(mac));
636         let macro_ptr = AstPtr::new(&mac_call);
637         let expansion = self.collect_macro_call(
638             mac_call,
639             macro_ptr,
640             false,
641             |this, expansion: Option<ast::MacroStmts>| match expansion {
642                 Some(expansion) => {
643                     expansion.statements().for_each(|stmt| this.collect_stmt(statements, stmt));
644                     expansion.expr().and_then(|expr| match expr {
645                         ast::Expr::MacroExpr(mac) => this.collect_macro_as_stmt(statements, mac),
646                         expr => Some(this.collect_expr(expr)),
647                     })
648                 }
649                 None => None,
650             },
651         );
652         match expansion {
653             Some(tail) => {
654                 // Make the macro-call point to its expanded expression so we can query
655                 // semantics on syntax pointers to the macro
656                 let src = self.expander.to_source(syntax_ptr);
657                 self.source_map.expr_map.insert(src, tail);
658                 Some(tail)
659             }
660             None => None,
661         }
662     }
663
664     fn collect_stmt(&mut self, statements: &mut Vec<Statement>, s: ast::Stmt) {
665         match s {
666             ast::Stmt::LetStmt(stmt) => {
667                 if self.check_cfg(&stmt).is_none() {
668                     return;
669                 }
670                 let pat = self.collect_pat_opt(stmt.pat());
671                 let type_ref =
672                     stmt.ty().map(|it| Interned::new(TypeRef::from_ast(&self.ctx(), it)));
673                 let initializer = stmt.initializer().map(|e| self.collect_expr(e));
674                 let else_branch = stmt
675                     .let_else()
676                     .and_then(|let_else| let_else.block_expr())
677                     .map(|block| self.collect_block(block));
678                 statements.push(Statement::Let { pat, type_ref, initializer, else_branch });
679             }
680             ast::Stmt::ExprStmt(stmt) => {
681                 let expr = stmt.expr();
682                 match &expr {
683                     Some(expr) if self.check_cfg(expr).is_none() => return,
684                     _ => (),
685                 }
686                 let has_semi = stmt.semicolon_token().is_some();
687                 // Note that macro could be expanded to multiple statements
688                 if let Some(ast::Expr::MacroExpr(mac)) = expr {
689                     if let Some(expr) = self.collect_macro_as_stmt(statements, mac) {
690                         statements.push(Statement::Expr { expr, has_semi })
691                     }
692                 } else {
693                     let expr = self.collect_expr_opt(expr);
694                     statements.push(Statement::Expr { expr, has_semi });
695                 }
696             }
697             ast::Stmt::Item(_item) => (),
698         }
699     }
700
701     fn collect_block(&mut self, block: ast::BlockExpr) -> ExprId {
702         let file_local_id = self.ast_id_map.ast_id(&block);
703         let ast_id = AstId::new(self.expander.current_file_id, file_local_id);
704         let block_loc =
705             BlockLoc { ast_id, module: self.expander.def_map.module_id(self.expander.module) };
706         let block_id = self.db.intern_block(block_loc);
707
708         let (module, def_map) = match self.db.block_def_map(block_id) {
709             Some(def_map) => {
710                 self.body.block_scopes.push(block_id);
711                 (def_map.root(), def_map)
712             }
713             None => (self.expander.module, self.expander.def_map.clone()),
714         };
715         let prev_def_map = mem::replace(&mut self.expander.def_map, def_map);
716         let prev_local_module = mem::replace(&mut self.expander.module, module);
717
718         let mut statements = Vec::new();
719         block.statements().for_each(|s| self.collect_stmt(&mut statements, s));
720         let tail = block.tail_expr().and_then(|e| match e {
721             ast::Expr::MacroExpr(mac) => self.collect_macro_as_stmt(&mut statements, mac),
722             expr => self.maybe_collect_expr(expr),
723         });
724         let tail = tail.or_else(|| {
725             let stmt = statements.pop()?;
726             if let Statement::Expr { expr, has_semi: false } = stmt {
727                 return Some(expr);
728             }
729             statements.push(stmt);
730             None
731         });
732
733         let syntax_node_ptr = AstPtr::new(&block.into());
734         let expr_id = self.alloc_expr(
735             Expr::Block {
736                 id: block_id,
737                 statements: statements.into_boxed_slice(),
738                 tail,
739                 label: None,
740             },
741             syntax_node_ptr,
742         );
743
744         self.expander.def_map = prev_def_map;
745         self.expander.module = prev_local_module;
746         expr_id
747     }
748
749     fn collect_block_opt(&mut self, expr: Option<ast::BlockExpr>) -> ExprId {
750         match expr {
751             Some(block) => self.collect_block(block),
752             None => self.missing_expr(),
753         }
754     }
755
756     fn collect_label(&mut self, ast_label: ast::Label) -> LabelId {
757         let label = Label {
758             name: ast_label.lifetime().as_ref().map_or_else(Name::missing, Name::new_lifetime),
759         };
760         self.alloc_label(label, AstPtr::new(&ast_label))
761     }
762
763     fn collect_pat(&mut self, pat: ast::Pat) -> PatId {
764         let pat_id = self.collect_pat_(pat);
765         for (_, pats) in self.name_to_pat_grouping.drain() {
766             let pats = Arc::<[_]>::from(pats);
767             self.body.or_pats.extend(pats.iter().map(|&pat| (pat, pats.clone())));
768         }
769         self.is_lowering_inside_or_pat = false;
770         pat_id
771     }
772
773     fn collect_pat_opt(&mut self, pat: Option<ast::Pat>) -> PatId {
774         match pat {
775             Some(pat) => self.collect_pat(pat),
776             None => self.missing_pat(),
777         }
778     }
779
780     fn collect_pat_(&mut self, pat: ast::Pat) -> PatId {
781         let pattern = match &pat {
782             ast::Pat::IdentPat(bp) => {
783                 let name = bp.name().map(|nr| nr.as_name()).unwrap_or_else(Name::missing);
784
785                 let key = self.is_lowering_inside_or_pat.then(|| name.clone());
786                 let annotation =
787                     BindingAnnotation::new(bp.mut_token().is_some(), bp.ref_token().is_some());
788                 let subpat = bp.pat().map(|subpat| self.collect_pat_(subpat));
789                 let pattern = if annotation == BindingAnnotation::Unannotated && subpat.is_none() {
790                     // This could also be a single-segment path pattern. To
791                     // decide that, we need to try resolving the name.
792                     let (resolved, _) = self.expander.def_map.resolve_path(
793                         self.db,
794                         self.expander.module,
795                         &name.clone().into(),
796                         BuiltinShadowMode::Other,
797                     );
798                     match resolved.take_values() {
799                         Some(ModuleDefId::ConstId(_)) => Pat::Path(name.into()),
800                         Some(ModuleDefId::EnumVariantId(_)) => {
801                             // this is only really valid for unit variants, but
802                             // shadowing other enum variants with a pattern is
803                             // an error anyway
804                             Pat::Path(name.into())
805                         }
806                         Some(ModuleDefId::AdtId(AdtId::StructId(s)))
807                             if self.db.struct_data(s).variant_data.kind() != StructKind::Record =>
808                         {
809                             // Funnily enough, record structs *can* be shadowed
810                             // by pattern bindings (but unit or tuple structs
811                             // can't).
812                             Pat::Path(name.into())
813                         }
814                         // shadowing statics is an error as well, so we just ignore that case here
815                         _ => Pat::Bind { name, mode: annotation, subpat },
816                     }
817                 } else {
818                     Pat::Bind { name, mode: annotation, subpat }
819                 };
820
821                 let ptr = AstPtr::new(&pat);
822                 let pat = self.alloc_pat(pattern, Either::Left(ptr));
823                 if let Some(key) = key {
824                     self.name_to_pat_grouping.entry(key).or_default().push(pat);
825                 }
826                 return pat;
827             }
828             ast::Pat::TupleStructPat(p) => {
829                 let path =
830                     p.path().and_then(|path| self.expander.parse_path(self.db, path)).map(Box::new);
831                 let (args, ellipsis) = self.collect_tuple_pat(p.fields());
832                 Pat::TupleStruct { path, args, ellipsis }
833             }
834             ast::Pat::RefPat(p) => {
835                 let pat = self.collect_pat_opt(p.pat());
836                 let mutability = Mutability::from_mutable(p.mut_token().is_some());
837                 Pat::Ref { pat, mutability }
838             }
839             ast::Pat::PathPat(p) => {
840                 let path =
841                     p.path().and_then(|path| self.expander.parse_path(self.db, path)).map(Box::new);
842                 path.map(Pat::Path).unwrap_or(Pat::Missing)
843             }
844             ast::Pat::OrPat(p) => {
845                 self.is_lowering_inside_or_pat = true;
846                 let pats = p.pats().map(|p| self.collect_pat_(p)).collect();
847                 Pat::Or(pats)
848             }
849             ast::Pat::ParenPat(p) => return self.collect_pat_opt_(p.pat()),
850             ast::Pat::TuplePat(p) => {
851                 let (args, ellipsis) = self.collect_tuple_pat(p.fields());
852                 Pat::Tuple { args, ellipsis }
853             }
854             ast::Pat::WildcardPat(_) => Pat::Wild,
855             ast::Pat::RecordPat(p) => {
856                 let path =
857                     p.path().and_then(|path| self.expander.parse_path(self.db, path)).map(Box::new);
858                 let args = p
859                     .record_pat_field_list()
860                     .expect("every struct should have a field list")
861                     .fields()
862                     .filter_map(|f| {
863                         let ast_pat = f.pat()?;
864                         let pat = self.collect_pat_(ast_pat);
865                         let name = f.field_name()?.as_name();
866                         Some(RecordFieldPat { name, pat })
867                     })
868                     .collect();
869
870                 let ellipsis = p
871                     .record_pat_field_list()
872                     .expect("every struct should have a field list")
873                     .rest_pat()
874                     .is_some();
875
876                 Pat::Record { path, args, ellipsis }
877             }
878             ast::Pat::SlicePat(p) => {
879                 let SlicePatComponents { prefix, slice, suffix } = p.components();
880
881                 // FIXME properly handle `RestPat`
882                 Pat::Slice {
883                     prefix: prefix.into_iter().map(|p| self.collect_pat_(p)).collect(),
884                     slice: slice.map(|p| self.collect_pat_(p)),
885                     suffix: suffix.into_iter().map(|p| self.collect_pat_(p)).collect(),
886                 }
887             }
888             ast::Pat::LiteralPat(lit) => {
889                 if let Some(ast_lit) = lit.literal() {
890                     let expr = Expr::Literal(ast_lit.kind().into());
891                     let expr_ptr = AstPtr::new(&ast::Expr::Literal(ast_lit));
892                     let expr_id = self.alloc_expr(expr, expr_ptr);
893                     Pat::Lit(expr_id)
894                 } else {
895                     Pat::Missing
896                 }
897             }
898             ast::Pat::RestPat(_) => {
899                 // `RestPat` requires special handling and should not be mapped
900                 // to a Pat. Here we are using `Pat::Missing` as a fallback for
901                 // when `RestPat` is mapped to `Pat`, which can easily happen
902                 // when the source code being analyzed has a malformed pattern
903                 // which includes `..` in a place where it isn't valid.
904
905                 Pat::Missing
906             }
907             ast::Pat::BoxPat(boxpat) => {
908                 let inner = self.collect_pat_opt_(boxpat.pat());
909                 Pat::Box { inner }
910             }
911             ast::Pat::ConstBlockPat(const_block_pat) => {
912                 if let Some(expr) = const_block_pat.block_expr() {
913                     let expr_id = self.collect_block(expr);
914                     Pat::ConstBlock(expr_id)
915                 } else {
916                     Pat::Missing
917                 }
918             }
919             ast::Pat::MacroPat(mac) => match mac.macro_call() {
920                 Some(call) => {
921                     let macro_ptr = AstPtr::new(&call);
922                     let src = self.expander.to_source(Either::Left(AstPtr::new(&pat)));
923                     let pat =
924                         self.collect_macro_call(call, macro_ptr, true, |this, expanded_pat| {
925                             this.collect_pat_opt_(expanded_pat)
926                         });
927                     self.source_map.pat_map.insert(src, pat);
928                     return pat;
929                 }
930                 None => Pat::Missing,
931             },
932             // FIXME: implement
933             ast::Pat::RangePat(_) => Pat::Missing,
934         };
935         let ptr = AstPtr::new(&pat);
936         self.alloc_pat(pattern, Either::Left(ptr))
937     }
938
939     fn collect_pat_opt_(&mut self, pat: Option<ast::Pat>) -> PatId {
940         match pat {
941             Some(pat) => self.collect_pat_(pat),
942             None => self.missing_pat(),
943         }
944     }
945
946     fn collect_tuple_pat(&mut self, args: AstChildren<ast::Pat>) -> (Box<[PatId]>, Option<usize>) {
947         // Find the location of the `..`, if there is one. Note that we do not
948         // consider the possibility of there being multiple `..` here.
949         let ellipsis = args.clone().position(|p| matches!(p, ast::Pat::RestPat(_)));
950         // We want to skip the `..` pattern here, since we account for it above.
951         let args = args
952             .filter(|p| !matches!(p, ast::Pat::RestPat(_)))
953             .map(|p| self.collect_pat_(p))
954             .collect();
955
956         (args, ellipsis)
957     }
958
959     /// Returns `None` (and emits diagnostics) when `owner` if `#[cfg]`d out, and `Some(())` when
960     /// not.
961     fn check_cfg(&mut self, owner: &dyn ast::HasAttrs) -> Option<()> {
962         match self.expander.parse_attrs(self.db, owner).cfg() {
963             Some(cfg) => {
964                 if self.expander.cfg_options().check(&cfg) != Some(false) {
965                     return Some(());
966                 }
967
968                 self.source_map.diagnostics.push(BodyDiagnostic::InactiveCode {
969                     node: InFile::new(
970                         self.expander.current_file_id,
971                         SyntaxNodePtr::new(owner.syntax()),
972                     ),
973                     cfg,
974                     opts: self.expander.cfg_options().clone(),
975                 });
976
977                 None
978             }
979             None => Some(()),
980         }
981     }
982 }
983
984 impl From<ast::LiteralKind> for Literal {
985     fn from(ast_lit_kind: ast::LiteralKind) -> Self {
986         match ast_lit_kind {
987             // FIXME: these should have actual values filled in, but unsure on perf impact
988             LiteralKind::IntNumber(lit) => {
989                 if let builtin @ Some(_) = lit.suffix().and_then(BuiltinFloat::from_suffix) {
990                     Literal::Float(
991                         FloatTypeWrapper::new(lit.float_value().unwrap_or(Default::default())),
992                         builtin,
993                     )
994                 } else if let builtin @ Some(_) = lit.suffix().and_then(BuiltinInt::from_suffix) {
995                     Literal::Int(lit.value().unwrap_or(0) as i128, builtin)
996                 } else {
997                     let builtin = lit.suffix().and_then(BuiltinUint::from_suffix);
998                     Literal::Uint(lit.value().unwrap_or(0), builtin)
999                 }
1000             }
1001             LiteralKind::FloatNumber(lit) => {
1002                 let ty = lit.suffix().and_then(BuiltinFloat::from_suffix);
1003                 Literal::Float(FloatTypeWrapper::new(lit.value().unwrap_or(Default::default())), ty)
1004             }
1005             LiteralKind::ByteString(bs) => {
1006                 let text = bs.value().map(Box::from).unwrap_or_else(Default::default);
1007                 Literal::ByteString(text)
1008             }
1009             LiteralKind::String(s) => {
1010                 let text = s.value().map(Box::from).unwrap_or_else(Default::default);
1011                 Literal::String(text)
1012             }
1013             LiteralKind::Byte(b) => {
1014                 Literal::Uint(b.value().unwrap_or_default() as u128, Some(BuiltinUint::U8))
1015             }
1016             LiteralKind::Char(c) => Literal::Char(c.value().unwrap_or_default()),
1017             LiteralKind::Bool(val) => Literal::Bool(val),
1018         }
1019     }
1020 }