1 /** 
2  * Copyright: Enalye
3  * License: Zlib
4  * Authors: Enalye
5  */
6 module grimoire.stdlib.typecast;
7 
8 import std.conv;
9 import grimoire.assembly, grimoire.compiler, grimoire.runtime;
10 
11 package(grimoire.stdlib) void grLoadStdLibTypecast(GrLibrary library) {
12     //As int
13     library.addCast(&typecast_r2i, grFloat, grInt, true);
14     library.addCast(&typecast_b2i, grBool, grInt);
15 
16     //As GrFloat
17     library.addCast(&typecast_i2r, grInt, grFloat);
18 
19     //As string
20     library.addCast(&typecast_b2s, grBool, grString);
21     library.addCast(&typecast_i2s, grInt, grString);
22     library.addCast(&typecast_r2s, grFloat, grString);
23     library.addCast(&typecast_as2s, grStringArray, grString);
24 
25     //As String Array
26     library.addCast(&typecast_s2as, grString, grStringArray);
27 }
28 
29 //As int
30 private void typecast_r2i(GrCall call) {
31     call.setInt(to!GrInt(call.getFloat(0)));
32 }
33 
34 private void typecast_b2i(GrCall call) {
35     call.setInt(to!GrInt(call.getBool(0)));
36 }
37 
38 //As float
39 private void typecast_i2r(GrCall call) {
40     call.setFloat(to!GrFloat(call.getInt(0)));
41 }
42 
43 //As string
44 private void typecast_b2s(GrCall call) {
45     call.setString(call.getBool(0) ? "true" : "false");
46 }
47 
48 private void typecast_i2s(GrCall call) {
49     call.setString(to!GrString(call.getInt(0)));
50 }
51 
52 private void typecast_r2s(GrCall call) {
53     call.setString(to!GrString(call.getFloat(0)));
54 }
55 
56 private void typecast_as2s(GrCall call) {
57     GrString result;
58     foreach (const sub; call.getStringArray(0).data) {
59         result ~= sub;
60     }
61     call.setString(result);
62 }
63 
64 //As string array
65 private void typecast_s2as(GrCall call) {
66     GrStringArray result = new GrStringArray;
67     foreach (const sub; call.getString(0)) {
68         result.data ~= to!GrString(sub);
69     }
70     call.setStringArray(result);
71 }