From 39f3efd86e5d9399cf2de0e553d4c4b505c0aa1c Mon Sep 17 00:00:00 2001 From: Iris Ward Date: Sun, 18 Dec 2016 00:19:58 +0000 Subject: [PATCH] Fix incorrect if/elseif/else code generation Fix the incorrect tests that passed erroneously Prevent a missing else from generating an empty else statement in code Move the offset pointing to within else to the correct position --- src/Compiler/QbScript/CodeGen.hs | 3 ++- test/Compiler/QbScript/CodeGen/Tests.hs | 12 +++++++++++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/src/Compiler/QbScript/CodeGen.hs b/src/Compiler/QbScript/CodeGen.hs index c0c84ad..16514af 100644 --- a/src/Compiler/QbScript/CodeGen.hs +++ b/src/Compiler/QbScript/CodeGen.hs @@ -161,13 +161,14 @@ putElseIfs = mapM_ putElseIf modify $ updateHoles nh' lh' putElse :: [Instruction] -> StateT BranchState Packing () +putElse [] = pure () putElse body = do BranchState nh lastHoles <- get h' <- lift $ do putWord8 0x01 - fillOffsetHole nh putWord8 0x48 nextHole <- putOffsetHole + fillOffsetHole nh mapM_ putInstr body return nextHole diff --git a/test/Compiler/QbScript/CodeGen/Tests.hs b/test/Compiler/QbScript/CodeGen/Tests.hs index 93a2eba..e574d6c 100644 --- a/test/Compiler/QbScript/CodeGen/Tests.hs +++ b/test/Compiler/QbScript/CodeGen/Tests.hs @@ -30,12 +30,22 @@ instrTests = it "generates an assignment correctly" $ testPacking (putInstr (Assign (NonLocal . QbName $ "x") (ELit . SmallLit . LitN $ 2))) `shouldBe` [0x01, 0x16, 0x7C, 0xE9, 0x23, 0x73, 0x07, 0x17, 0x02, 0x00, 0x00, 0x00] + it "generates an if with no else branches correctly" $ + testPacking (putInstr (IfElse (ELit LitPassthrough, [BareExpr $ ELit LitPassthrough]) + [] [])) + `shouldBe` [ 0x01, 0x47, 0x07, 0x00, 0x2C, 0x01, 0x2C, 0x01, 0x28 ] + it "generates an if/else correctly" $ + testPacking (putInstr (IfElse (ELit LitPassthrough, [BareExpr $ ELit LitPassthrough]) + [] + [BareExpr $ ELit LitPassthrough])) + `shouldBe` [ 0x01, 0x47, 0x09, 0x00, 0x2C, 0x01, 0x2C + , 0x01, 0x48, 0x06, 0x00, 0x01, 0x2C, 0x01, 0x28] it "generates an if/elseif/else correctly" $ testPacking (putInstr (IfElse (ELit LitPassthrough, [BareExpr $ ELit LitPassthrough]) [(ELit LitPassthrough, [BareExpr $ ELit LitPassthrough])] [BareExpr $ ELit LitPassthrough])) `shouldBe` [ 0x01, 0x47, 0x06, 0x00, 0x2C, 0x01, 0x2C - , 0x01, 0x27, 0x08, 0x00, 0x0D, 0x00, 0x2C, 0x01, 0x2C + , 0x01, 0x27, 0x0B, 0x00, 0x0D, 0x00, 0x2C, 0x01, 0x2C , 0x01, 0x48, 0x06, 0x00, 0x01, 0x2C, 0x01, 0x28 ] it "generates a repeat correctly" $ testPacking (putInstr (Repeat (ELit . SmallLit . LitN $ 4) [BareExpr $ ELit LitPassthrough]))