cgen: fix match expr multiline error
* cgen: fix match expr multiline error * Support for multiple statements in the else part of the match. * Add a test for the match expression with multiple statements.pull/4387/head
parent
d691f46f1e
commit
8cbdb75dd6
|
@ -324,11 +324,17 @@ pub fn (g mut Gen) reset_tmp_count() {
|
|||
|
||||
fn (g mut Gen) stmts(stmts []ast.Stmt) {
|
||||
g.indent++
|
||||
for stmt in stmts {
|
||||
if g.inside_ternary {
|
||||
g.write(' ( ')
|
||||
}
|
||||
for i, stmt in stmts {
|
||||
g.stmt(stmt)
|
||||
// if !g.inside_ternary {
|
||||
// g.writeln('')
|
||||
// }
|
||||
if g.inside_ternary && i < stmts.len - 1 {
|
||||
g.write(', ')
|
||||
}
|
||||
}
|
||||
if g.inside_ternary {
|
||||
g.write(' ) ')
|
||||
}
|
||||
g.indent--
|
||||
}
|
||||
|
|
|
@ -0,0 +1,66 @@
|
|||
|
||||
type SumType = int | string
|
||||
|
||||
fn s2s(s SumType) SumType { return s }
|
||||
|
||||
fn test_match_expression_on_sumtype_ordinary_branch(){
|
||||
// tests whether an ordinary branch supports multiple statements,
|
||||
// followed by a default expression
|
||||
mut c := 0
|
||||
s := s2s('abc')
|
||||
res := match s {
|
||||
string {
|
||||
c = 1
|
||||
eprintln('hi')
|
||||
'a string'
|
||||
}else{
|
||||
'unknown'
|
||||
}
|
||||
}
|
||||
assert res == 'a string'
|
||||
assert c == 1
|
||||
}
|
||||
|
||||
|
||||
fn test_match_expression_on_sumtype_else(){
|
||||
// tests whether else branches support multiple statements,
|
||||
// when the other branches are simple default expressions
|
||||
mut c := 0
|
||||
s := s2s(123)
|
||||
res := match s {
|
||||
string {
|
||||
'a string'
|
||||
}else{
|
||||
c = 3
|
||||
eprintln('hi')
|
||||
'unknown'
|
||||
}
|
||||
}
|
||||
assert res == 'unknown'
|
||||
assert c == 3
|
||||
}
|
||||
|
||||
fn test_match_expression_on_sumtype_full(){
|
||||
// tests whether all branches can have multiple statements,
|
||||
// followed by a default expression
|
||||
mut c := 0
|
||||
s := s2s(123)
|
||||
res := match s {
|
||||
int {
|
||||
c = 1
|
||||
eprintln('hi')
|
||||
'an integer'
|
||||
}
|
||||
string {
|
||||
c = 2
|
||||
eprintln('hi')
|
||||
'a string'
|
||||
}else{
|
||||
c = 3
|
||||
eprintln('hi')
|
||||
'unknown'
|
||||
}
|
||||
}
|
||||
assert res == 'an integer'
|
||||
assert c == 1
|
||||
}
|
Loading…
Reference in New Issue