summaryrefslogtreecommitdiffstats
path: root/src/Compiler/Language.java
blob: 549ea29834318def071d17591666a96a02dd65e1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
package Compiler;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.Path;
import java.util.List;
import java.util.Scanner;
import java.util.ArrayList;

/** 
 *Base class for running the Compiler 
 *Can run either from a file, or in an interactive mode
 */
public class Language {

    static boolean leaveCFile = false;
    static boolean hadError = false;
    static boolean printC = false;
    static boolean executeAfter = false;
    static Path sourcefile;

    //Main function for the compiler
    public static void main(String[] args) {

        //Extract required command line arguments
        try {
            sourcefile = Paths.get(args[0]);
        } catch (java.lang.ArrayIndexOutOfBoundsException e) {
            interactiveMode();
            return;
        }

        if (args[0].equals("-h") || args[0].equals("--help")) {
            System.out.println(getHelpText());
            return;
        }
    
        if (!(Files.exists(sourcefile))) {
            System.err.println("Could not find source code path.");
            return;
        }
        
        Path initOutPath = Paths.get(args[0]);
        String outname = initOutPath.getName(initOutPath.getNameCount() - 1).toString().split("\\.(?=[^\\.]+$)")[0];

        //Extract optional command line arguments
        ArrayList<String> arrayArgs = new ArrayList<>();
        for (int i = 0; i < args.length; i++) {
            String arg = args[i];
            arrayArgs.add(arg);
            if (arg.equals("-o") || arg.equals("--out")) {
                try {
                    outname = args[i + 1];
                } catch (java.lang.ArrayIndexOutOfBoundsException e) {
                    System.err.println("Invalid output name provided");
                    return;
                }
            }
            if (arg.equals("-c") || arg.equals("--keep-c-file")) {
                leaveCFile = true;
            }
            if (arg.equals("-pc") || arg.equals("--print-c")) {
                printC = true;
            }
            if (arg.equals("-e") || arg.equals("--execute")) {
                executeAfter = true;
            }
        }

        if (outname.startsWith("-")) {
            System.err.println("Invalid output name provided");
            return;
        }

        //Run the compiler on the source code
        try {
            runCompiler(Files.readString(sourcefile), outname);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /** 
     * Function to take source code, run the compiler and write to C
     *
     *  @param sourcecode the full source code as a string
     *  @param outName the name to write the compiled code to
     */
    private static void runCompiler(String sourceCode, String outName){
        //Extract tokens from the source code
        TokenScanner scanner = new TokenScanner();
        List<Token> tokens = scanner.extractTokens(sourceCode);
        if (hadError) return;

        //Parse into AST
        Parser parser = new Parser(tokens);
        List<Statement> ast = parser.parse();
        if (hadError) return;

        //Translate AST into equivalent C code
        Translator translator = new Translator();
        List<String> code = translator.compileToC(ast, printC);
        if (hadError) return;

        //Execute created C code
        ExecuteC cExecutor = new ExecuteC();
        cExecutor.compileAndExecuteC(code, outName, executeAfter, leaveCFile);
    }

    /**
     * Method for running the compiler in an interactive mode
     */
    private static void interactiveMode() {
        Scanner input = new Scanner(System.in);
        String sourceCode = "1";
        //Run compiler line by line
        while (sourceCode!=""){
            System.out.print("Code: ");
            sourceCode = input.nextLine();
            runCompiler(sourceCode, "out");
            hadError=false;
        }
        input.close();
    }
    
    /**
     * Method for displaying an error to the user
     * @param line the line the error occured on
     * @param message an error message to display to the user
     */
    static void displayError(int line,String message){
        hadError=true;
        System.out.println("An error was encountered on line: "+line);
        System.out.println(message);
    }


    static void displayError(String message){
        hadError=true;
        System.out.println("An error was encountered");
        System.out.println(message);
    }
    /**
     * Method for displaying error based on a specific token
     * @param token the token the parser detected the error on
     * @param message an error message to display to the user
     */
    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);
    }
    
    /**
     * Method for getting the helpfile text
     * @return the text for the helpfile
     */
    private static String getHelpText(){
        String helpText = "";
        try {
            helpText = Utils.readFile("Compiler/helpfile.txt");
        }
        // Catch any IO exceptions
        catch (IOException e) {
            System.out.println(e);
        }

        // Catch anything else
        catch (Exception e) {
            System.out.println(e);
        }

        return helpText;

    }
}