From f51a33901de390c670b92587dd4020fe83a7e474 Mon Sep 17 00:00:00 2001 From: DBooots Date: Wed, 18 Feb 2026 23:43:03 -0600 Subject: [PATCH 1/2] Implement try-catch for conditional branch Added error handling for type conversion in branch instructions to align with the not opcode. See https://github.com/KSP-KOS/KOS/issues/3094 --- src/kOS.Safe/Compilation/Opcode.cs | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/src/kOS.Safe/Compilation/Opcode.cs b/src/kOS.Safe/Compilation/Opcode.cs index d7a65a8d1..17a5b8f02 100644 --- a/src/kOS.Safe/Compilation/Opcode.cs +++ b/src/kOS.Safe/Compilation/Opcode.cs @@ -1058,9 +1058,15 @@ public class OpcodeBranchIfFalse : BranchOpcode public override void Execute(ICpu cpu) { - bool condition = Convert.ToBoolean(cpu.PopValueArgument()); - - DeltaInstructionPointer = !condition ? Distance : 1; + try + { + bool condition = Convert.ToBoolean(cpu.PopValueArgument()); + DeltaInstructionPointer = !condition ? Distance : 1; + } + catch + { + throw new KOSCastException(value.GetType(), typeof(BooleanValue)); + } } } @@ -1079,8 +1085,15 @@ public class OpcodeBranchIfTrue : BranchOpcode public override void Execute(ICpu cpu) { - bool condition = Convert.ToBoolean(cpu.PopValueArgument()); - DeltaInstructionPointer = condition ? Distance : 1; + try + { + bool condition = Convert.ToBoolean(cpu.PopValueArgument()); + DeltaInstructionPointer = condition ? Distance : 1; + } + catch + { + throw new KOSCastException(value.GetType(), typeof(BooleanValue)); + } } } From cd50bb0505a27b79d445d72140c51f14f2c25647 Mon Sep 17 00:00:00 2001 From: DBooots Date: Wed, 18 Feb 2026 23:45:29 -0600 Subject: [PATCH 2/2] Remove redundant not -> branch if false in favor of branch if true Fixes https://github.com/KSP-KOS/KOS/issues/3094 --- src/kOS.Safe/Compilation/KS/Compiler.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/kOS.Safe/Compilation/KS/Compiler.cs b/src/kOS.Safe/Compilation/KS/Compiler.cs index 2de644b33..b31533f8c 100644 --- a/src/kOS.Safe/Compilation/KS/Compiler.cs +++ b/src/kOS.Safe/Compilation/KS/Compiler.cs @@ -2386,8 +2386,7 @@ private void VisitUntilStatement(ParseNode node) string conditionLabel = GetNextLabel(false); PushBreakList(braceNestLevel); VisitNode(node.Nodes[1]); - AddOpcode(new OpcodeLogicNot()); - Opcode branch = AddOpcode(new OpcodeBranchIfFalse()); + Opcode branch = AddOpcode(new OpcodeBranchIfTrue()); AddToBreakList(branch); VisitNode(node.Nodes[2]); Opcode jump = AddOpcode(new OpcodeBranchJump());