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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
|
package org.shedlang.compiler.shid;
import org.junit.jupiter.api.Test;
import org.shedlang.compiler.ast.typed.BoundVariable;
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 ShidCodeGenValTests {
@Test
public void whenValIsFunctionStatementThenExpressionIsEvaluatedAndStoredAsLocal() {
var node = Typed.val("x", Typed.stringLiteral("hello"));
var context = ShidCodeGen.Context.EMPTY
.addShedVal("x");
var result = ShidCodeGen.compileFunctionStatement(node, context);
assertThat(result.instructions(), isSequence(
isShidPushString("hello"),
isShidLocalStore("x__0")
));
}
@Test
public void whenValIsNamespaceStatementThenExpressionIsEvaluatedAndStoredAsLocal() {
var node = Typed.val("x", Typed.stringLiteral("hello"));
var context = ShidCodeGen.Context.EMPTY
.addShedVal("x");
var result = ShidCodeGen.compileNamespaceStatement(node, context);
assertThat(result.instructions(), isSequence(
isShidPushString("hello"),
isShidLocalStore("x__0")
));
}
@Test
public void valsInDifferentBlocksAssignToDifferentLocals() {
var nodes = List.of(
Typed.val("x", Typed.intLiteral(10)),
Typed.expressionStatement(Typed.reference("x")),
Typed.expressionStatement(Typed.if_(
List.of(
Typed.conditionalBranch(
Typed.boolLiteral(true),
Typed.block(
List.of(
Typed.val("x", Typed.intLiteral(11)),
Typed.expressionStatement(Typed.reference("x"))
),
List.of(BoundVariable.val("x"))
)
)
),
Typed.block(
List.of(
Typed.val("x", Typed.intLiteral(12)),
Typed.expressionStatement(Typed.reference("x"))
),
List.of(BoundVariable.val("x"))
),
Types.INT
)),
Typed.expressionStatement(Typed.reference("x"))
);
var context = ShidCodeGen.Context.EMPTY
.addShedVal("x");
for (var node : nodes) {
context = ShidCodeGen.compileFunctionStatement(node, context);
}
assertThat(context.instructions(), isSequence(
isShidPushInt(10),
isShidLocalStore("x__0"),
isShidLocalLoad("x__0"),
isShidDiscard(),
isShidPushBool(true),
isShidIf(
isShidBlock(isSequence(
isShidPushInt(11),
isShidLocalStore("x__1"),
isShidLocalLoad("x__1"),
isShidDiscard(),
isShidPushUnit()
)),
isShidBlock(isSequence(
isShidBlock(isSequence(
isShidPushInt(12),
isShidLocalStore("x__2"),
isShidLocalLoad("x__2"),
isShidDiscard(),
isShidPushUnit()
))
))
),
isShidDiscard(),
isShidLocalLoad("x__0"),
isShidDiscard()
));
}
}
|