D Paste by bigasoft@gmail.com
Description: Class member functions generator with respect of some interface: storage classes are supported!
|
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 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 | module test; /* * The idea is to automatically generate implementation of class member functions * required by some interface (not necessarily inherited). * * In this example the following idea is demonstrated: * * Assume we have some interface MyIface. * Class MyClass implements interface MyIface, but all what it does is * forwarding all calls to a child class ChildClass (which also implements interface MyIface). * * Build using dmd2. */ import std.stdio; import std.traits: ParameterTypeTuple; import std.typetuple: TypeTuple; import std.string; // Parse function declaration. // In: // Function declaration string 'd'. // Out: // Function return type in 'rtype'. // Function parameter types in ptypes. // Function parameter names in pnames. void parse_fdecl(in string d, out string rtype, out string[] ptypes, out string[] pnames) { assert(d[d.length-1] == ')'); int v = 0; bool clean = true; // Parse from the end back. int j = d.length-1; // last saved position for (int i = j; i >= 0; i--) { if ( d[i] == ')' ) { v++; continue; } else if ( d[i] == '(' ) { v--; if ( v == 0 ) { // last parenthes was closed if ( i+1 < j ) { ptypes ~= d[i+1..j+1]; // ptype near latest parenthes } j = i-1; break; } continue; } if ( v == 1 ) { if ( clean ) { // expect parameter name j = i; while ( d[j] != ' ' && d[j] != '\t' ) { // pass name characters assert( d[j] != ',' ); j--; } if ( j != i ) { // got param name pnames ~= d[j+1..i+1]; // save param name i = j; // passed the param name j--; // skip the space clean = false; // expect parameter type then continue; } } else { if ( d[i] == ',' ) { ptypes ~= d[i+1..j+1]; j = i-1; clean = true; continue; } // else: pass parameter type } } } assert(d[j-7..j+1] == "function"); j = j-8; // skip "function" word while ( d[j] == ' ' || d[j] == '\t' ) j--; rtype = d[0..j+1]; // Now ptypes and rtypes are reverted, because the declaration // was parsed from its end. // .revert property doesn't work at compile time. // Revert arrays manually: for ( int i = 0; i < ptypes.length/2; i++ ) { string tmp = ptypes[i]; ptypes[i] = ptypes[length-1-i]; ptypes[length-1-i] = tmp; } for ( int i = 0; i < pnames.length/2; i++ ) { string tmp = pnames[i]; pnames[i] = pnames[length-1-i]; pnames[length-1-i] = tmp; } } // Auxiliary template template arrayToTuple(alias arr) { static if (arr.length) alias TypeTuple!(arr[0], arrayToTuple!(arr[1 .. $])) arrayToTuple; else alias TypeTuple!() arrayToTuple; } // This function generates member functions for each function required // by interface 'Iface'. // Function body is passed as template, where '##' is replaced with function name, // '#@' is replaced with arguements tuple, and '#1#' is replaced with 1-st parameter, // and so on. // (Unfortunately, function body can't be constructed via a delegate function, // because delegates aren't allowed at compile time.) static string genIfaceFunctions(Iface)(string fbody_tpl) { // Can't use std.string.replace at compile time. // This function replaces 'from' to 'to' in 's' inplace. // Returns false if nothing was replaced static bool replaceall(ref string s, string from, string to) { int j; bool replaced = false; string res; for (int i = 0; i <= s.length - from.length; i++) { if ( s[i..i+from.length] == from ) { // 'from' found res ~= s[j..i] ~ to; // add part of 's' before 'from', and add 'to'. replaced = 1; i += from.length; // skip 'from' j = i; } } s = res ~ s[j..$]; return replaced; } // Auxiliary function: joins strings with 'j' (e.g. ", ") string join(string[] ss, string j) { string res; for ( int i = 0; i < ss.length; i++ ) { if ( i > 0 ) res ~= j; res ~= ss[i]; } return res; } // Compile-time int-to-string formatting. string intToString(int i) { string res; string[] digits = ["0","1","2","3","4","5","6","7","8","9"]; while (i) { res ~= digits[i % 10]; i = i / 10; } return res; } string res; alias arrayToTuple!(__traits(allMembers, Iface)) Members; foreach (j, fname; Members) { string name = Members[j]; foreach (t; __traits(getVirtualFunctions, Iface, Members[j])) { string fdecl = typeof(&t).stringof; // get the full function declaration string rtype; string[] ptypes; string[] pnames; parse_fdecl(fdecl, rtype, ptypes, pnames); string fbody = fbody_tpl; replaceall(fbody, "##", name); replaceall(fbody, "#@", join(pnames, ", ")); if ( pnames.length > 0 ) { int pn = 1; while ( replaceall(fbody, "#"~intToString(pn)~"#", pnames[pn-1]) ) ++pn; } res ~= rtype~" "~name~"("; // function return type and funcion name // function parameters foreach (i, tp; ptypes) { if ( i > 0 ) res ~= ","; res ~= ptypes[i]~" "; res ~= pnames[i]; } res ~= "){"~fbody~"}\n"; // function body } } return res; } // This function is just a helper. genIfaceFunctions() could be called // directly from MyClass, but I just wished to avoid unneeded class members, // so placed the template instantiation outside MyClass. static string genMyIfaceFunctions(string fbody) { return genIfaceFunctions!(MyIface)(fbody); } // Our test interface interface MyIface { void a(ref string aa); // 'ref' works too! int a(void* aa1, out char[] aa2); // overloaded functions string b(); // void parameters // let's try something complex void delegate(const char[] ddd) d(void* function() dd1, bool dd2); } // Our test class class MyClass//: MyIface { MyIface child; // All MyIface calls will be forwarded to 'child'. this(MyIface xchild) { child = xchild; // initiate 'child' by a given object } // Generate all functions required by MyIface: // void a(TypeTuple!(string) args){return child.a(args);} // int a(TypeTuple!(void*, char[]) args){return child.a(args);} // ... // Just forward all MyIface calls to the 'child' after printing a simple message. mixin(genMyIfaceFunctions("writef(\"MyClass.a(), \"); return child.##(#@);")); // Print the generated code pragma(msg, "Generated code:"); pragma(msg, genMyIfaceFunctions("writef(\"MyClass.a(), \"); return child.##(#@);")); } // All MyIface functions are implemented in a child class: class ChildClass: MyIface { void a(ref string args) { writeln(args); args = "ChildClass.a()"; writeln("Change to: ", args); } // The rest are all dummy functions int a(void* aa1, out char[] aa2){typeof(return) res; return res;} string b(){typeof(return) res; return res;} void delegate(const const(char[]) ddd) d(void* function() dd1, bool dd2){typeof(return) res; return res;} } void main() { writeln("MyClass members: ", __traits(allMembers, MyClass),"\n"); MyClass myclass = new MyClass(new ChildClass()); writef("Calling myclass.a(\"Hello!\"): "); string s = "Hello!"; myclass.a(s); writeln("After: ", s); } |