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