From 31ee062ad12adcf6dae6716cb566fcbcde9f6959 Mon Sep 17 00:00:00 2001 From: geno Date: Thu, 18 Jul 2024 12:16:40 +0200 Subject: codegen while implemented, test added --- src/ast/Python3VisitorImpl.java | 2 -- src/ast/nodes/WhileStmtNode.java | 18 ++++++++++++++---- src/codegen/Label.java | 2 +- test/2f.py | 4 ++-- test/2g-fibonacci.py | 13 +++++++++++++ 5 files changed, 30 insertions(+), 9 deletions(-) create mode 100644 test/2g-fibonacci.py diff --git a/src/ast/Python3VisitorImpl.java b/src/ast/Python3VisitorImpl.java index e6728d5..7e8881f 100644 --- a/src/ast/Python3VisitorImpl.java +++ b/src/ast/Python3VisitorImpl.java @@ -504,7 +504,6 @@ public class Python3VisitorImpl extends Python3ParserBaseVisitor { } private void optimizeWithThird(BlockNode block, int lineStart, int lineStop, int index) { - int counter = 0; ArrayList stms = block.getChilds(); for (var e : stms) { if (e instanceof SimpleStmtsNode) { @@ -543,7 +542,6 @@ public class Python3VisitorImpl extends Python3ParserBaseVisitor { rewriter.replace(firstToken, lastToken, newVar); } } - counter++; } } } diff --git a/src/ast/nodes/WhileStmtNode.java b/src/ast/nodes/WhileStmtNode.java index 43bf5ff..64b0b71 100644 --- a/src/ast/nodes/WhileStmtNode.java +++ b/src/ast/nodes/WhileStmtNode.java @@ -4,6 +4,7 @@ import ast.types.*; import java.util.ArrayList; import semanticanalysis.SemanticError; import semanticanalysis.SymbolTable; +import codegen.Label; /** * Node for the `while_stmt` statement of the grammar. @@ -33,12 +34,21 @@ public class WhileStmtNode implements Node { 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 diff --git a/src/codegen/Label.java b/src/codegen/Label.java index a301ede..61403d8 100644 --- a/src/codegen/Label.java +++ b/src/codegen/Label.java @@ -41,6 +41,6 @@ public class Label { public static String newVar() { - return "_tmp" + (varDefCount++); + return "tmp" + (varDefCount++); } } diff --git a/test/2f.py b/test/2f.py index d83457b..fa71493 100644 --- a/test/2f.py +++ b/test/2f.py @@ -3,8 +3,8 @@ n = 6 counter = 1 result = 1 -while n - 1 == counter: +while n - 1 != counter: result = result * counter - counter = counter - 1 + counter = counter + 1 print(result) diff --git a/test/2g-fibonacci.py b/test/2g-fibonacci.py new file mode 100644 index 0000000..fb1ac9f --- /dev/null +++ b/test/2g-fibonacci.py @@ -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) -- cgit v1.2.3-18-g5258