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