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