package org.shedlang.compiler.shid; import org.junit.jupiter.api.Test; import org.shedlang.compiler.ast.typed.Typed; 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 ShidCodeGenAssignTests { @Test public void targetIgnoreIsCompiledToDiscard() { var node = Typed.assign( Typed.targetIgnore(), Typed.reference("x") ); var context = ShidCodeGen.Context.EMPTY .addShedVal("x"); var result = ShidCodeGen.compileFunctionStatement(node, context); assertThat(result.instructions(), isSequence( isShidLocalLoad("x__0"), isShidDiscard() )); } @Test public void whenTargetIsReassignThenExpressionIsEvaluatedAndStoredAsVar() { var node = Typed.assign( Typed.targetReassign("x"), Typed.stringLiteral("hello") ); var context = ShidCodeGen.Context.EMPTY .addShedVal("x"); var result = ShidCodeGen.compileFunctionStatement(node, context); assertThat(result.instructions(), isSequence( isShidPushString("hello"), isShidVarStore("x__0") )); } @Test public void whenTargetIsTupleThenExpressionIsDeconstructed() { var node = Typed.assign( Typed.targetTuple(List.of( Typed.targetVal("a"), Typed.targetVal("b"), Typed.targetVal("c") )), Typed.reference("x") ); var context = ShidCodeGen.Context.EMPTY .addShedVal("x") .addShedVal("a") .addShedVal("b") .addShedVal("c"); var result = ShidCodeGen.compileFunctionStatement(node, context); assertThat(result.instructions(), isSequence( isShidLocalLoad("x__0"), isShidDuplicate(), isShidTupleGet(0), isShidLocalStore("a__0"), isShidDuplicate(), isShidTupleGet(1), isShidLocalStore("b__0"), isShidTupleGet(2), isShidLocalStore("c__0") )); } @Test public void deconstructingEmptyTupleDiscardsExpression() { var node = Typed.assign( Typed.targetTuple(List.of()), Typed.reference("x") ); var context = ShidCodeGen.Context.EMPTY .addShedVal("x"); var result = ShidCodeGen.compileFunctionStatement(node, context); assertThat(result.instructions(), isSequence( isShidLocalLoad("x__0"), isShidDiscard() )); } }