1 /++
2 To create a executable which serves as a front end to just the compiler.  
3 
4 This can be used to:
5 * convert script to AST, and output the AST in JSON
6 * convert script to byte code, and output the byte code (to be added)
7 * optimize existing byte code, and output new optimized byte code (to be added, when optimizer is added)
8 * convert script to byte code, optimize it, and output optimized byte code (to be added, when optimizer is added)
9 +/
10 module compiler;
11 
12 import std.stdio;
13 import std.file;
14 
15 import qscript.compiler.compiler;
16 import qscript.compiler.misc : CompileError;
17 import qscript.compiler.misc : Function;
18 
19 import utils.misc;
20 
21 version(compiler){
22 	void main(string[] args){
23 		debug{
24 			args = [args[0], "bytecode", "sample"];
25 		}
26 		if (args.length < 3){
27 			writeln ("not enough args. Usage:\n./compiler CompilationType path/to/script");
28 			writeln ("CompilationType can be:\n* ast - output AST in JSON\n* bytecode - output Byte Code");
29 		}else if (!["ast", "bytecode"].hasElement(args[1])){
30 			writeln ("invalid CompilationType");
31 		}else if (!exists(args[2])){
32 			writeln ("file "~args[2]~" doesn't exist");
33 		}else{
34 			string[] script;
35 			try{
36 				script = fileToArray(args[2]);
37 			}catch (Exception e){
38 				.destroy(e);
39 				writeln ("Error reading file");
40 			}
41 			CompileError[] errors;
42 			if (args[1] == "ast"){
43 				string json = compileScriptAST(script,[],errors);
44 				if (errors.length > 0){
45 					stderr.writeln ("There are errors:");
46 					foreach (error; errors){
47 						stderr.writeln("Line#",error.lineno,": ",error.msg);
48 					}
49 				}
50 				writeln (json);
51 			}else if (args[1] == "bytecode"){
52 				Function[] fMap;
53 				string[] byteCode = compileScript(script, [], errors, fMap);
54 				if (errors.length > 0){
55 					stderr.writeln ("There are errors:");
56 					foreach (error; errors){
57 						stderr.writeln("Line#",error.lineno,": ",error.msg);
58 					}
59 				}
60 				foreach (line; byteCode){
61 					writeln(line);
62 				}
63 			}
64 		}
65 	}
66 }