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