From 55436caa9ae9c179639a4b238fc358ee7d768645 Mon Sep 17 00:00:00 2001 From: kbkpbot Date: Mon, 1 Dec 2025 19:47:16 +0800 Subject: [PATCH] cgen: fix nested or in assign decl (fix #25864) (#25865) --- vlib/v/gen/c/assign.v | 16 ++++++++++---- vlib/v/tests/nested_or_in_assign_decl_test.v | 23 ++++++++++++++++++++ 2 files changed, 35 insertions(+), 4 deletions(-) create mode 100644 vlib/v/tests/nested_or_in_assign_decl_test.v diff --git a/vlib/v/gen/c/assign.v b/vlib/v/gen/c/assign.v index ed41b0c36..5c6281196 100644 --- a/vlib/v/gen/c/assign.v +++ b/vlib/v/gen/c/assign.v @@ -37,16 +37,24 @@ fn (mut g Gen) expr_with_opt_or_block(expr ast.Expr, expr_typ ast.Type, var_expr or_expr := (expr as ast.Ident).or_expr stmts := or_expr.stmts scope := or_expr.scope + last_stmt := stmts.last() // handles stmt block which returns something // e.g. { return none } - if stmts.len > 0 && stmts.last() is ast.ExprStmt && stmts.last().typ != ast.void_type { - g.gen_or_block_stmts(c_name(var_expr.str()), '', stmts, ret_typ, false, - scope, expr.pos()) + if stmts.len > 0 && last_stmt is ast.ExprStmt && last_stmt.typ != ast.void_type { + var_expr_name := c_name(var_expr.str()) + if last_stmt.expr is ast.Ident && last_stmt.expr.or_expr.kind != .absent { + g.write('${var_expr_name} = ') + g.expr_with_opt_or_block(last_stmt.expr, last_stmt.typ, var_expr, + ret_typ, in_heap) + } else { + g.gen_or_block_stmts(var_expr_name, '', stmts, ret_typ, false, scope, + expr.pos()) + } } else { // handles stmt block which doesn't returns value // e.g. { return } g.stmts(stmts) - if stmts.len > 0 && stmts.last() is ast.ExprStmt { + if stmts.len > 0 && last_stmt is ast.ExprStmt { g.writeln(';') } g.write_defer_stmts(scope, false, expr.pos()) diff --git a/vlib/v/tests/nested_or_in_assign_decl_test.v b/vlib/v/tests/nested_or_in_assign_decl_test.v new file mode 100644 index 000000000..2a21c9739 --- /dev/null +++ b/vlib/v/tests/nested_or_in_assign_decl_test.v @@ -0,0 +1,23 @@ +module main + +fn fx1() ?int { + return none +} + +fn fx2() ?int { + return none +} + +fn fx3() ?int { + return none +} + +fn test_nested_or_in_assign_decl() { + x1 := fx1() + x2 := fx2() + x3 := fx3() + def := 123 + + y := x1 or { x2 or { x3 or { def } } } + assert y == 123 +} -- 2.39.5