/
base.d
947 lines (861 loc) · 30.7 KB
/
base.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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* Code generation metadata and templates used for implementing struct
* serialization.
*
* Many templates can be customized using field meta data, which is read from
* a manifest constant member of the given type called fieldMeta (if present),
* and is concatenated with the elements from the optional fieldMetaData
* template alias parameter.
*
* Some code generation templates take account of the optional TVerboseCodegen
* version declaration, which causes warning messages to be emitted if no
* metadata for a field/method has been found and the default behavior is
* used instead. If this version is not defined, the templates just silently
* behave like the Thrift compiler does in this situation, i.e. automatically
* assign negative ids (starting at -1) for fields and assume TReq.AUTO as
* requirement level.
*/
// Implementation note: All the templates in here taking a field metadata
// parameter should ideally have a constraint that restricts the alias to
// TFieldMeta[]-typed values, but the is() expressions seems to always fail.
module thrift.codegen.base;
import std.algorithm : find;
import std.array : empty, front;
import std.conv : to;
import std.exception : enforce;
import std.traits : BaseTypeTuple, isPointer, isSomeFunction, pointerTarget,
ReturnType;
import thrift.base;
import thrift.internal.codegen;
import thrift.protocol.base;
/*
* Thrift struct/service meta data, which is used to store information from
* the interface definition files not representable in plain D, i.e. field
* requirement levels, Thrift field IDs, etc.
*/
/**
* Struct field requirement levels.
*/
enum TReq {
/// Detect the requiredness from the field type: if it is nullable, treat
/// the field as optional, if it is non-nullable, treat the field as
/// required. This is the default used for handling structs not generated
/// from an IDL file, and never emitted by the Thrift compiler. TReq.AUTO
/// shouldn't be specified explicitly.
// Implementation note: thrift.codegen templates use
// thrift.internal.codegen.memberReq to resolve AUTO to REQUIRED/OPTIONAL
// instead of handling it directly.
AUTO,
/// The field is treated as optional when deserializing/receiving the struct
/// and as required when serializing/sending. This is the Thrift default if
/// neither "required" nor "optional" are specified in the IDL file.
OPT_IN_REQ_OUT,
/// The field is optional.
OPTIONAL,
/// The field is required.
REQUIRED,
/// Ignore the struct field when serializing/deserializing.
IGNORE
}
/**
* The way how methods are called.
*/
enum TMethodType {
/// Called in the normal two-way scheme consisting of a request and a
/// response.
REGULAR,
/// A fire-and-forget one-way method, where no response is sent and the
/// client immediately returns.
ONEWAY
}
/**
* Compile-time metadata for a struct field.
*/
struct TFieldMeta {
/// The name of the field. Used for matching a TFieldMeta with the actual
/// D struct member during code generation.
string name;
/// The (Thrift) id of the field.
short id;
/// Whether the field is requried.
TReq req;
/// A code string containing a D expression for the default value, if there
/// is one.
string defaultValue;
}
/**
* Compile-time metadata for a service method.
*/
struct TMethodMeta {
/// The name of the method. Used for matching a TMethodMeta with the actual
/// method during code generation.
string name;
/// Meta information for the parameteres.
TParamMeta[] params;
/// Specifies which exceptions can be thrown by the method. All other
/// exceptions are converted to a TApplicationException instead.
TExceptionMeta[] exceptions;
/// The fundamental type of the method.
TMethodType type;
}
/**
* Compile-time metadata for a service method parameter.
*/
struct TParamMeta {
/// The name of the parameter. Contrary to TFieldMeta, it only serves
/// decorative purposes here.
string name;
/// The Thrift id of the parameter in the param struct.
short id;
/// A code string containing a D expression for the default value for the
/// parameter, if any.
string defaultValue;
}
/**
* Compile-time metadata for a service method exception annotation.
*/
struct TExceptionMeta {
/// The name of the exception »return value«. Contrary to TFieldMeta, it
/// only serves decorative purposes here, as it is only used in code not
/// visible to processor implementations/service clients.
string name;
/// The Thrift id of the exception field in the return value struct.
short id;
/// The name of the exception type.
string type;
}
/**
* A pair of two TPorotocols. To be used in places where a list of protocols
* is expected, for specifying different protocols for input and output.
*/
struct TProtocolPair(InputProtocol, OutputProtocol) if (
isTProtocol!InputProtocol && isTProtocol!OutputProtocol
) {}
/**
* true if T is a TProtocolPair.
*/
template isTProtocolPair(T) {
static if (is(T _ == TProtocolPair!(I, O), I, O)) {
enum isTProtocolPair = true;
} else {
enum isTProtocolPair = false;
}
}
unittest {
static assert(isTProtocolPair!(TProtocolPair!(TProtocol, TProtocol)));
static assert(!isTProtocolPair!TProtocol);
}
/**
* true if T is a TProtocol or a TProtocolPair.
*/
template isTProtocolOrPair(T) {
enum isTProtocolOrPair = isTProtocol!T || isTProtocolPair!T;
}
unittest {
static assert(isTProtocolOrPair!TProtocol);
static assert(isTProtocolOrPair!(TProtocolPair!(TProtocol, TProtocol)));
static assert(!isTProtocolOrPair!void);
}
/**
* true if T represents a Thrift service.
*/
template isService(T) {
enum isService = isBaseService!T || isDerivedService!T;
}
/**
* true if T represents a Thrift service not derived from another service.
*/
template isBaseService(T) {
static if(is(T _ == interface) &&
(!is(T TBases == super) || TBases.length == 0)
) {
enum isBaseService = true;
} else {
enum isBaseService = false;
}
}
/**
* true if T represents a Thrift service derived from another service.
*/
template isDerivedService(T) {
static if(is(T _ == interface) &&
is(T TBases == super) && TBases.length == 1
) {
enum isDerivedService = isService!(TBases[0]);
} else {
enum isDerivedService = false;
}
}
/**
* For derived services, gets the base service interface.
*/
template BaseService(T) if (isDerivedService!T) {
alias BaseTypeTuple!T[0] BaseService;
}
/*
* Code generation templates.
*/
/**
* Mixin template defining additional helper methods for using a struct with
* Thrift, and a member called isSetFlags if the struct contains any fields
* for which an »is set« flag is needed.
*
* It can only be used inside structs or Exception classes.
*
* For example, consider the following struct definition:
* ---
* struct Foo {
* string a;
* int b;
* int c;
*
* mixin TStructHelpers!([
* TFieldMeta("a", 1), // Implicitly optional (nullable).
* TFieldMeta("b", 2), // Implicitly required (non-nullable).
* TFieldMeta("c", 3, TReq.REQUIRED, "4")
* ]);
* }
* ---
*
* TStructHelper adds the following methods to the struct:
* ---
* /++
* + Sets member fieldName to the given value and marks it as set.
* +
* + Examples:
* + ---
* + auto f = Foo();
* + f.set!"b"(12345);
* + assert(f.isSet!"b");
* + ---
* +/
* void set(string fieldName)(MemberType!(This, fieldName) value);
*
* /++
* + Resets member fieldName to the init property of its type and marks it as
* + not set.
* +
* + Examples:
* + ---
* + // Set f.b to some value.
* + auto f = Foo();
* + f.set!"b"(12345);
* +
* + f.unset!b();
* +
* + // f.b is now unset again.
* + assert(!f.isSet!"b");
* + ---
* +/
* void unset(string fieldName)();
*
* /++
* + Returns whether member fieldName is set.
* +
* + Examples:
* + ---
* + auto f = Foo();
* + assert(!f.isSet!"b");
* + f.set!"b"(12345);
* + assert(f.isSet!"b");
* + ---
* +/
* bool isSet(string fieldName)() const @property;
*
* /++
* + Returns a string representation of the struct.
* +
* + Examples:
* + ---
* + auto f = Foo();
* + f.a = "a string";
* + assert(f.toString() == `Foo("a string", 0 (unset), 4)`);
* + ---
* +/
* string toString() const;
*
* /++
* + Deserializes the struct, setting its members to the values read from the
* + protocol. Forwards to readStruct(this, proto);
* +/
* void read(Protocol)(Protocol proto) if (isTProtocol!Protocol);
*
* /++
* + Serializes the struct to the target protocol. Forwards to
* + writeStruct(this, proto);
* +/
* void write(Protocol)(Protocol proto) const if (isTProtocol!Protocol);
* ---
*
* Additionally, an opEquals() implementation is provided which simply
* compares all fields, but disregards the is set struct, if any (the exact
* signature obviously differs between structs and exception classes). The
* metadata is stored in a manifest constant called fieldMeta.
*
* Note: To set the default values for fields where one has been specified in
* the field metadata, a parameterless static opCall is generated, because D
* does not allow parameterless (default) constructors for structs. Thus, be
* always to use to initialize structs:
* ---
* Foo foo; // Wrong!
* auto foo = Foo(); // Correct.
* ---
*/
mixin template TStructHelpers(alias fieldMetaData = cast(TFieldMeta[])null) if (
is(typeof(fieldMetaData) : TFieldMeta[])
) {
import std.algorithm : canFind;
import thrift.codegen.base;
import thrift.internal.codegen : isNullable, MemberType, mergeFieldMeta,
FieldNames;
import thrift.protocol.base : TProtocol, isTProtocol;
alias typeof(this) This;
static assert(is(This == struct) || is(This : Exception),
"TStructHelpers can only be used inside a struct or an Exception class.");
static if (TIsSetFlags!(This, fieldMetaData).tupleof.length > 0) {
// If we need to keep isSet flags around, create an instance of the
// container struct.
TIsSetFlags!(This, fieldMetaData) isSetFlags;
enum fieldMeta = fieldMetaData ~ [TFieldMeta("isSetFlags", 0, TReq.IGNORE)];
} else {
enum fieldMeta = fieldMetaData;
}
void set(string fieldName)(MemberType!(This, fieldName) value) if (
is(MemberType!(This, fieldName))
) {
__traits(getMember, this, fieldName) = value;
static if (is(typeof(mixin("this.isSetFlags." ~ fieldName)) : bool)) {
__traits(getMember, this.isSetFlags, fieldName) = true;
}
}
void unset(string fieldName)() if (is(MemberType!(This, fieldName))) {
static if (is(typeof(mixin("this.isSetFlags." ~ fieldName)) : bool)) {
__traits(getMember, this.isSetFlags, fieldName) = false;
}
__traits(getMember, this, fieldName) = MemberType!(This, fieldName).init;
}
bool isSet(string fieldName)() const @property if (
is(MemberType!(This, fieldName))
) {
static if (isNullable!(MemberType!(This, fieldName))) {
return __traits(getMember, this, fieldName) !is null;
} else static if (is(typeof(mixin("this.isSetFlags." ~ fieldName)) : bool)) {
return __traits(getMember, this.isSetFlags, fieldName);
} else {
// This is a required field, which is always set.
return true;
}
}
static if (is(This _ == class)) {
override string toString() const {
return thriftToStringImpl();
}
override bool opEquals(Object other) const {
auto rhs = cast(This)other;
if (rhs) {
return thriftOpEqualsImpl(rhs);
}
return (cast()super).opEquals(other);
}
} else {
string toString() const {
return thriftToStringImpl();
}
bool opEquals(ref const This other) const {
return thriftOpEqualsImpl(other);
}
}
private string thriftToStringImpl() const {
import std.conv : to;
string result = This.stringof ~ "(";
mixin({
string code = "";
bool first = true;
foreach (name; FieldNames!(This, fieldMeta)) {
if (first) {
first = false;
} else {
code ~= "result ~= `, `;\n";
}
code ~= "result ~= `" ~ name ~ ": ` ~ to!string(cast()this." ~ name ~ ");\n";
code ~= "if (!isSet!q{" ~ name ~ "}) {\n";
code ~= "result ~= ` (unset)`;\n";
code ~= "}\n";
}
return code;
}());
result ~= ")";
return result;
}
private bool thriftOpEqualsImpl(const ref This rhs) const {
foreach (name; FieldNames!This) {
if (mixin("this." ~ name) != mixin("rhs." ~ name)) return false;
}
return true;
}
static if (canFind!`!a.defaultValue.empty`(mergeFieldMeta!(This, fieldMetaData))) {
static if (is(This _ == class)) {
this() {
mixin(thriftFieldInitCode!(mergeFieldMeta!(This, fieldMetaData))("this"));
}
} else {
// DMD @@BUG@@: Have to use auto here to avoid »no size yet for forward
// reference« errors.
static auto opCall() {
auto result = This.init;
mixin(thriftFieldInitCode!(mergeFieldMeta!(This, fieldMetaData))("result"));
return result;
}
}
}
void read(Protocol)(Protocol proto) if (isTProtocol!Protocol) {
// Need to explicitly specify fieldMetaData here, since it isn't already
// picked up in some situations (e.g. the TArgs struct for methods with
// multiple parameters in async_test_servers) otherwise. Due to a DMD
// @@BUG@@, we need to explicitly specify the other template parameters
// as well.
readStruct!(This, Protocol, fieldMetaData, false)(this, proto);
}
void write(Protocol)(Protocol proto) const if (isTProtocol!Protocol) {
writeStruct!(This, Protocol, fieldMetaData, false)(this, proto);
}
}
// DMD @@BUG@@: Having this inside TStructHelpers leads to weird lookup errors
// (e.g. for std.arry.empty).
string thriftFieldInitCode(alias fieldMeta)(string thisName) {
string code = "";
foreach (field; fieldMeta) {
if (field.defaultValue.empty) continue;
code ~= thisName ~ "." ~ field.name ~ " = " ~ field.defaultValue ~ ";\n";
}
return code;
}
version (unittest) {
// Cannot make this nested in the unittest block due to a »no size yet for
// forward reference« error.
struct Foo {
string a;
int b;
int c;
mixin TStructHelpers!([
TFieldMeta("a", 1),
TFieldMeta("b", 2, TReq.OPT_IN_REQ_OUT),
TFieldMeta("c", 3, TReq.REQUIRED, "4")
]);
}
}
unittest {
auto f = Foo();
f.set!"b"(12345);
assert(f.isSet!"b");
f.unset!"b"();
assert(!f.isSet!"b");
f.set!"b"(12345);
assert(f.isSet!"b");
f.unset!"b"();
f.a = "a string";
assert(f.toString() == `Foo(a: a string, b: 0 (unset), c: 4)`);
}
/**
* Generates an eponymous struct with boolean flags for the non-required
* non-nullable fields of T.
*
* Nullable fields are just set to null to signal »not set«, so no flag is
* emitted for them, even if they are optional.
*
* In most cases, you do not want to use this directly, but via TStructHelpers
* instead.
*/
template TIsSetFlags(T, alias fieldMetaData) {
mixin({
string code = "struct TIsSetFlags {\n";
foreach (meta; fieldMetaData) {
code ~= "static if (!is(MemberType!(T, `" ~ meta.name ~ "`))) {\n";
code ~= q{
static assert(false, "Field '" ~ meta.name ~
"' referenced in metadata not present in struct '" ~ T.stringof ~ "'.");
};
code ~= "}";
if (meta.req == TReq.OPTIONAL || meta.req == TReq.OPT_IN_REQ_OUT) {
code ~= "else static if (!isNullable!(MemberType!(T, `" ~ meta.name ~ "`))) {\n";
code ~= " bool " ~ meta.name ~ ";\n";
code ~= "}\n";
}
}
code ~= "}";
return code;
}());
}
/**
* Deserializes a Thrift struct from a protocol.
*
* Using the Protocol template parameter, the concrete TProtocol to use can be
* be specified. If the pointerStruct parameter is set to true, the struct
* fields are expected to be pointers to the actual data. This is used
* internally (combined with TPResultStruct) and usually should not be used in
* user code.
*
* This is a free function to make it possible to read exisiting structs from
* the wire without altering their definitions.
*/
void readStruct(T, Protocol, alias fieldMetaData = cast(TFieldMeta[])null,
bool pointerStruct = false)(ref T s, Protocol p) if (isTProtocol!Protocol)
{
mixin({
string code;
// Check that all fields for which there is meta info are actually in the
// passed struct type.
foreach (field; mergeFieldMeta!(T, fieldMetaData)) {
code ~= "static assert(is(MemberType!(T, `" ~ field.name ~ "`)));\n";
}
// Returns the code string for reading a value of type F off the wire and
// assigning it to v. The level parameter is used to make sure that there
// are no conflicting variable names on recursive calls.
string readValueCode(ValueType)(string v, size_t level = 0) {
// Some non-ambigous names to use (shadowing is not allowed in D).
immutable i = "i" ~ to!string(level);
immutable elem = "elem" ~ to!string(level);
immutable key = "key" ~ to!string(level);
immutable list = "list" ~ to!string(level);
immutable map = "map" ~ to!string(level);
immutable set = "set" ~ to!string(level);
immutable value = "value" ~ to!string(level);
alias FullyUnqual!ValueType F;
static if (is(F == bool)) {
return v ~ " = p.readBool();";
} else static if (is(F == byte)) {
return v ~ " = p.readByte();";
} else static if (is(F == double)) {
return v ~ " = p.readDouble();";
} else static if (is(F == short)) {
return v ~ " = p.readI16();";
} else static if (is(F == int)) {
return v ~ " = p.readI32();";
} else static if (is(F == long)) {
return v ~ " = p.readI64();";
} else static if (is(F : string)) {
return v ~ " = p.readString();";
} else static if (is(F == enum)) {
return v ~ " = cast(typeof(" ~ v ~ "))p.readI32();";
} else static if (is(F _ : E[], E)) {
return "{\n" ~
"auto " ~ list ~ " = p.readListBegin();\n" ~
// TODO: Check element type here?
v ~ " = new typeof(" ~ v ~ "[0])[" ~ list ~ ".size];\n" ~
"foreach (" ~ i ~ "; 0 .. " ~ list ~ ".size) {\n" ~
readValueCode!E(v ~ "[" ~ i ~ "]", level + 1) ~ "\n" ~
"}\n" ~
"p.readListEnd();\n" ~
"}";
} else static if (is(F _ : V[K], K, V)) {
return "{\n" ~
"auto " ~ map ~ " = p.readMapBegin();" ~
v ~ " = null;\n" ~
// TODO: Check key/value types here?
"foreach (" ~ i ~ "; 0 .. " ~ map ~ ".size) {\n" ~
"FullyUnqual!(typeof(" ~ v ~ ".keys[0])) " ~ key ~ ";\n" ~
readValueCode!K(key, level + 1) ~ "\n" ~
"typeof(" ~ v ~ ".values[0]) " ~ value ~ ";\n" ~
readValueCode!V(value, level + 1) ~ "\n" ~
v ~ "[cast(typeof(" ~ v ~ ".keys[0]))" ~ key ~ "] = " ~ value ~ ";\n" ~
"}\n" ~
"p.readMapEnd();" ~
"}";
} else static if (is(F _ : HashSet!(E), E)) {
return "{\n" ~
"auto " ~ set ~ " = p.readSetBegin();" ~
// TODO: Check element type here?
v ~ " = new typeof(" ~ v ~ ")();\n" ~
"foreach (" ~ i ~ "; 0 .. " ~ set ~ ".size) {\n" ~
"typeof(" ~ v ~ "[][0]) " ~ elem ~ ";\n" ~
readValueCode!E(elem, level + 1) ~ "\n" ~
v ~ " ~= " ~ elem ~ ";\n" ~
"}\n" ~
"p.readSetEnd();" ~
"}";
} else static if (is(F == struct) || is(F : TException)) {
static if (is(F == struct)) {
auto result = v ~ " = typeof(" ~ v ~ ")();\n";
} else {
auto result = v ~ " = new typeof(" ~ v ~ ")();\n";
}
static if (__traits(compiles, F.init.read(TProtocol.init))) {
result ~= v ~ ".read(p);";
} else {
result ~= "readStruct(" ~ v ~ ", p);";
}
return result;
} else {
static assert(false, "Cannot represent type in Thrift: " ~ F.stringof);
}
}
string readFieldCode(FieldType)(string name, short id, TReq req) {
static if (pointerStruct && isPointer!FieldType) {
immutable v = "(*s." ~ name ~ ")";
alias pointerTarget!FieldType F;
} else {
immutable v = "s." ~ name;
alias FieldType F;
}
string code = "case " ~ to!string(id) ~ ":\n";
code ~= "if (f.type == " ~ dToTTypeString!F ~ ") {\n";
code ~= readValueCode!F(v) ~ "\n";
if (req == TReq.REQUIRED) {
// For required fields, set the corresponding local isSet variable.
code ~= "isSet_" ~ name ~ " = true;\n";
} else if (!isNullable!F){
code ~= "s.isSetFlags." ~ name ~ " = true;\n";
}
code ~= "} else skip(p, f.type);\n";
code ~= "break;\n";
return code;
}
// Code for the local boolean flags used to make sure required fields have
// been found.
string isSetFlagCode = "";
// Code for checking whether the flags for the required fields are true.
string isSetCheckCode = "";
/// Code for the case statements storing the fields to the result struct.
string readMembersCode = "";
// The last automatically assigned id – fields with no meta information
// are assigned (in lexical order) descending negative ids, starting with
// -1, just like the Thrift compiler does.
short lastId;
foreach (name; FieldNames!T) {
enum req = memberReq!(T, name, fieldMetaData);
if (req == TReq.REQUIRED) {
// For required fields, generate local bool flags to keep track
// whether the field has been encountered.
immutable n = "isSet_" ~ name;
isSetFlagCode ~= "bool " ~ n ~ ";\n";
isSetCheckCode ~= "enforce(" ~ n ~ ", new TProtocolException(" ~
"`Required field '" ~ name ~ "' not found in serialized data`, " ~
"TProtocolException.Type.INVALID_DATA));\n";
}
enum meta = find!`a.name == b`(mergeFieldMeta!(T, fieldMetaData), name);
static if (meta.empty) {
--lastId;
version (TVerboseCodegen) {
code ~= "pragma(msg, `[thrift.codegen.base.readStruct] Warning: No " ~
"meta information for field '" ~ name ~ "' in struct '" ~
T.stringof ~ "'. Assigned id: " ~ to!string(lastId) ~ ".`);\n";
}
readMembersCode ~= readFieldCode!(MemberType!(T, name))(
name, lastId, req);
} else static if (req != TReq.IGNORE) {
readMembersCode ~= readFieldCode!(MemberType!(T, name))(
name, meta.front.id, req);
}
}
code ~= isSetFlagCode;
code ~= "p.readStructBegin();\n";
code ~= "while (true) {\n";
code ~= "auto f = p.readFieldBegin();\n";
code ~= "if (f.type == TType.STOP) break;\n";
code ~= "switch(f.id) {\n";
code ~= readMembersCode;
code ~= "default: skip(p, f.type);\n";
code ~= "}\n";
code ~= "p.readFieldEnd();\n";
code ~= "}\n";
code ~= "p.readStructEnd();\n";
code ~= isSetCheckCode;
return code;
}());
}
/**
* Serializes a struct to the target protocol.
*
* Using the Protocol template parameter, the concrete TProtocol to use can be
* be specified. If the pointerStruct parameter is set to true, the struct
* fields are expected to be pointers to the actual data. This is used
* internally (combined with TPargsStruct) and usually should not be used in
* user code.
*
* This is a free function to make it possible to read exisiting structs from
* the wire without altering their definitions.
*/
void writeStruct(T, Protocol, alias fieldMetaData = cast(TFieldMeta[])null,
bool pointerStruct = false) (const T s, Protocol p) if (isTProtocol!Protocol)
{
mixin({
// Check that all fields for which there is meta info are actually in the
// passed struct type.
string code = "";
foreach (field; mergeFieldMeta!(T, fieldMetaData)) {
code ~= "static assert(is(MemberType!(T, `" ~ field.name ~ "`)));\n";
}
// Check that required nullable members are non-null.
// WORKAROUND: To stop LDC from emitting the manifest constant »meta« below
// into the writeStruct function body this is inside the string mixin
// block – the code wouldn't depend on it (this is an LDC bug, and because
// of it a new array would be allocate on each method invocation at runtime).
foreach (name; StaticFilter!(
Compose!(isNullable, PApply!(MemberType, T)),
FieldNames!T
)) {
static if (memberReq!(T, name, fieldMetaData) == TReq.REQUIRED) {
code ~= `enforce(__traits(getMember, s, name) !is null,
new TException("Required field '` ~ name ~ `' is null."));\n`;
}
}
return code;
}());
p.writeStructBegin(TStruct(T.stringof));
mixin({
string writeValueCode(ValueType)(string v, size_t level = 0) {
// Some non-ambigous names to use (shadowing is not allowed in D).
immutable elem = "elem" ~ to!string(level);
immutable key = "key" ~ to!string(level);
immutable value = "value" ~ to!string(level);
alias FullyUnqual!ValueType F;
static if (is(F == bool)) {
return "p.writeBool(" ~ v ~ ");";
} else static if (is(F == byte)) {
return "p.writeByte(" ~ v ~ ");";
} else static if (is(F == double)) {
return "p.writeDouble(" ~ v ~ ");";
} else static if (is(F == short)) {
return "p.writeI16(" ~ v ~ ");";
} else static if (is(F == int)) {
return "p.writeI32(" ~ v ~ ");";
} else static if (is(F == long)) {
return "p.writeI64(" ~ v ~ ");";
} else static if (is(F : string)) {
return "p.writeString(" ~ v ~ ");";
} else static if (is(F == enum)) {
return "p.writeI32(cast(int)" ~ v ~ ");";
} else static if (is(F _ : E[], E)) {
return "p.writeListBegin(TList(" ~ dToTTypeString!E ~ ", " ~ v ~
".length));\n" ~
"foreach (" ~ elem ~ "; " ~ v ~ ") {\n" ~
writeValueCode!E(elem, level + 1) ~ "\n" ~
"}\n" ~
"p.writeListEnd();";
} else static if (is(F _ : V[K], K, V)) {
return "p.writeMapBegin(TMap(" ~ dToTTypeString!K ~ ", " ~
dToTTypeString!V ~ ", " ~ v ~ ".length));\n" ~
"foreach (" ~ key ~ ", " ~ value ~ "; " ~ v ~ ") {\n" ~
writeValueCode!K(key, level + 1) ~ "\n" ~
writeValueCode!V(value, level + 1) ~ "\n" ~
"}\n" ~
"p.writeMapEnd();";
} else static if (is(F _ : HashSet!E, E)) {
return "p.writeSetBegin(TSet(" ~ dToTTypeString!E ~ ", " ~ v ~
".length));\n" ~
"foreach (" ~ elem ~ "; " ~ v ~ "[]) {\n" ~
writeValueCode!E(elem, level + 1) ~ "\n" ~
"}\n" ~
"p.writeSetEnd();";
} else static if (is(F == struct) || is(F : TException)) {
static if (__traits(compiles, F.init.write(TProtocol.init))) {
return v ~ ".write(p);";
} else {
return "writeStruct(" ~ v ~ ", p);";
}
} else {
static assert(false, "Cannot represent type in Thrift: " ~ F.stringof);
}
}
string writeFieldCode(FieldType)(string name, short id, TReq req) {
string code;
if (!pointerStruct && req == TReq.OPTIONAL) {
code ~= "if (s.isSet!`" ~ name ~ "`) {\n";
}
static if (pointerStruct && isPointer!FieldType) {
immutable v = "(*s." ~ name ~ ")";
alias pointerTarget!FieldType F;
} else {
immutable v = "s." ~ name;
alias FieldType F;
}
code ~= "p.writeFieldBegin(TField(`" ~ name ~ "`, " ~ dToTTypeString!F ~
", " ~ to!string(id) ~ "));\n";
code ~= writeValueCode!F(v) ~ "\n";
code ~= "p.writeFieldEnd();\n";
if (!pointerStruct && req == TReq.OPTIONAL) {
code ~= "}\n";
}
return code;
}
// The last automatically assigned id – fields with no meta information
// are assigned (in lexical order) descending negative ids, starting with
// -1, just like the Thrift compiler does.
short lastId;
string code = "";
foreach (name; FieldNames!T) {
alias MemberType!(T, name) F;
enum req = memberReq!(T, name, fieldMetaData);
enum meta = find!`a.name == b`(mergeFieldMeta!(T, fieldMetaData), name);
if (meta.empty) {
--lastId;
version (TVerboseCodegen) {
code ~= "pragma(msg, `[thrift.codegen.base.writeStruct] Warning: No " ~
"meta information for field '" ~ name ~ "' in struct '" ~
T.stringof ~ "'. Assigned id: " ~ to!string(lastId) ~ ".`);\n";
}
code ~= writeFieldCode!F(name, lastId, req);
} else if (req != TReq.IGNORE) {
code ~= writeFieldCode!F(name, meta.front.id, req);
}
}
return code;
}());
p.writeFieldStop();
p.writeStructEnd();
}
private {
/*
* Returns a D code string containing the matching TType value for a passed
* D type, e.g. dToTTypeString!byte == "TType.BYTE".
*/
template dToTTypeString(T) {
static if (is(FullyUnqual!T == bool)) {
enum dToTTypeString = "TType.BOOL";
} else static if (is(FullyUnqual!T == byte)) {
enum dToTTypeString = "TType.BYTE";
} else static if (is(FullyUnqual!T == double)) {
enum dToTTypeString = "TType.DOUBLE";
} else static if (is(FullyUnqual!T == short)) {
enum dToTTypeString = "TType.I16";
} else static if (is(FullyUnqual!T == int)) {
enum dToTTypeString = "TType.I32";
} else static if (is(FullyUnqual!T == long)) {
enum dToTTypeString = "TType.I64";
} else static if (is(FullyUnqual!T : string)) {
enum dToTTypeString = "TType.STRING";
} else static if (is(FullyUnqual!T == enum)) {
enum dToTTypeString = "TType.I32";
} else static if (is(FullyUnqual!T _ : U[], U)) {
enum dToTTypeString = "TType.LIST";
} else static if (is(FullyUnqual!T _ : V[K], K, V)) {
enum dToTTypeString = "TType.MAP";
} else static if (is(FullyUnqual!T _ : HashSet!E, E)) {
enum dToTTypeString = "TType.SET";
} else static if (is(FullyUnqual!T == struct)) {
enum dToTTypeString = "TType.STRUCT";
} else static if (is(FullyUnqual!T : TException)) {
enum dToTTypeString = "TType.STRUCT";
} else {
static assert(false, "Cannot represent type in Thrift: " ~ T.stringof);
}
}
}