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