74 lines
1.4 KiB
D
74 lines
1.4 KiB
D
module clox.main;
|
|
|
|
import core.sys.posix.unistd : STDIN_FILENO;
|
|
import core.stdc.stdio;
|
|
import core.stdc.stdlib;
|
|
|
|
import clox.util;
|
|
import clox.chunk;
|
|
import clox.dbg;
|
|
import clox.vm;
|
|
|
|
int interpretResult(VM.InterpretResult result){
|
|
if(result == VM.InterpretResult.CompileError)
|
|
return 65;
|
|
else if(result == VM.InterpretResult.RuntimeError)
|
|
return 70;
|
|
return 0;
|
|
}
|
|
|
|
int runPrompt(){
|
|
vm.isREPL = true;
|
|
char[1024 * 4] line;
|
|
while(true){
|
|
printf(colour!("lox> ", Colour.Green).ptr);
|
|
if(!fgets(line.ptr, line.sizeof, stdin)){
|
|
printf("\n");
|
|
return 0;
|
|
}
|
|
vm.interpret(line.ptr);
|
|
}
|
|
}
|
|
int runStdin(){
|
|
char* source = readStdin();
|
|
scope(exit)
|
|
source.free();
|
|
return vm.interpret(source).interpretResult;
|
|
}
|
|
int runFile(const char* path){
|
|
char* source = path.readFile();
|
|
if(!source)
|
|
return 74;
|
|
scope(exit)
|
|
source.free();
|
|
return vm.interpret(source).interpretResult;
|
|
}
|
|
|
|
int runMain(ulong argc, const char** argv){
|
|
vm.initialise();
|
|
scope(exit)
|
|
vm.free();
|
|
|
|
if(argc == 1 && isatty(STDIN_FILENO)){
|
|
return runPrompt();
|
|
} else if(argc == 1){
|
|
return runStdin();
|
|
} else if(argc == 2){
|
|
return runFile(argv[1]);
|
|
} else {
|
|
stderr.fprintf("Usage: lox [path]\n");
|
|
return 64;
|
|
}
|
|
}
|
|
|
|
version(D_BetterC){
|
|
extern(C) int main(int argc, const char** argv){
|
|
return runMain(argc, argv);
|
|
}
|
|
} else {
|
|
int main(string[] args){
|
|
import std.string, std.algorithm, std.array;
|
|
return runMain(args.length, cast(const char**)args.map!toStringz.array);
|
|
}
|
|
}
|
|
|