aboutsummaryrefslogtreecommitdiff
path: root/src/test/java/org/shedlang/compiler/shid/ShidCodeGenWhileTests.java
blob: 5e1ce2c45ba86072af8bc3d3f1157d3c9e4f956b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
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 ShidCodeGenWhileTests {
    @Test
    public void whileIsCompiledToLoop() {
        var node = Typed.while_(
            Typed.reference("c"),
            Typed.block(List.of(
                Typed.expressionStatement(Typed.intLiteral(42))
            ))
        );
        var context = ShidCodeGen.Context.EMPTY
            .addShedVal("c");

        var result = ShidCodeGen.compileFunctionStatement(node, context);

        assertThat(result.instructions(), isSequence(
            isShidLoop(
                isShidBlock(isSequence(
                    isShidLocalLoad("c__0"),
                    isShidIf(
                        isShidBlock(isSequence()),
                        isShidBlock(isSequence(
                            isShidLoopBreak()
                        ))
                    ),
                    isShidBlock(isSequence(
                        isShidPushInt(42),
                        isShidDiscard()
                    )),
                    isShidLoopContinue()
                ))
            )
        ));
    }

    @Test
    public void whenBodyYieldsValueThenValueIsDiscarded() {
        // In principle, the type checker should prevent the body from yielding
        // a value, but we check we handle this case anyway.
        var node = Typed.while_(
            Typed.reference("c"),
            Typed.block(List.of(
                Typed.blockReturn(Typed.intLiteral(42))
            ))
        );
        var context = ShidCodeGen.Context.EMPTY
            .addShedVal("c");

        var result = ShidCodeGen.compileFunctionStatement(node, context);

        assertThat(result.instructions(), isSequence(
            isShidLoop(
                isShidBlock(isSequence(
                    isShidLocalLoad("c__0"),
                    isShidIf(
                        isShidBlock(isSequence()),
                        isShidBlock(isSequence(
                            isShidLoopBreak()
                        ))
                    ),
                    isShidBlock(isSequence(
                        isShidPushInt(42),
                        isShidDiscard()
                    )),
                    isShidLoopContinue()
                ))
            )
        ));
    }
}