diff options
| author | Melodi <62381002+Melodi17@users.noreply.github.com> | 2025-08-09 00:16:57 +1000 |
|---|---|---|
| committer | Melodi <62381002+Melodi17@users.noreply.github.com> | 2025-08-09 00:16:57 +1000 |
| commit | d36d51429d604f0ab3b2076c4c05e28ebf9b52c5 (patch) | |
| tree | 9a3755684359aa041bf391f4ef5d3f30837a2271 /Compiler/CCompilerVisitor.cs | |
| parent | e62b66dd08ca445d1f7e5b802a503ad3ec83b2df (diff) | |
updated block syntax and removed body grammar, fixed issue with if requiring an else branch
Diffstat (limited to 'Compiler/CCompilerVisitor.cs')
| -rw-r--r-- | Compiler/CCompilerVisitor.cs | 34 |
1 files changed, 22 insertions, 12 deletions
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?> { 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); |
