]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/body/lower.rs
Merge #10902
[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, |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         mut collector: F,
580     ) {
581         // File containing the macro call. Expansion errors will be attached here.
582         let outer_file = self.expander.current_file_id;
583
584         let macro_call = self.expander.to_source(AstPtr::new(&e));
585         let res = self.expander.enter_expand(self.db, e);
586
587         let res = match res {
588             Ok(res) => res,
589             Err(UnresolvedMacro { path }) => {
590                 self.source_map.diagnostics.push(BodyDiagnostic::UnresolvedMacroCall {
591                     node: InFile::new(outer_file, syntax_ptr),
592                     path,
593                 });
594                 collector(self, None);
595                 return;
596             }
597         };
598
599         match &res.err {
600             Some(ExpandError::UnresolvedProcMacro) => {
601                 self.source_map.diagnostics.push(BodyDiagnostic::UnresolvedProcMacro {
602                     node: InFile::new(outer_file, syntax_ptr),
603                 });
604             }
605             Some(err) => {
606                 self.source_map.diagnostics.push(BodyDiagnostic::MacroError {
607                     node: InFile::new(outer_file, syntax_ptr),
608                     message: err.to_string(),
609                 });
610             }
611             None => {}
612         }
613
614         match res.value {
615             Some((mark, expansion)) => {
616                 self.source_map.expansions.insert(macro_call, self.expander.current_file_id);
617
618                 let id = collector(self, Some(expansion));
619                 self.expander.exit(self.db, mark);
620                 id
621             }
622             None => collector(self, None),
623         }
624     }
625
626     fn collect_expr_opt(&mut self, expr: Option<ast::Expr>) -> ExprId {
627         match expr {
628             Some(expr) => self.collect_expr(expr),
629             None => self.missing_expr(),
630         }
631     }
632
633     fn collect_stmt(&mut self, s: ast::Stmt) {
634         match s {
635             ast::Stmt::LetStmt(stmt) => {
636                 if self.check_cfg(&stmt).is_none() {
637                     return;
638                 }
639                 let pat = self.collect_pat_opt(stmt.pat());
640                 let type_ref =
641                     stmt.ty().map(|it| Interned::new(TypeRef::from_ast(&self.ctx(), it)));
642                 let initializer = stmt.initializer().map(|e| self.collect_expr(e));
643                 let else_branch = stmt
644                     .let_else()
645                     .and_then(|let_else| let_else.block_expr())
646                     .map(|block| self.collect_block(block));
647                 self.statements_in_scope.push(Statement::Let {
648                     pat,
649                     type_ref,
650                     initializer,
651                     else_branch,
652                 });
653             }
654             ast::Stmt::ExprStmt(stmt) => {
655                 if let Some(expr) = stmt.expr() {
656                     if self.check_cfg(&expr).is_none() {
657                         return;
658                     }
659                 }
660                 let has_semi = stmt.semicolon_token().is_some();
661                 // Note that macro could be expended to multiple statements
662                 if let Some(ast::Expr::MacroCall(m)) = stmt.expr() {
663                     let macro_ptr = AstPtr::new(&m);
664                     let syntax_ptr = AstPtr::new(&stmt.expr().unwrap());
665
666                     self.collect_macro_call(m, macro_ptr, |this, expansion| match expansion {
667                         Some(expansion) => {
668                             let statements: ast::MacroStmts = expansion;
669
670                             statements.statements().for_each(|stmt| this.collect_stmt(stmt));
671                             if let Some(expr) = statements.expr() {
672                                 let expr = this.collect_expr(expr);
673                                 this.statements_in_scope.push(Statement::Expr { expr, has_semi });
674                             }
675                         }
676                         None => {
677                             let expr = this.alloc_expr(Expr::Missing, syntax_ptr.clone());
678                             this.statements_in_scope.push(Statement::Expr { expr, has_semi });
679                         }
680                     });
681                 } else {
682                     let expr = self.collect_expr_opt(stmt.expr());
683                     self.statements_in_scope.push(Statement::Expr { expr, has_semi });
684                 }
685             }
686             ast::Stmt::Item(item) => {
687                 self.check_cfg(&item);
688             }
689         }
690     }
691
692     fn collect_block(&mut self, block: ast::BlockExpr) -> ExprId {
693         let ast_id = self.expander.ast_id(&block);
694         let block_loc =
695             BlockLoc { ast_id, module: self.expander.def_map.module_id(self.expander.module) };
696         let block_id = self.db.intern_block(block_loc);
697
698         let (module, def_map) = match self.db.block_def_map(block_id) {
699             Some(def_map) => {
700                 self.body.block_scopes.push(block_id);
701                 (def_map.root(), def_map)
702             }
703             None => (self.expander.module, self.expander.def_map.clone()),
704         };
705         let prev_def_map = mem::replace(&mut self.expander.def_map, def_map);
706         let prev_local_module = mem::replace(&mut self.expander.module, module);
707         let prev_statements = std::mem::take(&mut self.statements_in_scope);
708
709         block.statements().for_each(|s| self.collect_stmt(s));
710         block.tail_expr().and_then(|e| {
711             let expr = self.maybe_collect_expr(e)?;
712             self.statements_in_scope.push(Statement::Expr { expr, has_semi: false });
713             Some(())
714         });
715
716         let mut tail = None;
717         if let Some(Statement::Expr { expr, has_semi: false }) = self.statements_in_scope.last() {
718             tail = Some(*expr);
719             self.statements_in_scope.pop();
720         }
721         let tail = tail;
722         let statements = std::mem::replace(&mut self.statements_in_scope, prev_statements).into();
723         let syntax_node_ptr = AstPtr::new(&block.into());
724         let expr_id = self.alloc_expr(
725             Expr::Block { id: block_id, statements, tail, label: None },
726             syntax_node_ptr,
727         );
728
729         self.expander.def_map = prev_def_map;
730         self.expander.module = prev_local_module;
731         expr_id
732     }
733
734     fn collect_block_opt(&mut self, expr: Option<ast::BlockExpr>) -> ExprId {
735         match expr {
736             Some(block) => self.collect_block(block),
737             None => self.missing_expr(),
738         }
739     }
740
741     fn collect_label(&mut self, ast_label: ast::Label) -> LabelId {
742         let label = Label {
743             name: ast_label.lifetime().as_ref().map_or_else(Name::missing, Name::new_lifetime),
744         };
745         self.alloc_label(label, AstPtr::new(&ast_label))
746     }
747
748     fn collect_pat(&mut self, pat: ast::Pat) -> PatId {
749         let pattern = match &pat {
750             ast::Pat::IdentPat(bp) => {
751                 let name = bp.name().map(|nr| nr.as_name()).unwrap_or_else(Name::missing);
752                 let annotation =
753                     BindingAnnotation::new(bp.mut_token().is_some(), bp.ref_token().is_some());
754                 let subpat = bp.pat().map(|subpat| self.collect_pat(subpat));
755                 if annotation == BindingAnnotation::Unannotated && subpat.is_none() {
756                     // This could also be a single-segment path pattern. To
757                     // decide that, we need to try resolving the name.
758                     let (resolved, _) = self.expander.def_map.resolve_path(
759                         self.db,
760                         self.expander.module,
761                         &name.clone().into(),
762                         BuiltinShadowMode::Other,
763                     );
764                     match resolved.take_values() {
765                         Some(ModuleDefId::ConstId(_)) => Pat::Path(name.into()),
766                         Some(ModuleDefId::EnumVariantId(_)) => {
767                             // this is only really valid for unit variants, but
768                             // shadowing other enum variants with a pattern is
769                             // an error anyway
770                             Pat::Path(name.into())
771                         }
772                         Some(ModuleDefId::AdtId(AdtId::StructId(s)))
773                             if self.db.struct_data(s).variant_data.kind() != StructKind::Record =>
774                         {
775                             // Funnily enough, record structs *can* be shadowed
776                             // by pattern bindings (but unit or tuple structs
777                             // can't).
778                             Pat::Path(name.into())
779                         }
780                         // shadowing statics is an error as well, so we just ignore that case here
781                         _ => Pat::Bind { name, mode: annotation, subpat },
782                     }
783                 } else {
784                     Pat::Bind { name, mode: annotation, subpat }
785                 }
786             }
787             ast::Pat::TupleStructPat(p) => {
788                 let path =
789                     p.path().and_then(|path| self.expander.parse_path(self.db, path)).map(Box::new);
790                 let (args, ellipsis) = self.collect_tuple_pat(p.fields());
791                 Pat::TupleStruct { path, args, ellipsis }
792             }
793             ast::Pat::RefPat(p) => {
794                 let pat = self.collect_pat_opt(p.pat());
795                 let mutability = Mutability::from_mutable(p.mut_token().is_some());
796                 Pat::Ref { pat, mutability }
797             }
798             ast::Pat::PathPat(p) => {
799                 let path =
800                     p.path().and_then(|path| self.expander.parse_path(self.db, path)).map(Box::new);
801                 path.map(Pat::Path).unwrap_or(Pat::Missing)
802             }
803             ast::Pat::OrPat(p) => {
804                 let pats = p.pats().map(|p| self.collect_pat(p)).collect();
805                 Pat::Or(pats)
806             }
807             ast::Pat::ParenPat(p) => return self.collect_pat_opt(p.pat()),
808             ast::Pat::TuplePat(p) => {
809                 let (args, ellipsis) = self.collect_tuple_pat(p.fields());
810                 Pat::Tuple { args, ellipsis }
811             }
812             ast::Pat::WildcardPat(_) => Pat::Wild,
813             ast::Pat::RecordPat(p) => {
814                 let path =
815                     p.path().and_then(|path| self.expander.parse_path(self.db, path)).map(Box::new);
816                 let args = p
817                     .record_pat_field_list()
818                     .expect("every struct should have a field list")
819                     .fields()
820                     .filter_map(|f| {
821                         let ast_pat = f.pat()?;
822                         let pat = self.collect_pat(ast_pat);
823                         let name = f.field_name()?.as_name();
824                         Some(RecordFieldPat { name, pat })
825                     })
826                     .collect();
827
828                 let ellipsis = p
829                     .record_pat_field_list()
830                     .expect("every struct should have a field list")
831                     .rest_pat()
832                     .is_some();
833
834                 Pat::Record { path, args, ellipsis }
835             }
836             ast::Pat::SlicePat(p) => {
837                 let SlicePatComponents { prefix, slice, suffix } = p.components();
838
839                 // FIXME properly handle `RestPat`
840                 Pat::Slice {
841                     prefix: prefix.into_iter().map(|p| self.collect_pat(p)).collect(),
842                     slice: slice.map(|p| self.collect_pat(p)),
843                     suffix: suffix.into_iter().map(|p| self.collect_pat(p)).collect(),
844                 }
845             }
846             ast::Pat::LiteralPat(lit) => {
847                 if let Some(ast_lit) = lit.literal() {
848                     let expr = Expr::Literal(ast_lit.kind().into());
849                     let expr_ptr = AstPtr::new(&ast::Expr::Literal(ast_lit));
850                     let expr_id = self.alloc_expr(expr, expr_ptr);
851                     Pat::Lit(expr_id)
852                 } else {
853                     Pat::Missing
854                 }
855             }
856             ast::Pat::RestPat(_) => {
857                 // `RestPat` requires special handling and should not be mapped
858                 // to a Pat. Here we are using `Pat::Missing` as a fallback for
859                 // when `RestPat` is mapped to `Pat`, which can easily happen
860                 // when the source code being analyzed has a malformed pattern
861                 // which includes `..` in a place where it isn't valid.
862
863                 Pat::Missing
864             }
865             ast::Pat::BoxPat(boxpat) => {
866                 let inner = self.collect_pat_opt(boxpat.pat());
867                 Pat::Box { inner }
868             }
869             ast::Pat::ConstBlockPat(const_block_pat) => {
870                 if let Some(expr) = const_block_pat.block_expr() {
871                     let expr_id = self.collect_block(expr);
872                     Pat::ConstBlock(expr_id)
873                 } else {
874                     Pat::Missing
875                 }
876             }
877             ast::Pat::MacroPat(mac) => match mac.macro_call() {
878                 Some(call) => {
879                     let macro_ptr = AstPtr::new(&call);
880                     let mut pat = None;
881                     self.collect_macro_call(call, macro_ptr, |this, expanded_pat| {
882                         pat = Some(this.collect_pat_opt(expanded_pat));
883                     });
884
885                     match pat {
886                         Some(pat) => return pat,
887                         None => Pat::Missing,
888                     }
889                 }
890                 None => Pat::Missing,
891             },
892             // FIXME: implement
893             ast::Pat::RangePat(_) => Pat::Missing,
894         };
895         let ptr = AstPtr::new(&pat);
896         self.alloc_pat(pattern, Either::Left(ptr))
897     }
898
899     fn collect_pat_opt(&mut self, pat: Option<ast::Pat>) -> PatId {
900         match pat {
901             Some(pat) => self.collect_pat(pat),
902             None => self.missing_pat(),
903         }
904     }
905
906     fn collect_tuple_pat(&mut self, args: AstChildren<ast::Pat>) -> (Box<[PatId]>, Option<usize>) {
907         // Find the location of the `..`, if there is one. Note that we do not
908         // consider the possibility of there being multiple `..` here.
909         let ellipsis = args.clone().position(|p| matches!(p, ast::Pat::RestPat(_)));
910         // We want to skip the `..` pattern here, since we account for it above.
911         let args = args
912             .filter(|p| !matches!(p, ast::Pat::RestPat(_)))
913             .map(|p| self.collect_pat(p))
914             .collect();
915
916         (args, ellipsis)
917     }
918
919     /// Returns `None` (and emits diagnostics) when `owner` if `#[cfg]`d out, and `Some(())` when
920     /// not.
921     fn check_cfg(&mut self, owner: &dyn ast::HasAttrs) -> Option<()> {
922         match self.expander.parse_attrs(self.db, owner).cfg() {
923             Some(cfg) => {
924                 if self.expander.cfg_options().check(&cfg) != Some(false) {
925                     return Some(());
926                 }
927
928                 self.source_map.diagnostics.push(BodyDiagnostic::InactiveCode {
929                     node: InFile::new(
930                         self.expander.current_file_id,
931                         SyntaxNodePtr::new(owner.syntax()),
932                     ),
933                     cfg,
934                     opts: self.expander.cfg_options().clone(),
935                 });
936
937                 None
938             }
939             None => Some(()),
940         }
941     }
942 }
943
944 impl From<ast::LiteralKind> for Literal {
945     fn from(ast_lit_kind: ast::LiteralKind) -> Self {
946         match ast_lit_kind {
947             // FIXME: these should have actual values filled in, but unsure on perf impact
948             LiteralKind::IntNumber(lit) => {
949                 if let builtin @ Some(_) = lit.suffix().and_then(BuiltinFloat::from_suffix) {
950                     Literal::Float(Default::default(), builtin)
951                 } else if let builtin @ Some(_) =
952                     lit.suffix().and_then(|it| BuiltinInt::from_suffix(it))
953                 {
954                     Literal::Int(lit.value().unwrap_or(0) as i128, builtin)
955                 } else {
956                     let builtin = lit.suffix().and_then(|it| BuiltinUint::from_suffix(it));
957                     Literal::Uint(lit.value().unwrap_or(0), builtin)
958                 }
959             }
960             LiteralKind::FloatNumber(lit) => {
961                 let ty = lit.suffix().and_then(|it| BuiltinFloat::from_suffix(it));
962                 Literal::Float(Default::default(), ty)
963             }
964             LiteralKind::ByteString(bs) => {
965                 let text = bs.value().map(Box::from).unwrap_or_else(Default::default);
966                 Literal::ByteString(text)
967             }
968             LiteralKind::String(_) => Literal::String(Default::default()),
969             LiteralKind::Byte => Literal::Uint(Default::default(), Some(BuiltinUint::U8)),
970             LiteralKind::Bool(val) => Literal::Bool(val),
971             LiteralKind::Char => Literal::Char(Default::default()),
972         }
973     }
974 }