My favorites | Sign in
Project Home Downloads Wiki Issues Source
Checkout   Browse   Changes    
 
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
/*
* Copyright: Public Domain
*/
module nonstd.typecons;

public import std.typecons;
import std.metastrings;
import std.typetuple;

import nonstd.traits;


/**
Generates implementations for the specified functions.

Params:
Generator = See the example below.
FuncTraits = A tuple of $(D FunctionTraits) on the functions to be
implemented.

Example:
--------------------
interface Base
{
int foo(int n);
double bar(double n);
}
template MyGenerator()
{
// generateFunction is a template or template function, which
// returns the function body for the given FunctionTrait ft.
template generateFunction(alias ft)
{
enum string generateFunction =
"return _p0;" ; // parameters are _p0, _p1, ...
}
}
class MyClass : Base
{
// Base.foo and Base.bar are implemented.
mixin generateFunctions!(MyGenerator!(),
TypeTuple!(FunctionTraits!(Base.foo),
FunctionTraits!(Base.bar)));
}
void main()
{
auto c = new MyClass;
assert(c.foo(42) == 42);
assert(c.bar(3.14) == 3.14);
}
--------------------

Bugs:
$(BUGZILLA 2740) should be fixed.
*/
template generateFunctions(alias Generator, FuncTraits...)
{
private alias FuncTraits _FT; // for traitsID
mixin (generateFunctionsImpl!(Generator, "_FT", _FT).code);
}

// [internal]
private template generateFunctionsImpl(
alias Generator, string traitsID, FuncTraits...)
{
/*
* Why is traitsID necessary?
*
* When this code is generated:
* --------------------
* module modA;
* class AutoImpl(Base) : Base
* {
* some.another.module.T foo(); // generated
* }
* --------------------
* Then the compiler can't tell what the T is, and spits an error:
* "identifier 'some.another.module.T' is not defined".
*
* traitsID is a string that evaluates to a function traits tuple
* when mixed in the scope where a genearted code is mixed. To
* prevent not-defined error, we use traitsID for indirectly
* referencing the return types and parameter types in the
* generated code.
*/

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //

/*
* [workaround] FuncTraits[i].sth (intermediate indexing) does not
* compile. We have to declare __FuncTraits_0, __FuncTraits_1, etc.
* and use them instead.
*/
template unrollTraits(size_t i)
{
static if (i < FuncTraits.length)
enum unrollTraits =
"alias " ~ traitsID ~ "[" ~ ToString!(i) ~ "] "
"_" ~ traitsID ~ "_" ~ ToString!(i) ~ ";\n" ~
unrollTraits!(i + 1);
else
enum unrollTraits = "";
}
enum preamble =
"private\n"
"{\n"
~ unrollTraits!(0) ~
"}\n";

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //

/*
* Generate the i-th function and returns the code in .code.
*/
template generateFunction(size_t i)
{
alias FuncTraits[i] ft;
enum FTi = "_" ~ traitsID ~ "_" ~ ToString!(i);

/*
* Various modifiers
*/
enum link = "extern(" ~ linkageToString(ft.linkage) ~ ")";
enum stoc = storageClassToString(ft.storageClass);
enum attrs = funcAttrToString(ft.attributes);
enum prefix = link ~ " " ~ stoc ~ " " ~ attrs;

/*
* Return type
*/
enum rtype = FTi ~ ".ReturnType";

/*
* Generate parameters
*/
string param(size_t k)()
{
enum stoc = storageClassToString(ft.parameterStorageClasses[k]);
enum type = FTi ~ ".ParameterTypeTuple[" ~ ToString!(k) ~ "]";
return stoc ~ " " ~ type ~ " _p" ~ ToString!(k);
}

string params()
{
string params = "";

foreach (k, P; ft.ParameterTypeTuple)
{
static if (k >= 1)
params ~= ", ";
params ~= param!(k);
}

// classic variadic arguments: ( foo, ... ) or ( ... )
static if (ft.variadic == Variadic.VARIADIC)
params ~= ft.ParameterTypeTuple.length ?
", ..." : "...";

// typesafe variadic arguments: ( foo ... )
static if (ft.variadic == Variadic.TYPESAFE)
params ~= "...";

return params;
}

/*
* Finish
*/
enum code =
prefix ~ " " ~ rtype ~ " " ~ ft.name ~ "(" ~ params ~ ")\n"
"{\n"
~ Generator.generateFunction!(ft) ~ "\n"
"}";
}

// Generate i, i+1, ...-th methods.
template foreachFunction(size_t i)
{
static if (i < FuncTraits.length)
enum foreachFunction =
generateFunction!(i).code ~ "\n" ~
foreachFunction!(i + 1);
else
enum foreachFunction = "";
}

enum impls = foreachFunction!(0);

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //

/*
* Finish
*/
enum code = preamble ~ "\n" ~ impls;

debug (std_typecons_printGeneratedCode)
{
pragma(msg, "--------------------");
pragma(msg, code);
pragma(msg, "--------------------");
}
}


// : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : //
// BlackHole and WhiteHole
// : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : //

/*
Generates aliases for all member functions defined in $(D Base):
--------------------
alias Base.foo foo;
alias Base.bar bar;
...
--------------------
This template will be used for revealing hidden functions.
*/
private template generateOverloadAliases(string base, Base)
{
enum generateOverloadAliases =
generateOverloadAliasesImpl!(base, methodNames!(Base)).code;
}

// [internal]
private template generateOverloadAliasesImpl(string base, alias ms)
{
static if (ms.length)
enum code =
"alias " ~ base ~ "." ~ ms[0] ~ " " ~ ms[0] ~ ";\n" ~
generateOverloadAliasesImpl!(base, ms[1 .. $]).code;
else
enum code = "";
}


/*
Returns a tuple of $(D FunctionTraits), each of which is the traits on
a function that can override an abstract member function overloads in
$(D C) or its ancestors.
*/
private template AbstractOverrideTraitsTuple(C)
{
alias OverrideTraitsTuple!(
CovariantOverloadSets!(AbstractMethodsTuple!(C))
) AbstractOverrideTraitsTuple;
}


// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //

/**
$(D BlackHole!(Base)) is a class which implements all abstract methods
defined in $(D Base) and its ancestors. Each method just returns the
$(D .init) property of its return type.

Example:
--------------------
interface I { int foo(); }
void main()
{
auto bh = new BlackHole!I;
assert(bh.foo == 0);
}
--------------------
*/
class BlackHole(Base) : Base
{
/*
* Implement abstract methods.
*/
mixin generateFunctions!(BlackHoleGenerator!(Base),
AbstractOverrideTraitsTuple!(Base));

/*
* The generated methods would hide ones defined in Base. This mixin
* reveals hidden methods.
*/
mixin (generateOverloadAliases!("Base", Base));
}

private template BlackHoleGenerator(Base)
{
// The generated function does nothing and returns .init.
string generateFunction(alias mt)()
{
string stmt;

static if (is(mt.ReturnType == void))
stmt = "";
else static if (mt.attributes & FuncAttr.REF)
// reference to a dummy variable
stmt = "static __gshared typeof(return) dummy;\n"
"return dummy;";
else
stmt = "return typeof(return).init;";
return stmt;
}
}


unittest
{
struct Scope
{
interface X {}
interface Y : X {}
interface I { X foo() nothrow; }
interface J { Y foo() const; }
class C : I, J
{
alias I.foo foo;
alias J.foo foo;
abstract ref int foo(lazy short i, int[] a...);
extern (C) abstract void bar(size_t n, ...);
final int bar() const pure nothrow { return 42; }
}
}
auto bh = new BlackHole!(Scope.C);

Scope.Y y = (cast(immutable) bh).foo();
assert(y is null);

int* p = &bh.foo((assert(0), 1), 2, 3, 4); // lazy eval
assert(p != null); // a static variable is returned

bh.bar(4, 3, 2, 1); // C-style variadic function
assert(bh.bar() == 42); // final method is not overridden
}


/**
$(D WhiteHole!(Base)) is a class which implements all abstract methods
defined in $(D Base) and its ancestors. Each method will throw an
$(D AssertError) when it's invoked.

Example:
--------------------
interface I { real foo(); }
void main()
{
auto wh = new WhiteHole!I;
wh.foo(); // throws AssertError
}
--------------------
*/
class WhiteHole(Base) : Base
{
/*
* Implement abstract methods.
*/
mixin generateFunctions!(WhiteHoleGenerator!(Base),
AbstractOverrideTraitsTuple!(Base));

/*
* The generated methods would hide methods defined in Base. So
* aliases should be inserted.
*/
mixin (generateOverloadAliases!("Base", Base));
}

private template WhiteHoleGenerator(Base)
{
// The generated function throws AssertError.
string generateFunction(alias mt)()
{
enum qname = Base.stringof ~ "." ~ mt.name;
enum id = qname ~ mt.ParameterTypeTuple.stringof;
enum msg = id ~ " is not implemented";

/*
* We use assert in case the method is a nothrow function
* (assert doesn't violate nothrow).
*/
return "enum emsg = q\"EOS_WhiteHole_\n"
~ msg ~
"\nEOS_WhiteHole_\";\n"
"assert(0, emsg[0 .. $ - 1]);";
}
}

unittest
{
static class B
{
abstract void foo();
}
auto wh = new WhiteHole!B;
try { wh.foo(); assert(0); } catch (Error e) { }
}

Change log

r39 by rsinfu on May 28, 2009   Diff
fix: allMembers
Go to: 
Project members, sign in to write a code review

Older revisions

r38 by rsinfu on May 25, 2009   Diff
doc :: cosmetic
r36 by rsinfu on May 25, 2009   Diff
revert: removed the (uint i) parameter
r34 by rsinfu on May 25, 2009   Diff
added a new parameter (uint i) to
gnerateFunction
All revisions of this file

File info

Size: 10175 bytes, 390 lines
Powered by Google Project Hosting