package Compiler; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; import java.util.Scanner; //Base class for the interpreter public class Language { static boolean hadError = false; public static void main(String[] args){ //Allow users to input a single line of code //Still needs some work to re-ask for input after each line if (args.length < 1){ Scanner input = new Scanner(System.in); String sourceCode = "1"; while (sourceCode!=""){ System.out.print("Code: "); sourceCode = input.nextLine(); runInterpreter(sourceCode, "out"); hadError=false; } input.close(); //Allow users to provide a path to a file as an argument } else if (args.length==1){ try { String sourcecode = Files.readString(Paths.get(args[0])); //Maybe should set charset here runInterpreter(sourcecode, args[0].split("\\.(?=[^\\.]+$)")[0]); } catch (IOException exception){ System.out.println("File not found"); } } else { System.out.println("Error, argument should be file path"); System.exit(64); } } //Function to take source code and output the result private static void runInterpreter(String sourceCode, String outName){ //Extract tokens from the source code TokenScanner scanner = new TokenScanner(); List tokens = scanner.extractTokens(sourceCode); //for (Token token : tokens) { // System.out.println(token); //} if (hadError) return; //Parse into AST Parser parser = new Parser(tokens); List ast = parser.parse(); if (hadError) return; //Translate AST into equivalent C code Translator translator = new Translator(); List code = translator.compileToC(ast); if (hadError) return; //Execute created C code ExecuteC cExecutor = new ExecuteC(); cExecutor.compileAndExecuteC(code, outName); } //Basic error reporting static void displayError(int line,String message){ hadError=true; System.out.println("An error was encountered on line: "+line); System.out.println(message); } //Basic error reporting static void displayError(Token token,String message){ hadError=true; System.out.println("An error was encountered on line: "+token.line); System.out.println("ERROR: "+token.text); System.out.println(message); } }