Skip to content

Commit

Permalink
codegen while implemented, test added
Browse files Browse the repository at this point in the history
  • Loading branch information
gabrielegenovese committed Jul 18, 2024
1 parent 6353601 commit 31ee062
Show file tree
Hide file tree
Showing 5 changed files with 30 additions and 9 deletions.
2 changes: 0 additions & 2 deletions src/ast/Python3VisitorImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -504,7 +504,6 @@ public Node visitFor_stmt(For_stmtContext ctx) {
}

private void optimizeWithThird(BlockNode block, int lineStart, int lineStop, int index) {
int counter = 0;
ArrayList<Node> stms = block.getChilds();
for (var e : stms) {
if (e instanceof SimpleStmtsNode) {
Expand Down Expand Up @@ -543,7 +542,6 @@ private void optimizeWithThird(BlockNode block, int lineStart, int lineStop, int
rewriter.replace(firstToken, lastToken, newVar);
}
}
counter++;
}
}
}
Expand Down
18 changes: 14 additions & 4 deletions src/ast/nodes/WhileStmtNode.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import java.util.ArrayList;
import semanticanalysis.SemanticError;
import semanticanalysis.SymbolTable;
import codegen.Label;

/**
* Node for the `while_stmt` statement of the grammar.
Expand Down Expand Up @@ -33,12 +34,21 @@ public Type typeCheck() {
return new VoidType();
}

/**
* NOTE: It is not a part for this project.
*/
@Override
public String codeGeneration() {
return "";
String startLabel = Label.newBasic("start");
String endLabel = Label.newBasic("end");

String exprS = expr.codeGeneration();
String blockS = block.codeGeneration();

return startLabel + ":\n" +
exprS +
"storei T1 0\n" +
"beq A0 T1 " + endLabel + "\n" +
blockS +
"b " + startLabel + "\n" +
endLabel + ":\n";
}

@Override
Expand Down
2 changes: 1 addition & 1 deletion src/codegen/Label.java
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,6 @@ public static String newFun(String base) {


public static String newVar() {
return "_tmp" + (varDefCount++);
return "tmp" + (varDefCount++);
}
}
4 changes: 2 additions & 2 deletions test/2f.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
counter = 1
result = 1

while n - 1 == counter:
while n - 1 != counter:
result = result * counter
counter = counter - 1
counter = counter + 1

print(result)
13 changes: 13 additions & 0 deletions test/2g-fibonacci.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
n = 9

a = 0
b = 1
c = 0
i = 0
while i < n - 2:
c = a + b
a = b
b = c
i = i + 1

print(c)

0 comments on commit 31ee062

Please sign in to comment.