From d36d51429d604f0ab3b2076c4c05e28ebf9b52c5 Mon Sep 17 00:00:00 2001 From: Melodi <62381002+Melodi17@users.noreply.github.com> Date: Sat, 9 Aug 2025 00:16:57 +1000 Subject: updated block syntax and removed body grammar, fixed issue with if requiring an else branch --- Compiler/CCompilerVisitor.cs | 34 ++++++++++++++++++++++------------ 1 file changed, 22 insertions(+), 12 deletions(-) (limited to 'Compiler/CCompilerVisitor.cs') diff --git a/Compiler/CCompilerVisitor.cs b/Compiler/CCompilerVisitor.cs index aa08147..fb7df0f 100644 --- a/Compiler/CCompilerVisitor.cs +++ b/Compiler/CCompilerVisitor.cs @@ -546,23 +546,33 @@ public class CCompilerVisitor : CGrammarBaseVisitor { string cond = this.Visit(context.expression()) ?? throw new CompilerException("If condition was not an expression"); - - // Else branch is first since it saves us from having to perform a NOT operation. - // If cond, jump to then, else fall through to else, then jump to end - - string thenBranch = this.GenerateBranchLabel("then"); string endBranch = this.GenerateBranchLabel("end"); this.Instruction($"bz {cond}", "check if condition"); - this.Instruction($"jmp {thenBranch}"); - - this.GeneratedComment("if failed"); + if (context.@else != null) - this.Visit(context.@else); - this.Instruction($"jmp {endBranch}"); + { + // Else branch is first since it saves us from having to perform a NOT operation. + // If cond, jump to then, else fall through to else, then jump to end + + string thenBranch = this.GenerateBranchLabel("then"); + + this.Instruction($"jmp {thenBranch}"); + + this.GeneratedComment("if failed"); + if (context.@else != null) + this.Visit(context.@else); + this.Instruction($"jmp {endBranch}"); - this.Label(thenBranch, "if succeeded"); - this.Visit(context.then); + this.Label(thenBranch, "if succeeded"); + this.Visit(context.then); + } + else + { + this.Instruction($"not"); + this.Instruction($"jmp {endBranch}", "if succeeds, continue, else jump to end"); + this.Visit(context.then); + } this.Label(endBranch); -- cgit v1.3.1