1 //! Transforms `ast::Expr` into an equivalent `hir_def::expr::Expr`
4 use std::{mem, sync::Arc};
8 ast_id_map::{AstIdMap, FileAstId},
10 name::{name, AsName, Name},
11 ExpandError, HirFileId, InFile,
17 self, ArgListOwner, ArrayExprKind, AstChildren, LiteralKind, LoopBodyOwner, NameOwner,
20 AstNode, AstPtr, SyntaxNodePtr,
25 body::{Body, BodySourceMap, Expander, LabelSource, PatPtr, SyntheticSyntax},
26 body::{BodyDiagnostic, ExprSource, PatSource},
27 builtin_type::{BuiltinFloat, BuiltinInt, BuiltinUint},
30 dummy_expr_id, Array, BindingAnnotation, Expr, ExprId, Label, LabelId, Literal, MatchArm,
31 MatchGuard, Pat, PatId, RecordFieldPat, RecordLitField, Statement,
34 item_scope::BuiltinShadowMode,
35 path::{GenericArgs, Path},
36 type_ref::{Mutability, Rawness, TypeRef},
37 AdtId, BlockLoc, ModuleDefId, UnresolvedMacro,
40 pub struct LowerCtx<'a> {
41 pub db: &'a dyn DefDatabase,
43 file_id: Option<HirFileId>,
44 source_ast_id_map: Option<Arc<AstIdMap>>,
47 impl<'a> LowerCtx<'a> {
48 pub fn new(db: &'a dyn DefDatabase, file_id: HirFileId) -> Self {
51 hygiene: Hygiene::new(db.upcast(), file_id),
52 file_id: Some(file_id),
53 source_ast_id_map: Some(db.ast_id_map(file_id)),
57 pub fn with_hygiene(db: &'a dyn DefDatabase, hygiene: &Hygiene) -> Self {
58 LowerCtx { db, hygiene: hygiene.clone(), file_id: None, source_ast_id_map: None }
61 pub(crate) fn hygiene(&self) -> &Hygiene {
65 pub(crate) fn file_id(&self) -> HirFileId {
69 pub(crate) fn lower_path(&self, ast: ast::Path) -> Option<Path> {
70 Path::from_src(ast, self)
73 pub(crate) fn ast_id<N: AstNode>(&self, item: &N) -> Option<FileAstId<N>> {
74 self.source_ast_id_map.as_ref().map(|ast_id_map| ast_id_map.ast_id(item))
81 params: Option<ast::ParamList>,
82 body: Option<ast::Expr>,
83 ) -> (Body, BodySourceMap) {
86 source_map: BodySourceMap::default(),
88 exprs: Arena::default(),
89 pats: Arena::default(),
90 labels: Arena::default(),
92 body_expr: dummy_expr_id(),
93 block_scopes: Vec::new(),
97 statements_in_scope: Vec::new(),
99 .collect(params, body)
102 struct ExprCollector<'a> {
103 db: &'a dyn DefDatabase,
106 source_map: BodySourceMap,
107 statements_in_scope: Vec<Statement>,
110 impl ExprCollector<'_> {
113 param_list: Option<ast::ParamList>,
114 body: Option<ast::Expr>,
115 ) -> (Body, BodySourceMap) {
116 if let Some(param_list) = param_list {
117 if let Some(self_param) = param_list.self_param() {
118 let ptr = AstPtr::new(&self_param);
119 let param_pat = self.alloc_pat(
122 mode: BindingAnnotation::new(
123 self_param.mut_token().is_some() && self_param.amp_token().is_none(),
130 self.body.params.push(param_pat);
133 for param in param_list.params() {
134 let pat = match param.pat() {
138 let param_pat = self.collect_pat(pat);
139 self.body.params.push(param_pat);
143 self.body.body_expr = self.collect_expr_opt(body);
144 (self.body, self.source_map)
147 fn ctx(&self) -> LowerCtx<'_> {
148 LowerCtx::new(self.db, self.expander.current_file_id)
151 fn alloc_expr(&mut self, expr: Expr, ptr: AstPtr<ast::Expr>) -> ExprId {
152 let src = self.expander.to_source(ptr);
153 let id = self.make_expr(expr, Ok(src.clone()));
154 self.source_map.expr_map.insert(src, id);
157 // desugared exprs don't have ptr, that's wrong and should be fixed
159 fn alloc_expr_desugared(&mut self, expr: Expr) -> ExprId {
160 self.make_expr(expr, Err(SyntheticSyntax))
162 fn unit(&mut self) -> ExprId {
163 self.alloc_expr_desugared(Expr::Tuple { exprs: Vec::new() })
165 fn missing_expr(&mut self) -> ExprId {
166 self.alloc_expr_desugared(Expr::Missing)
168 fn make_expr(&mut self, expr: Expr, src: Result<ExprSource, SyntheticSyntax>) -> ExprId {
169 let id = self.body.exprs.alloc(expr);
170 self.source_map.expr_map_back.insert(id, src);
174 fn alloc_pat(&mut self, pat: Pat, ptr: PatPtr) -> PatId {
175 let src = self.expander.to_source(ptr);
176 let id = self.make_pat(pat, Ok(src.clone()));
177 self.source_map.pat_map.insert(src, id);
180 fn missing_pat(&mut self) -> PatId {
181 self.make_pat(Pat::Missing, Err(SyntheticSyntax))
183 fn make_pat(&mut self, pat: Pat, src: Result<PatSource, SyntheticSyntax>) -> PatId {
184 let id = self.body.pats.alloc(pat);
185 self.source_map.pat_map_back.insert(id, src);
189 fn alloc_label(&mut self, label: Label, ptr: AstPtr<ast::Label>) -> LabelId {
190 let src = self.expander.to_source(ptr);
191 let id = self.make_label(label, src.clone());
192 self.source_map.label_map.insert(src, id);
195 fn make_label(&mut self, label: Label, src: LabelSource) -> LabelId {
196 let id = self.body.labels.alloc(label);
197 self.source_map.label_map_back.insert(id, src);
201 fn collect_expr(&mut self, expr: ast::Expr) -> ExprId {
202 self.maybe_collect_expr(expr).unwrap_or_else(|| self.missing_expr())
205 /// Returns `None` if and only if the expression is `#[cfg]`d out.
206 fn maybe_collect_expr(&mut self, expr: ast::Expr) -> Option<ExprId> {
207 let syntax_ptr = AstPtr::new(&expr);
208 self.check_cfg(&expr)?;
211 ast::Expr::IfExpr(e) => {
212 let then_branch = self.collect_block_opt(e.then_branch());
214 let else_branch = e.else_branch().map(|b| match b {
215 ast::ElseBranch::Block(it) => self.collect_block(it),
216 ast::ElseBranch::IfExpr(elif) => {
217 let expr: ast::Expr = ast::Expr::cast(elif.syntax().clone()).unwrap();
218 self.collect_expr(expr)
222 let condition = match e.condition() {
223 None => self.missing_expr(),
224 Some(condition) => match condition.pat() {
225 None => self.collect_expr_opt(condition.expr()),
226 // if let -- desugar to match
228 let pat = self.collect_pat(pat);
229 let match_expr = self.collect_expr_opt(condition.expr());
230 let placeholder_pat = self.missing_pat();
232 MatchArm { pat, expr: then_branch, guard: None },
234 pat: placeholder_pat,
235 expr: else_branch.unwrap_or_else(|| self.unit()),
240 self.alloc_expr(Expr::Match { expr: match_expr, arms }, syntax_ptr),
246 self.alloc_expr(Expr::If { condition, then_branch, else_branch }, syntax_ptr)
248 ast::Expr::BlockExpr(e) => match e.modifier() {
249 Some(ast::BlockModifier::Try(_)) => {
250 let body = self.collect_block(e);
251 self.alloc_expr(Expr::TryBlock { body }, syntax_ptr)
253 Some(ast::BlockModifier::Unsafe(_)) => {
254 let body = self.collect_block(e);
255 self.alloc_expr(Expr::Unsafe { body }, syntax_ptr)
257 // FIXME: we need to record these effects somewhere...
258 Some(ast::BlockModifier::Label(label)) => {
259 let label = self.collect_label(label);
260 let res = self.collect_block(e);
261 match &mut self.body.exprs[res] {
262 Expr::Block { label: block_label, .. } => {
263 *block_label = Some(label);
269 Some(ast::BlockModifier::Async(_)) => {
270 let body = self.collect_block(e);
271 self.alloc_expr(Expr::Async { body }, syntax_ptr)
273 Some(ast::BlockModifier::Const(_)) => {
274 let body = self.collect_block(e);
275 self.alloc_expr(Expr::Const { body }, syntax_ptr)
277 None => self.collect_block(e),
279 ast::Expr::LoopExpr(e) => {
280 let label = e.label().map(|label| self.collect_label(label));
281 let body = self.collect_block_opt(e.loop_body());
282 self.alloc_expr(Expr::Loop { body, label }, syntax_ptr)
284 ast::Expr::WhileExpr(e) => {
285 let label = e.label().map(|label| self.collect_label(label));
286 let body = self.collect_block_opt(e.loop_body());
288 let condition = match e.condition() {
289 None => self.missing_expr(),
290 Some(condition) => match condition.pat() {
291 None => self.collect_expr_opt(condition.expr()),
292 // if let -- desugar to match
294 cov_mark::hit!(infer_resolve_while_let);
295 let pat = self.collect_pat(pat);
296 let match_expr = self.collect_expr_opt(condition.expr());
297 let placeholder_pat = self.missing_pat();
299 self.alloc_expr_desugared(Expr::Break { expr: None, label: None });
301 MatchArm { pat, expr: body, guard: None },
302 MatchArm { pat: placeholder_pat, expr: break_, guard: None },
305 self.alloc_expr_desugared(Expr::Match { expr: match_expr, arms });
307 self.alloc_expr(Expr::Loop { body: match_expr, label }, syntax_ptr),
313 self.alloc_expr(Expr::While { condition, body, label }, syntax_ptr)
315 ast::Expr::ForExpr(e) => {
316 let label = e.label().map(|label| self.collect_label(label));
317 let iterable = self.collect_expr_opt(e.iterable());
318 let pat = self.collect_pat_opt(e.pat());
319 let body = self.collect_block_opt(e.loop_body());
320 self.alloc_expr(Expr::For { iterable, pat, body, label }, syntax_ptr)
322 ast::Expr::CallExpr(e) => {
323 let callee = self.collect_expr_opt(e.expr());
324 let args = if let Some(arg_list) = e.arg_list() {
325 arg_list.args().filter_map(|e| self.maybe_collect_expr(e)).collect()
329 self.alloc_expr(Expr::Call { callee, args }, syntax_ptr)
331 ast::Expr::MethodCallExpr(e) => {
332 let receiver = self.collect_expr_opt(e.receiver());
333 let args = if let Some(arg_list) = e.arg_list() {
334 arg_list.args().filter_map(|e| self.maybe_collect_expr(e)).collect()
338 let method_name = e.name_ref().map(|nr| nr.as_name()).unwrap_or_else(Name::missing);
341 .and_then(|it| GenericArgs::from_ast(&self.ctx(), it))
344 Expr::MethodCall { receiver, method_name, args, generic_args },
348 ast::Expr::MatchExpr(e) => {
349 let expr = self.collect_expr_opt(e.expr());
350 let arms = if let Some(match_arm_list) = e.match_arm_list() {
354 self.check_cfg(&arm).map(|()| MatchArm {
355 pat: self.collect_pat_opt(arm.pat()),
356 expr: self.collect_expr_opt(arm.expr()),
357 guard: arm.guard().map(|guard| match guard.pat() {
358 Some(pat) => MatchGuard::IfLet {
359 pat: self.collect_pat(pat),
360 expr: self.collect_expr_opt(guard.expr()),
363 MatchGuard::If { expr: self.collect_expr_opt(guard.expr()) }
372 self.alloc_expr(Expr::Match { expr, arms }, syntax_ptr)
374 ast::Expr::PathExpr(e) => {
377 .and_then(|path| self.expander.parse_path(self.db, path))
379 .unwrap_or(Expr::Missing);
380 self.alloc_expr(path, syntax_ptr)
382 ast::Expr::ContinueExpr(e) => self.alloc_expr(
383 Expr::Continue { label: e.lifetime().map(|l| Name::new_lifetime(&l)) },
386 ast::Expr::BreakExpr(e) => {
387 let expr = e.expr().map(|e| self.collect_expr(e));
389 Expr::Break { expr, label: e.lifetime().map(|l| Name::new_lifetime(&l)) },
393 ast::Expr::ParenExpr(e) => {
394 let inner = self.collect_expr_opt(e.expr());
395 // make the paren expr point to the inner expression as well
396 let src = self.expander.to_source(syntax_ptr);
397 self.source_map.expr_map.insert(src, inner);
400 ast::Expr::ReturnExpr(e) => {
401 let expr = e.expr().map(|e| self.collect_expr(e));
402 self.alloc_expr(Expr::Return { expr }, syntax_ptr)
404 ast::Expr::YieldExpr(e) => {
405 let expr = e.expr().map(|e| self.collect_expr(e));
406 self.alloc_expr(Expr::Yield { expr }, syntax_ptr)
408 ast::Expr::RecordExpr(e) => {
410 e.path().and_then(|path| self.expander.parse_path(self.db, path)).map(Box::new);
411 let record_lit = if let Some(nfl) = e.record_expr_field_list() {
414 .filter_map(|field| {
415 self.check_cfg(&field)?;
417 let name = field.field_name()?.as_name();
419 let expr = match field.expr() {
420 Some(e) => self.collect_expr(e),
421 None => self.missing_expr(),
423 let src = self.expander.to_source(AstPtr::new(&field));
424 self.source_map.field_map.insert(src.clone(), expr);
425 self.source_map.field_map_back.insert(expr, src);
426 Some(RecordLitField { name, expr })
429 let spread = nfl.spread().map(|s| self.collect_expr(s));
430 Expr::RecordLit { path, fields, spread }
432 Expr::RecordLit { path, fields: Vec::new(), spread: None }
435 self.alloc_expr(record_lit, syntax_ptr)
437 ast::Expr::FieldExpr(e) => {
438 let expr = self.collect_expr_opt(e.expr());
439 let name = match e.field_access() {
440 Some(kind) => kind.as_name(),
441 _ => Name::missing(),
443 self.alloc_expr(Expr::Field { expr, name }, syntax_ptr)
445 ast::Expr::AwaitExpr(e) => {
446 let expr = self.collect_expr_opt(e.expr());
447 self.alloc_expr(Expr::Await { expr }, syntax_ptr)
449 ast::Expr::TryExpr(e) => {
450 let expr = self.collect_expr_opt(e.expr());
451 self.alloc_expr(Expr::Try { expr }, syntax_ptr)
453 ast::Expr::CastExpr(e) => {
454 let expr = self.collect_expr_opt(e.expr());
455 let type_ref = Interned::new(TypeRef::from_ast_opt(&self.ctx(), e.ty()));
456 self.alloc_expr(Expr::Cast { expr, type_ref }, syntax_ptr)
458 ast::Expr::RefExpr(e) => {
459 let expr = self.collect_expr_opt(e.expr());
460 let raw_tok = e.raw_token().is_some();
461 let mutability = if raw_tok {
462 if e.mut_token().is_some() {
464 } else if e.const_token().is_some() {
467 unreachable!("parser only remaps to raw_token() if matching mutability token follows")
470 Mutability::from_mutable(e.mut_token().is_some())
472 let rawness = Rawness::from_raw(raw_tok);
473 self.alloc_expr(Expr::Ref { expr, rawness, mutability }, syntax_ptr)
475 ast::Expr::PrefixExpr(e) => {
476 let expr = self.collect_expr_opt(e.expr());
477 if let Some(op) = e.op_kind() {
478 self.alloc_expr(Expr::UnaryOp { expr, op }, syntax_ptr)
480 self.alloc_expr(Expr::Missing, syntax_ptr)
483 ast::Expr::ClosureExpr(e) => {
484 let mut args = Vec::new();
485 let mut arg_types = Vec::new();
486 if let Some(pl) = e.param_list() {
487 for param in pl.params() {
488 let pat = self.collect_pat_opt(param.pat());
490 param.ty().map(|it| Interned::new(TypeRef::from_ast(&self.ctx(), it)));
492 arg_types.push(type_ref);
497 .and_then(|r| r.ty())
498 .map(|it| Interned::new(TypeRef::from_ast(&self.ctx(), it)));
499 let body = self.collect_expr_opt(e.body());
500 self.alloc_expr(Expr::Lambda { args, arg_types, ret_type, body }, syntax_ptr)
502 ast::Expr::BinExpr(e) => {
503 let lhs = self.collect_expr_opt(e.lhs());
504 let rhs = self.collect_expr_opt(e.rhs());
505 let op = e.op_kind();
506 self.alloc_expr(Expr::BinaryOp { lhs, rhs, op }, syntax_ptr)
508 ast::Expr::TupleExpr(e) => {
509 let exprs = e.fields().map(|expr| self.collect_expr(expr)).collect();
510 self.alloc_expr(Expr::Tuple { exprs }, syntax_ptr)
512 ast::Expr::BoxExpr(e) => {
513 let expr = self.collect_expr_opt(e.expr());
514 self.alloc_expr(Expr::Box { expr }, syntax_ptr)
517 ast::Expr::ArrayExpr(e) => {
521 ArrayExprKind::ElementList(e) => {
522 let exprs = e.map(|expr| self.collect_expr(expr)).collect();
523 self.alloc_expr(Expr::Array(Array::ElementList(exprs)), syntax_ptr)
525 ArrayExprKind::Repeat { initializer, repeat } => {
526 let initializer = self.collect_expr_opt(initializer);
527 let repeat = self.collect_expr_opt(repeat);
529 Expr::Array(Array::Repeat { initializer, repeat }),
536 ast::Expr::Literal(e) => self.alloc_expr(Expr::Literal(e.kind().into()), syntax_ptr),
537 ast::Expr::IndexExpr(e) => {
538 let base = self.collect_expr_opt(e.base());
539 let index = self.collect_expr_opt(e.index());
540 self.alloc_expr(Expr::Index { base, index }, syntax_ptr)
542 ast::Expr::RangeExpr(e) => {
543 let lhs = e.start().map(|lhs| self.collect_expr(lhs));
544 let rhs = e.end().map(|rhs| self.collect_expr(rhs));
546 Some(range_type) => {
547 self.alloc_expr(Expr::Range { lhs, rhs, range_type }, syntax_ptr)
549 None => self.alloc_expr(Expr::Missing, syntax_ptr),
552 ast::Expr::MacroCall(e) => {
553 let macro_ptr = AstPtr::new(&e);
554 let mut ids = vec![];
555 self.collect_macro_call(e, macro_ptr, |this, expansion| {
556 ids.push(match expansion {
557 Some(it) => this.collect_expr(it),
558 None => this.alloc_expr(Expr::Missing, syntax_ptr.clone()),
563 ast::Expr::MacroStmts(e) => {
564 e.statements().for_each(|s| self.collect_stmt(s));
567 .map(|e| self.collect_expr(e))
568 .unwrap_or_else(|| self.alloc_expr(Expr::Missing, syntax_ptr.clone()));
570 self.alloc_expr(Expr::MacroStmts { tail }, syntax_ptr)
575 fn collect_macro_call<F: FnMut(&mut Self, Option<T>), T: ast::AstNode>(
578 syntax_ptr: AstPtr<ast::MacroCall>,
581 // File containing the macro call. Expansion errors will be attached here.
582 let outer_file = self.expander.current_file_id;
584 let macro_call = self.expander.to_source(AstPtr::new(&e));
585 let res = self.expander.enter_expand(self.db, e);
587 let res = match res {
589 Err(UnresolvedMacro { path }) => {
590 self.source_map.diagnostics.push(BodyDiagnostic::UnresolvedMacroCall {
591 node: InFile::new(outer_file, syntax_ptr),
594 collector(self, None);
600 Some(ExpandError::UnresolvedProcMacro) => {
601 self.source_map.diagnostics.push(BodyDiagnostic::UnresolvedProcMacro {
602 node: InFile::new(outer_file, syntax_ptr),
606 self.source_map.diagnostics.push(BodyDiagnostic::MacroError {
607 node: InFile::new(outer_file, syntax_ptr),
608 message: err.to_string(),
615 Some((mark, expansion)) => {
616 self.source_map.expansions.insert(macro_call, self.expander.current_file_id);
618 let id = collector(self, Some(expansion));
619 self.expander.exit(self.db, mark);
622 None => collector(self, None),
626 fn collect_expr_opt(&mut self, expr: Option<ast::Expr>) -> ExprId {
627 if let Some(expr) = expr {
628 self.collect_expr(expr)
634 fn collect_stmt(&mut self, s: ast::Stmt) {
636 ast::Stmt::LetStmt(stmt) => {
637 if self.check_cfg(&stmt).is_none() {
640 let pat = self.collect_pat_opt(stmt.pat());
642 stmt.ty().map(|it| Interned::new(TypeRef::from_ast(&self.ctx(), it)));
643 let initializer = stmt.initializer().map(|e| self.collect_expr(e));
644 self.statements_in_scope.push(Statement::Let { pat, type_ref, initializer });
646 ast::Stmt::ExprStmt(stmt) => {
647 if let Some(expr) = stmt.expr() {
648 if self.check_cfg(&expr).is_none() {
652 let has_semi = stmt.semicolon_token().is_some();
653 // Note that macro could be expended to multiple statements
654 if let Some(ast::Expr::MacroCall(m)) = stmt.expr() {
655 let macro_ptr = AstPtr::new(&m);
656 let syntax_ptr = AstPtr::new(&stmt.expr().unwrap());
658 self.collect_macro_call(m, macro_ptr, |this, expansion| match expansion {
660 let statements: ast::MacroStmts = expansion;
662 statements.statements().for_each(|stmt| this.collect_stmt(stmt));
663 if let Some(expr) = statements.expr() {
664 let expr = this.collect_expr(expr);
665 this.statements_in_scope.push(Statement::Expr { expr, has_semi });
669 let expr = this.alloc_expr(Expr::Missing, syntax_ptr.clone());
670 this.statements_in_scope.push(Statement::Expr { expr, has_semi });
674 let expr = self.collect_expr_opt(stmt.expr());
675 self.statements_in_scope.push(Statement::Expr { expr, has_semi });
678 ast::Stmt::Item(item) => {
679 self.check_cfg(&item);
684 fn collect_block(&mut self, block: ast::BlockExpr) -> ExprId {
685 let ast_id = self.expander.ast_id(&block);
687 BlockLoc { ast_id, module: self.expander.def_map.module_id(self.expander.module) };
688 let block_id = self.db.intern_block(block_loc);
690 let (module, def_map) = match self.db.block_def_map(block_id) {
692 self.body.block_scopes.push(block_id);
693 (def_map.root(), def_map)
695 None => (self.expander.module, self.expander.def_map.clone()),
697 let prev_def_map = mem::replace(&mut self.expander.def_map, def_map);
698 let prev_local_module = mem::replace(&mut self.expander.module, module);
699 let prev_statements = std::mem::take(&mut self.statements_in_scope);
701 block.statements().for_each(|s| self.collect_stmt(s));
702 block.tail_expr().and_then(|e| {
703 let expr = self.maybe_collect_expr(e)?;
704 self.statements_in_scope.push(Statement::Expr { expr, has_semi: false });
709 if let Some(Statement::Expr { expr, has_semi: false }) = self.statements_in_scope.last() {
711 self.statements_in_scope.pop();
714 let statements = std::mem::replace(&mut self.statements_in_scope, prev_statements);
715 let syntax_node_ptr = AstPtr::new(&block.into());
716 let expr_id = self.alloc_expr(
717 Expr::Block { id: block_id, statements, tail, label: None },
721 self.expander.def_map = prev_def_map;
722 self.expander.module = prev_local_module;
726 fn collect_block_opt(&mut self, expr: Option<ast::BlockExpr>) -> ExprId {
727 if let Some(block) = expr {
728 self.collect_block(block)
734 fn collect_label(&mut self, ast_label: ast::Label) -> LabelId {
736 name: ast_label.lifetime().as_ref().map_or_else(Name::missing, Name::new_lifetime),
738 self.alloc_label(label, AstPtr::new(&ast_label))
741 fn collect_pat(&mut self, pat: ast::Pat) -> PatId {
742 let pattern = match &pat {
743 ast::Pat::IdentPat(bp) => {
744 let name = bp.name().map(|nr| nr.as_name()).unwrap_or_else(Name::missing);
746 BindingAnnotation::new(bp.mut_token().is_some(), bp.ref_token().is_some());
747 let subpat = bp.pat().map(|subpat| self.collect_pat(subpat));
748 if annotation == BindingAnnotation::Unannotated && subpat.is_none() {
749 // This could also be a single-segment path pattern. To
750 // decide that, we need to try resolving the name.
751 let (resolved, _) = self.expander.def_map.resolve_path(
753 self.expander.module,
754 &name.clone().into(),
755 BuiltinShadowMode::Other,
757 match resolved.take_values() {
758 Some(ModuleDefId::ConstId(_)) => Pat::Path(name.into()),
759 Some(ModuleDefId::EnumVariantId(_)) => {
760 // this is only really valid for unit variants, but
761 // shadowing other enum variants with a pattern is
763 Pat::Path(name.into())
765 Some(ModuleDefId::AdtId(AdtId::StructId(s)))
766 if self.db.struct_data(s).variant_data.kind() != StructKind::Record =>
768 // Funnily enough, record structs *can* be shadowed
769 // by pattern bindings (but unit or tuple structs
771 Pat::Path(name.into())
773 // shadowing statics is an error as well, so we just ignore that case here
774 _ => Pat::Bind { name, mode: annotation, subpat },
777 Pat::Bind { name, mode: annotation, subpat }
780 ast::Pat::TupleStructPat(p) => {
782 p.path().and_then(|path| self.expander.parse_path(self.db, path)).map(Box::new);
783 let (args, ellipsis) = self.collect_tuple_pat(p.fields());
784 Pat::TupleStruct { path, args, ellipsis }
786 ast::Pat::RefPat(p) => {
787 let pat = self.collect_pat_opt(p.pat());
788 let mutability = Mutability::from_mutable(p.mut_token().is_some());
789 Pat::Ref { pat, mutability }
791 ast::Pat::PathPat(p) => {
793 p.path().and_then(|path| self.expander.parse_path(self.db, path)).map(Box::new);
794 path.map(Pat::Path).unwrap_or(Pat::Missing)
796 ast::Pat::OrPat(p) => {
797 let pats = p.pats().map(|p| self.collect_pat(p)).collect();
800 ast::Pat::ParenPat(p) => return self.collect_pat_opt(p.pat()),
801 ast::Pat::TuplePat(p) => {
802 let (args, ellipsis) = self.collect_tuple_pat(p.fields());
803 Pat::Tuple { args, ellipsis }
805 ast::Pat::WildcardPat(_) => Pat::Wild,
806 ast::Pat::RecordPat(p) => {
808 p.path().and_then(|path| self.expander.parse_path(self.db, path)).map(Box::new);
810 .record_pat_field_list()
811 .expect("every struct should have a field list")
814 let ast_pat = f.pat()?;
815 let pat = self.collect_pat(ast_pat);
816 let name = f.field_name()?.as_name();
817 Some(RecordFieldPat { name, pat })
822 .record_pat_field_list()
823 .expect("every struct should have a field list")
827 Pat::Record { path, args, ellipsis }
829 ast::Pat::SlicePat(p) => {
830 let SlicePatComponents { prefix, slice, suffix } = p.components();
832 // FIXME properly handle `RestPat`
834 prefix: prefix.into_iter().map(|p| self.collect_pat(p)).collect(),
835 slice: slice.map(|p| self.collect_pat(p)),
836 suffix: suffix.into_iter().map(|p| self.collect_pat(p)).collect(),
839 ast::Pat::LiteralPat(lit) => {
840 if let Some(ast_lit) = lit.literal() {
841 let expr = Expr::Literal(ast_lit.kind().into());
842 let expr_ptr = AstPtr::new(&ast::Expr::Literal(ast_lit));
843 let expr_id = self.alloc_expr(expr, expr_ptr);
849 ast::Pat::RestPat(_) => {
850 // `RestPat` requires special handling and should not be mapped
851 // to a Pat. Here we are using `Pat::Missing` as a fallback for
852 // when `RestPat` is mapped to `Pat`, which can easily happen
853 // when the source code being analyzed has a malformed pattern
854 // which includes `..` in a place where it isn't valid.
858 ast::Pat::BoxPat(boxpat) => {
859 let inner = self.collect_pat_opt(boxpat.pat());
862 ast::Pat::ConstBlockPat(const_block_pat) => {
863 if let Some(expr) = const_block_pat.block_expr() {
864 let expr_id = self.collect_block(expr);
865 Pat::ConstBlock(expr_id)
870 ast::Pat::MacroPat(mac) => match mac.macro_call() {
872 let macro_ptr = AstPtr::new(&call);
874 self.collect_macro_call(call, macro_ptr, |this, expanded_pat| {
875 pat = Some(this.collect_pat_opt(expanded_pat));
879 Some(pat) => return pat,
880 None => Pat::Missing,
883 None => Pat::Missing,
886 ast::Pat::RangePat(_) => Pat::Missing,
888 let ptr = AstPtr::new(&pat);
889 self.alloc_pat(pattern, Either::Left(ptr))
892 fn collect_pat_opt(&mut self, pat: Option<ast::Pat>) -> PatId {
893 if let Some(pat) = pat {
894 self.collect_pat(pat)
900 fn collect_tuple_pat(&mut self, args: AstChildren<ast::Pat>) -> (Vec<PatId>, Option<usize>) {
901 // Find the location of the `..`, if there is one. Note that we do not
902 // consider the possibility of there being multiple `..` here.
903 let ellipsis = args.clone().position(|p| matches!(p, ast::Pat::RestPat(_)));
904 // We want to skip the `..` pattern here, since we account for it above.
906 .filter(|p| !matches!(p, ast::Pat::RestPat(_)))
907 .map(|p| self.collect_pat(p))
913 /// Returns `None` (and emits diagnostics) when `owner` if `#[cfg]`d out, and `Some(())` when
915 fn check_cfg(&mut self, owner: &dyn ast::AttrsOwner) -> Option<()> {
916 match self.expander.parse_attrs(self.db, owner).cfg() {
918 if self.expander.cfg_options().check(&cfg) != Some(false) {
922 self.source_map.diagnostics.push(BodyDiagnostic::InactiveCode {
924 self.expander.current_file_id,
925 SyntaxNodePtr::new(owner.syntax()),
928 opts: self.expander.cfg_options().clone(),
938 impl From<ast::LiteralKind> for Literal {
939 fn from(ast_lit_kind: ast::LiteralKind) -> Self {
941 // FIXME: these should have actual values filled in, but unsure on perf impact
942 LiteralKind::IntNumber(lit) => {
943 if let builtin @ Some(_) = lit.suffix().and_then(BuiltinFloat::from_suffix) {
944 Literal::Float(Default::default(), builtin)
945 } else if let builtin @ Some(_) =
946 lit.suffix().and_then(|it| BuiltinInt::from_suffix(it))
948 Literal::Int(lit.value().unwrap_or(0) as i128, builtin)
950 let builtin = lit.suffix().and_then(|it| BuiltinUint::from_suffix(it));
951 Literal::Uint(lit.value().unwrap_or(0), builtin)
954 LiteralKind::FloatNumber(lit) => {
955 let ty = lit.suffix().and_then(|it| BuiltinFloat::from_suffix(it));
956 Literal::Float(Default::default(), ty)
958 LiteralKind::ByteString(bs) => {
959 let text = bs.value().map(Vec::from).unwrap_or_else(Default::default);
960 Literal::ByteString(text)
962 LiteralKind::String(_) => Literal::String(Default::default()),
963 LiteralKind::Byte => Literal::Uint(Default::default(), Some(BuiltinUint::U8)),
964 LiteralKind::Bool(val) => Literal::Bool(val),
965 LiteralKind::Char => Literal::Char(Default::default()),