cgen: fix multi-return in if/match exprs (#12139)
							parent
							
								
									0f7dfb984a
								
							
						
					
					
						commit
						e69df54a36
					
				|  | @ -4879,7 +4879,10 @@ fn (mut g Gen) cast_expr(node ast.CastExpr) { | ||||||
| } | } | ||||||
| 
 | 
 | ||||||
| fn (mut g Gen) concat_expr(node ast.ConcatExpr) { | fn (mut g Gen) concat_expr(node ast.ConcatExpr) { | ||||||
| 	styp := g.typ(node.return_type) | 	mut styp := g.typ(node.return_type) | ||||||
|  | 	if g.inside_return { | ||||||
|  | 		styp = g.typ(g.fn_decl.return_type) | ||||||
|  | 	} | ||||||
| 	sym := g.table.get_type_symbol(node.return_type) | 	sym := g.table.get_type_symbol(node.return_type) | ||||||
| 	is_multi := sym.kind == .multi_return | 	is_multi := sym.kind == .multi_return | ||||||
| 	if !is_multi { | 	if !is_multi { | ||||||
|  | @ -5163,8 +5166,8 @@ fn (mut g Gen) return_stmt(node ast.Return) { | ||||||
| 	} | 	} | ||||||
| 	// regular cases
 | 	// regular cases
 | ||||||
| 	if fn_return_is_multi && node.exprs.len > 0 && !g.expr_is_multi_return_call(node.exprs[0]) { | 	if fn_return_is_multi && node.exprs.len > 0 && !g.expr_is_multi_return_call(node.exprs[0]) { | ||||||
| 		if node.exprs.len == 1 && node.exprs[0] is ast.IfExpr { | 		if node.exprs.len == 1 && (node.exprs[0] is ast.IfExpr || node.exprs[0] is ast.MatchExpr) { | ||||||
| 			// use a temporary for `return if cond { x,y } else { a,b }`
 | 			// use a temporary for `return if cond { x,y } else { a,b }` or `return match expr { abc { x, y } else { z, w } }`
 | ||||||
| 			g.write('$ret_typ $tmpvar = ') | 			g.write('$ret_typ $tmpvar = ') | ||||||
| 			g.expr(node.exprs[0]) | 			g.expr(node.exprs[0]) | ||||||
| 			g.writeln(';') | 			g.writeln(';') | ||||||
|  |  | ||||||
|  | @ -82,3 +82,29 @@ fn test_multi_values() { | ||||||
| 	assert x == 'abc' | 	assert x == 'abc' | ||||||
| 	assert y == 'def' | 	assert y == 'def' | ||||||
| } | } | ||||||
|  | 
 | ||||||
|  | fn match_expr(x bool) (int, int) { | ||||||
|  | 	return match x { | ||||||
|  | 		true { 1, 1 } | ||||||
|  | 		else { 0, 0 } | ||||||
|  | 	} | ||||||
|  | } | ||||||
|  | 
 | ||||||
|  | fn if_expr(x bool) (int, int) { | ||||||
|  | 	return if x { 3, 3 } else { 2, 2 } | ||||||
|  | } | ||||||
|  | 
 | ||||||
|  | fn test_multi_return_if_match_expr() { | ||||||
|  | 	a, b := match_expr(true) | ||||||
|  | 	c, d := match_expr(false) | ||||||
|  | 	x, y := if_expr(true) | ||||||
|  | 	z, w := if_expr(false) | ||||||
|  | 	assert a == 1 | ||||||
|  | 	assert b == 1 | ||||||
|  | 	assert c == 0 | ||||||
|  | 	assert d == 0 | ||||||
|  | 	assert x == 3 | ||||||
|  | 	assert y == 3 | ||||||
|  | 	assert z == 2 | ||||||
|  | 	assert w == 2 | ||||||
|  | } | ||||||
|  |  | ||||||
		Loading…
	
		Reference in New Issue