-
Notifications
You must be signed in to change notification settings - Fork 284
/
codegen.d
409 lines (348 loc) · 12.2 KB
/
codegen.d
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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
/**
Templates and CTFE-functions useful for type introspection during code generation.
Some of those are very similar to `traits` utilities but instead of general type
information focus on properties that are most important during such code generation.
Copyright: © 2013 RejectedSoftware e.K.
License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file.
Authors: Sönke Ludwig, Михаил Страшун
*/
module vibe.internal.meta.codegen;
import std.traits : FunctionTypeOf, isSomeFunction;
/*
As user types defined inside unittest blocks don't have proper parent
module, those need to be defined outside for tests that require module
inspection for some reasons. All such tests use single declaration
compiled in this module in unittest version.
*/
version(unittest)
{
private:
interface TestInterface
{
static struct Inner
{
}
const(Inner[]) func1(ref string name);
ref int func1();
shared(Inner[4]) func2(...) const;
immutable(int[string]) func3(in Inner anotherName) @safe;
}
}
/**
For a given type T finds all user-defined symbols it embeds.
Important property of such symbols is that they are likely to
need an explicit import if used in some other scope / module.
Implementation is incomplete and tuned for REST interface generation needs.
Params:
T = type to introspect for qualified symbols
Returns:
tuple of "interesting" symbols, no duplicates
*/
template getSymbols(T)
{
import std.typetuple : TypeTuple, NoDuplicates, staticMap;
import std.traits;
private template Implementation(T)
{
static if (is(T == U!V, alias U, V)) { // single-argument template support
alias Implementation = TypeTuple!(U, Implementation!V);
}
else static if (isAggregateType!T || is(T == enum)) {
alias Implementation = T;
}
else static if (isStaticArray!T || isArray!T) {
alias Implementation = Implementation!(typeof(T.init[0]));
}
else static if (isAssociativeArray!T) {
alias Implementation = TypeTuple!(
Implementation!(ValueType!T),
Implementation!(KeyType!T)
);
}
else static if (isPointer!T) {
alias Implementation = Implementation!(PointerTarget!T);
}
else
alias Implementation = TypeTuple!();
}
alias getSymbols = NoDuplicates!(Implementation!T);
}
///
unittest
{
import std.typetuple : TypeTuple;
struct A {}
interface B {}
alias Type = A[const(B[A*])];
struct C(T) {}
// can't directly compare tuples thus comparing their string representation
static assert (getSymbols!Type.stringof == TypeTuple!(A, B).stringof);
static assert (getSymbols!int.stringof == TypeTuple!().stringof);
static assert (getSymbols!(C!A).stringof == TypeTuple!(C, A).stringof);
}
/**
For a given interface I finds all modules that types in its methods
come from.
These modules need to be imported in the scope code generated from I
is used to avoid errors with unresolved symbols for user types.
Params:
I = interface to inspect
Returns:
list of module name strings, no duplicates
*/
string[] getRequiredImports(I)()
if (is(I == interface))
{
import std.traits : MemberFunctionsTuple, moduleName,
ParameterTypeTuple, ReturnType;
if( !__ctfe )
assert(false);
bool[string] visited;
string[] ret;
void addModule(string name)
{
if (name !in visited) {
ret ~= name;
visited[name] = true;
}
}
foreach (method; __traits(allMembers, I)) {
// WORKAROUND #1045 / @@BUG14375@@
static if (method.length != 0)
foreach (overload; MemberFunctionsTuple!(I, method)) {
alias FuncType = FunctionTypeOf!overload;
foreach (symbol; getSymbols!(ReturnType!FuncType)) {
static if (__traits(compiles, moduleName!symbol)) {
addModule(moduleName!symbol);
}
}
foreach (P; ParameterTypeTuple!FuncType) {
foreach (symbol; getSymbols!P) {
static if (__traits(compiles, moduleName!symbol)) {
addModule(moduleName!symbol);
}
}
}
}
}
return ret;
}
///
unittest
{
// `Test` is an interface using single user type
enum imports = getRequiredImports!TestInterface;
static assert (imports.length == 1);
static assert (imports[0] == "vibe.internal.meta.codegen");
}
/**
* Returns a Tuple of the parameters.
* It can be used to declare function.
*/
template ParameterTuple(alias Func)
{
static if (is(FunctionTypeOf!Func Params == __parameters)) {
alias ParameterTuple = Params;
} else static assert(0, "Argument to ParameterTuple must be a function");
}
///
unittest
{
void foo(string val = "Test", int = 10);
void bar(ParameterTuple!foo) { assert(val == "Test"); }
// Variadic functions require special handling:
import core.vararg;
void foo2(string val, ...);
void bar2(ParameterTuple!foo2, ...) { assert(val == "42"); }
bar();
bar2("42");
// Note: outside of a parameter list, it's value is the type of the param.
import std.traits : ParameterDefaultValueTuple;
ParameterTuple!(foo)[0] test = ParameterDefaultValueTuple!(foo)[0];
assert(test == "Test");
}
/// Returns a Tuple containing a 1-element parameter list, with an optional default value.
/// Can be used to concatenate a parameter to a parameter list, or to create one.
template ParameterTuple(T, string identifier, DefVal : void = void)
{
import std.string : format;
mixin(q{private void __func(T %s);}.format(identifier));
alias ParameterTuple = ParameterTuple!__func;
}
/// Ditto
template ParameterTuple(T, string identifier, alias DefVal)
{
import std.string : format;
mixin(q{private void __func(T %s = DefVal);}.format(identifier));
alias ParameterTuple = ParameterTuple!__func;
}
///
unittest
{
void foo(ParameterTuple!(int, "arg2")) { assert(arg2 == 42); }
foo(42);
void bar(string arg);
void bar2(ParameterTuple!bar, ParameterTuple!(string, "val")) { assert(val == arg); }
bar2("isokay", "isokay");
// For convenience, you can directly pass the result of std.traits.ParameterDefaultValueTuple
// without checking for void.
import std.traits : PDVT = ParameterDefaultValueTuple;
import std.traits : arity;
void baz(string test, int = 10);
static assert(is(PDVT!(baz)[0] == void));
// void baz2(string test2, string test);
void baz2(ParameterTuple!(string, "test2", PDVT!(baz)[0]), ParameterTuple!(baz)[0..$-1]) { assert(test == test2); }
static assert(arity!baz2 == 2);
baz2("Try", "Try");
// void baz3(string test, int = 10, int ident = 10);
void baz3(ParameterTuple!baz, ParameterTuple!(int, "ident", PDVT!(baz)[1])) { assert(ident == 10); }
baz3("string");
import std.datetime;
void baz4(ParameterTuple!(SysTime, "epoch", Clock.currTime)) { assert((Clock.currTime - epoch) < 30.seconds); }
baz4();
// Convertion are possible for default parameters...
alias baz5PT = ParameterTuple!(SysTime, "epoch", uint.min);
// However this blows up because of @@bug 14369@@
// alias baz6PT = ParameterTuple!(SysTime, "epoch", PDVT!(baz4)[0]));
alias baz7PT = ParameterTuple!(SysTime, "epoch", uint.max);
// Non existing convertion are detected.
static assert(!__traits(compiles, { alias baz7PT = ParameterTuple!(SysTime, "epoch", Object.init); }));
// And types are refused
static assert(!__traits(compiles, { alias baz7PT = ParameterTuple!(SysTime, "epoch", uint); }));
}
/// Returns a string of the functions attributes, suitable to be mixed
/// on the LHS of the function declaration.
///
/// Unfortunately there is no "nice" syntax for declaring a function,
/// so we have to resort on string for functions attributes.
template FuncAttributes(alias Func)
{
import std.array : join;
enum FuncAttributes = [__traits(getFunctionAttributes, Func)].join(" ");
}
/// A template mixin which allow you to clone a function, and specify the implementation.
///
/// Params:
/// Func = An alias to the function to copy.
/// body_ = The implementation of the class which will be mixed in.
/// keepUDA = Whether or not to copy UDAs. Since the primary use case for this template
/// is implementing classes from interface, this defaults to $(D false).
/// identifier = The identifier to give to the new function. Default to the identifier of
/// $(D Func).
///
/// See_Also: $(D CloneFunctionDecl) to clone a prototype.
mixin template CloneFunction(alias Func, string body_, bool keepUDA = false, string identifier = __traits(identifier, Func))
{
// Template mixin: everything has to be self-contained.
import std.string : format, variadicFunctionStyle, Variadic;
import std.traits : ReturnType;
import std.typetuple : TypeTuple;
import vibe.internal.meta.codegen : ParameterTuple, FuncAttributes;
// Sadly this is not possible:
// class Test {
// int foo(string par) pure @safe nothrow { /* ... */ }
// typeof(foo) bar {
// return foo(par);
// }
// }
static if (keepUDA)
private alias UDA = TypeTuple!(__traits(getAttributes, Func));
else
private alias UDA = TypeTuple!();
static if (variadicFunctionStyle!Func == Variadic.no) {
mixin(q{
@(UDA) ReturnType!Func %s(ParameterTuple!Func) %s {
%s
}
}.format(identifier, FuncAttributes!Func, body_));
} else static if (variadicFunctionStyle!Func == Variadic.typesafe) {
mixin(q{
@(UDA) ReturnType!Func %s(ParameterTuple!Func...) %s {
%s
}
}.format(identifier, FuncAttributes!Func, body_));
} else
static assert(0, "Variadic style " ~ variadicFunctionStyle!Func.stringof
~ " not implemented.");
}
///
unittest
{
import std.typetuple : TypeTuple;
interface ITest
{
@("42") int foo(string par, int, string p = "foo", int = 10) pure @safe nothrow const;
@property int foo2() pure @safe nothrow const;
// Issue #1144
void variadicFun(ref size_t bar, string[] args...);
// Gives weird error message, not supported so far
//bool variadicDFun(...);
}
class Test : ITest
{
mixin CloneFunction!(ITest.foo, q{return 84;}, false, "customname");
override:
mixin CloneFunction!(ITest.foo, q{return 42;}, true);
mixin CloneFunction!(ITest.foo2, q{return 42;});
mixin CloneFunction!(ITest.variadicFun, q{bar = args.length;});
//mixin CloneFunction!(ITest.variadicDFun, q{return true;});
}
// UDA tests
static assert(__traits(getAttributes, Test.customname).length == 0);
static assert(__traits(getAttributes, Test.foo2).length == 0);
static assert(__traits(getAttributes, Test.foo) == TypeTuple!("42"));
assert(new Test().foo("", 21) == 42);
assert(new Test().foo2 == 42);
assert(new Test().customname("", 21) == 84);
size_t l;
new Test().variadicFun(l, "Hello", "variadic", "world");
assert(l == 3);
//assert(new Test().variadicDFun("Hello", "again", "variadic", "world"));
}
/// A template mixin which allow you to clone a function declaration
///
/// Params:
/// Func = An alias to the function to copy.
/// keepUDA = Whether or not to copy UDAs. Since the primary use case for this template
/// is copying a definition, this defaults to $(D true).
/// identifier = The identifier to give to the new function. Default to the identifier of
/// $(D Func).
///
/// See_Also : $(D CloneFunction) to implement a function.
mixin template CloneFunctionDecl(alias Func, bool keepUDA = true, string identifier = __traits(identifier, Func))
{
// Template mixin: everything has to be self-contained.
import std.string : format, variadicFunctionStyle, Variadic;
import std.traits : ReturnType;
import std.typetuple : TypeTuple;
import vibe.internal.meta.codegen : ParameterTuple, FuncAttributes;
static if (keepUDA)
private alias UDA = TypeTuple!(__traits(getAttributes, Func));
else
private alias UDA = TypeTuple!();
static if (variadicFunctionStyle!Func == Variadic.no) {
mixin(q{
@(UDA) ReturnType!Func %s(ParameterTuple!Func) %s;
}.format(identifier, FuncAttributes!Func));
} else static if (variadicFunctionStyle!Func == Variadic.typesafe) {
mixin(q{
@(UDA) ReturnType!Func %s(ParameterTuple!Func...) %s;
}.format(identifier, FuncAttributes!Func));
} else
static assert(0, "Variadic style " ~ variadicFunctionStyle!Func.stringof
~ " not implemented.");
}
///
unittest {
import std.typetuple : TypeTuple;
enum Foo;
interface IUDATest {
@(Foo, "forty-two", 42) const(Object) bar() @safe;
}
interface UDATest {
mixin CloneFunctionDecl!(IUDATest.bar);
}
// Tuples don't like when you compare types using '=='.
static assert(is(TypeTuple!(__traits(getAttributes, UDATest.bar))[0] == Foo));
static assert(__traits(getAttributes, UDATest.bar)[1 .. $] == TypeTuple!("forty-two", 42));
}