From 9e6c89f1fa93287104381e02f0bbbdd6060a9382 Mon Sep 17 00:00:00 2001 From: AidenRushbrooke <72034940+AidenRushbrooke@users.noreply.github.com> Date: Sun, 5 Dec 2021 03:27:18 +0000 Subject: Added subroutines and comments for most files --- src/Compiler/Translator.java | 197 +++++++++++++++++++++++++++++++++++++++---- 1 file changed, 182 insertions(+), 15 deletions(-) (limited to 'src/Compiler/Translator.java') diff --git a/src/Compiler/Translator.java b/src/Compiler/Translator.java index e0bff23..d520b67 100644 --- a/src/Compiler/Translator.java +++ b/src/Compiler/Translator.java @@ -6,16 +6,25 @@ import java.util.List; import Compiler.Expression.*; import Compiler.Statement.*; - +/** + * Class to take a convert a list of statements into equivalent C source code + */ public class Translator{ List CCode = new ArrayList<>(); private Environment environment = new Environment(); - + /** + * Method to take a list of statements and convert to C code + * @param statements a list of statement objects + * @param printC a variable to say if the produced C code should be outputted + * @return a list of strings for each line of the produced C code + */ public List compileToC(List statements, boolean printC){ + //Write basic include header files CCode.add("#include "); CCode.add("#include "); + //Try and write each statement, with a space between each try{ for (Statement statement: statements){ evaluateStatement(statement); @@ -25,6 +34,7 @@ public class Translator{ } + //Output the C code if desired if (printC) { for(String t:CCode){ System.out.println(t); @@ -34,7 +44,12 @@ public class Translator{ return CCode; } + /** + * Method to write a single statement to C + * @param statement the statement to write to C + */ private void evaluateStatement(Statement statement){ + //Call the correct function for each statement type switch(statement.getStatmentType()){ case "main": evalMainFunction((MainFunction)statement); @@ -78,40 +93,76 @@ public class Translator{ } } + /** + * Method to write the main function + * @param stmt statement to write + */ private void evalMainFunction(MainFunction stmt){ CCode.add("int main(){"); evaluateStatement(stmt.block); CCode.add("}"); } + /** + * Method to write a function + * @param stmt statement to write + */ private void evalFunction(Function stmt){ - - String functionString = stmt.returnType+" "+stmt.name.text+"("; + String functionString; + if(!(stmt.returnType==null)){ + functionString = stmt.returnType+" "+stmt.name.text+"("; + }else{ + functionString = "void "+stmt.name.text+"("; + } boolean first=true; + //Write each function argument into C for(int i=0;i