1 module demo;
2 version (demo){
3 	import utils.misc;
4 	import qscript.qscript;
5 	import std.datetime.stopwatch;
6 	import std.stdio;
7 	/// runs the scripts using QScript
8 	class ScriptExec{
9 	private:
10 		/// where the magic happens
11 		QScript _qscript;
12 		/// writeln function
13 		NaData writeln(NaData[] args){
14 			std.stdio.writeln (args[0].strVal);
15 			return NaData(0);
16 		}
17 		/// write function
18 		NaData write(NaData[] args){
19 			std.stdio.write (args[0].strVal);
20 			return NaData(0);
21 		}
22 		/// write int
23 		NaData writeInt(NaData[] args){
24 			std.stdio.write(args[0].intVal);
25 			return NaData(0);
26 		}
27 		/// write double
28 		NaData writeDbl(NaData[] args){
29 			std.stdio.write(args[0].doubleVal);
30 			return NaData(0);
31 		}
32 		/// readln function
33 		NaData readln(NaData[] args){
34 			string s = std.stdio.readln;
35 			s.length--;
36 			return NaData(s);
37 		}
38 	public:
39 		/// constructor
40 		this (){
41 			_qscript = new QScript(
42 				[
43 					Function("writeln", DataType("void"), [DataType("string")]),
44 					Function("write", DataType("void"), [DataType("string")]),
45 					Function("write", DataType("void"), [DataType("int")]),
46 					Function("write", DataType("void"), [DataType("double")]),
47 					Function("readln", DataType("string"), [])
48 				],
49 				[
50 					&writeln,
51 					&write,
52 					&writeInt,
53 					&writeDbl,
54 					&this.readln
55 				]
56 			);
57 		}
58 		/// compiles & returns byte code
59 		string[] compileToByteCode(string[] script, ref CompileError[] errors){
60 			string[] byteCode;
61 			errors = _qscript.loadScript(script, byteCode);
62 			return byteCode;
63 		}
64 		/// called right after all external functions have been loaded
65 		void initialize(){
66 			_qscript.initialize();
67 		}
68 		/// executes the first function in script
69 		NaData execute(uinteger functionID, NaData[] args){
70 			return _qscript.execute(functionID, args);
71 		}
72 	}
73 
74 	void main (string[] args){
75 		debug{
76 			args = args[0]~["sample.qs", "out.bcode"];
77 		}
78 		if (args.length < 2){
79 			writeln("not enough args. Usage:");
80 			writeln("./demo [script] [bytecode, output, optional]");	
81 		}else{
82 			StopWatch sw;
83 			ScriptExec scr = new ScriptExec();
84 			CompileError[] errors;
85 			scr.initialize;
86 			string[] byteCode = scr.compileToByteCode(fileToArray(args[1]), errors);
87 			if (errors.length > 0){
88 				writeln("Compilation errors:");
89 				foreach (err; errors){
90 					writeln ("line#",err.lineno, ": ",err.msg);
91 				}
92 			}else{
93 				if (args.length > 2){
94 					byteCode.arrayToFile(args[2]);
95 				}
96 				// now execute main
97 				sw.start;
98 				scr.execute(0, []);
99 				sw.stop;
100 				writeln("execution took: ", sw.peek.total!"msecs", "msecs");
101 			}
102 		}
103 	}
104 }