package org.shedlang.compiler.shid; import org.junit.jupiter.api.Test; import org.shedlang.compiler.ast.typed.Typed; import org.shedlang.compiler.types.Types; import java.util.List; import static org.shedlang.compiler.shid.instructions.ShidMatchers.*; import static org.zwobble.precisely.AssertThat.assertThat; import static org.zwobble.precisely.Matchers.isSequence; public class ShidCodeGenIfTests { @Test public void ifWithSingleConditionalBranchIsCompiledToSingleIfInstruction() { var node = Typed.if_( List.of( Typed.conditionalBranch( Typed.reference("c"), Typed.block(List.of( Typed.blockReturn(Typed.intLiteral(42)) )) ) ), Typed.block(List.of( Typed.functionReturn(Typed.stringLiteral("x")) )), Types.INT ); var context = ShidCodeGen.Context.EMPTY .addShedVal("c"); var result = ShidCodeGen.compileExpression(node, context); assertThat(result.instructions(), isSequence( isShidLocalLoad("c__0"), isShidIf( isShidBlock(isSequence( isShidPushInt(42) )), isShidBlock(isSequence( isShidBlock(isSequence( isShidPushString("x"), isShidReturn() )) )) ) )); } @Test public void ifWithMultipleConditionalBranchesIsCompiledToNestedIfInstructions() { var node = Typed.if_( List.of( Typed.conditionalBranch( Typed.reference("c"), Typed.block(List.of( Typed.blockReturn(Typed.intLiteral(42)) )) ), Typed.conditionalBranch( Typed.reference("d"), Typed.block(List.of( Typed.blockReturn(Typed.intLiteral(1)) )) ) ), Typed.block(List.of( Typed.functionReturn(Typed.stringLiteral("x")) )), Types.INT ); var context = ShidCodeGen.Context.EMPTY .addShedVal("c") .addShedVal("d"); var result = ShidCodeGen.compileExpression(node, context); assertThat(result.instructions(), isSequence( isShidLocalLoad("c__0"), isShidIf( isShidBlock(isSequence( isShidPushInt(42) )), isShidBlock(isSequence( isShidLocalLoad("d__0"), isShidIf( isShidBlock(isSequence( isShidPushInt(1) )), isShidBlock(isSequence( isShidBlock(isSequence( isShidPushString("x"), isShidReturn() )) )) ) )) ) )); } }