Browse Source

added if statements

rlbr-dev
Larry Xue 5 years ago
parent
commit
27d279c490
  1. 30
      c2logic/compiler.py
  2. 8
      examples/test.c
  3. 15
      examples/test2.c

30
c2logic/compiler.py

@ -54,7 +54,7 @@ class Compiler(c_ast.NodeVisitor):
out2 = []
for instruction in instructions:
if isinstance(instruction, RelativeJump):
instruction.func_start = function.start #FIXME
instruction.func_start = function.start
out2.append(str(instruction))
out.append("\n".join(out2))
return "\n\n".join(out)
@ -178,7 +178,6 @@ class Compiler(c_ast.NodeVisitor):
self.loop_start = len(self.curr_function.instructions)
self.visit(node.cond)
# jump over loop body when cond is false
print(self.peek())
if isinstance(self.peek(), BinaryOp):
self.push(RelativeJump(None, JumpCondition.from_binaryop(self.pop())))
else:
@ -190,6 +189,33 @@ class Compiler(c_ast.NodeVisitor):
for offset in self.loop_end_jumps:
self.curr_function.instructions[offset].offset = len(self.curr_function.instructions)
def visit_If(self, node):
self.visit(node.cond)
# jump over if body when cond is false
#TODO optimize for when cond is a binary operation
if isinstance(self.peek(), BinaryOp):
self.push(RelativeJump(None, JumpCondition("!=", "__rax", "0")))
else:
self.push(RelativeJump(None, JumpCondition("!=", "__rax", "0")))
cond_jump_offset = len(self.curr_function.instructions) - 1
self.visit(node.iftrue)
#jump over else body from end of if body
if node.iffalse is not None:
self.push(RelativeJump(None, JumpCondition("==", "0", "0")))
cond_jump_offset2 = len(self.curr_function.instructions) - 1
self.curr_function.instructions[cond_jump_offset].offset = len(
self.curr_function.instructions
)
if node.iffalse is not None:
self.visit(node.iffalse)
self.curr_function.instructions[cond_jump_offset2].offset = len(
self.curr_function.instructions
)
def visit_Break(self, node):
self.push(RelativeJump(None, JumpCondition("==", "0", "0")))
self.loop_end_jumps.append(len(self.curr_function.instructions) - 1)
def visit_FuncCall(self, node):
name = node.name.name
if name == "_asm":

8
examples/test.c

@ -3,12 +3,6 @@ extern struct MindustryObject message1;
extern struct MindustryObject swarmer1;
extern struct MindustryObject conveyor1;
void main(void) {
/*double i = 0;
while (i < 10) {
print(i);
printflush(message1);
i += 1;
}*/
struct MindustryObject player = radar(swarmer1, "player", "any", "any", "distance", 0);
double x = sensor(player, "x");
double y = sensor(player, "y");
@ -17,5 +11,5 @@ void main(void) {
printd(y);
printflush(message1);
enable(conveyor1, x < 10);
shoot(swarmer1, 0, 0, x > 10);
shoot(swarmer1, 0, 0, 1);
}

15
examples/test2.c

@ -0,0 +1,15 @@
#include "mindustry.h"
extern struct MindustryObject message1;
void main(void) {
double i = 0;
while (i < 10) {
if (i == 3) {
print("is 3");
} else {
print("not 3");
}
}
printd(i);
print("\n");
printflush(message1);
}
Loading…
Cancel
Save