Skip to content

Commit

Permalink
Fix switch tests
Browse files Browse the repository at this point in the history
  • Loading branch information
voltrevo committed Jul 6, 2023
1 parent ced2b3c commit 9000487
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 10 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
//! test_output(["default","matched 42"])
// Should be: ["matched 42"]
//! test_output(["matched 42"])

export default function foo() {
let logs: string[] = [];
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
//! test_output(["c1","default"])
// Should be: ["c1","c2","default"]
//! test_output(["c1","c2","default"])

export default function foo() {
let logs = [];
Expand Down
20 changes: 14 additions & 6 deletions valuescript_compiler/src/function_compiler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -673,7 +673,7 @@ impl FunctionCompiler {
.collect::<Vec<Label>>();

let cond_reg = ec.fnc.allocate_numbered_reg("_sw_cond");
let mut has_default = false;
let mut default_i: Option<usize> = None;

for (i, case) in switch.cases.iter().enumerate() {
match &case.test {
Expand All @@ -694,15 +694,23 @@ impl FunctionCompiler {
}
// default:
None => {
has_default = true;
ec.fnc.push(Instruction::Jmp(case_labels[i].ref_()));
if default_i.is_some() {
ec.fnc.diagnostics.push(Diagnostic {
level: DiagnosticLevel::Error,
message: "A switch can only have one default".to_string(),
span: case.span,
});
}

default_i = Some(i);
}
};
}

if !has_default {
ec.fnc.push(Instruction::Jmp(end_label.ref_()));
}
ec.fnc.push(Instruction::Jmp(match default_i {
Some(default_i) => case_labels[default_i].ref_(),
None => end_label.ref_(),
}));

for (i, case) in switch.cases.iter().enumerate() {
ec.fnc.label(case_labels[i].clone());
Expand Down

0 comments on commit 9000487

Please sign in to comment.