Skip to content

Add compiling of boolean expressions to stack IR #42

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 4, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -343,15 +343,47 @@ private boolean compileSymbolExpr(AST.NameExpr symbolExpr) {
return false;
}

private boolean codeBoolean(AST.BinaryExpr binaryExpr) {
boolean isAnd = binaryExpr.op.str.equals("&&");
BasicBlock l1 = createBlock();
BasicBlock l2 = createBlock();
BasicBlock l3 = createBlock();
boolean indexed = compileExpr(binaryExpr.expr1);
if (indexed)
codeIndexedLoad();
if (isAnd) {
code(new Instruction.ConditionalBranch(currentBlock, l1, l2));
} else {
code(new Instruction.ConditionalBranch(currentBlock, l2, l1));
}
startBlock(l1);
indexed = compileExpr(binaryExpr.expr2);
if (indexed)
codeIndexedLoad();
jumpTo(l3);
startBlock(l2);
// Below we must write to the same temp
code(new Instruction.PushConst(isAnd ? 0 : 1));
jumpTo(l3);
startBlock(l3);
// leaves result on stack
return false;
}

private boolean compileBinaryExpr(AST.BinaryExpr binaryExpr) {
String binOp = binaryExpr.op.str;
if (binOp.equals("&&") ||
binOp.equals("||")) {
return codeBoolean(binaryExpr);
}
int opCode = 0;
boolean indexed = compileExpr(binaryExpr.expr1);
if (indexed)
codeIndexedLoad();
indexed = compileExpr(binaryExpr.expr2);
if (indexed)
codeIndexedLoad();
switch (binaryExpr.op.str) {
switch (binOp) {
case "+" -> opCode = Instruction.ADD_I;
case "-" -> opCode = Instruction.SUB_I;
case "*" -> opCode = Instruction.MUL_I;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -634,4 +634,34 @@ public void testFunction28() {
L1:
""", result);
}

@Test
public void testFunction104() {
String src = """
func foo()->Int
{
return 1 == 1 && 2 == 2
}
""";
String result = compileSrc(src);
Assert.assertEquals("""
L0:
pushi 1
pushi 1
eq
cbr L2 L3
L2:
pushi 2
pushi 2
eq
jump L4
L4:
jump L1
L1:
L3:
pushi 0
jump L4
""", result);
}

}