-
Notifications
You must be signed in to change notification settings - Fork 1
/
type.go
1122 lines (1027 loc) · 31.8 KB
/
type.go
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
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package signature
import (
"bytes"
"fmt"
"log"
"reflect"
"strings"
"github.com/dave/jennifer/jen"
)
// TypeSet is a container which contains exactly one instance of each
// Type currently generated. It is used to generate the
// type declaration only once.
type TypeSet struct {
Names []string
Types []Type
}
// Declare writes all the registered Type into the jen.File.
func (s *TypeSet) Declare(f *jen.File) {
for _, v := range s.Types {
v.TypeDeclaration(f)
}
}
// Search returns a Type if a name is associated.
func (s *TypeSet) Search(name string) Type {
for i, n := range s.Names {
if n == name {
return s.Types[i]
}
}
return nil
}
// ResolveCollision returns a type name not already present in the
// set. If name if not present, returns name, else it returns a new
// string derived from name.
func (s *TypeSet) ResolveCollision(originalName, signature string) string {
name := originalName
// loop 100 times to avoid name collision
for i := 0; i < 100; i++ {
ok := true // can use the name
for i, n := range s.Names {
if n == name {
if s.Types[i].Signature() == signature {
// already registered
return name
}
ok = false
break
}
}
if ok {
return name
}
name = fmt.Sprintf("%s_%d", originalName, i)
}
return "can_not_register_name_" + originalName
}
// NewTypeSet construct a new TypeSet.
func NewTypeSet() *TypeSet {
typ := make([]Type, 0)
nam := make([]string, 0)
return &TypeSet{nam, typ}
}
// Type represents a type of a signature or a type
// embedded inside a signature. Type represents types for
// primitive types (int, long, float, string), vectors of a type,
// associative maps and structures.
type Type interface {
Signature() string
SignatureIDL() string
TypeName() *Statement
TypeDeclaration(*jen.File)
RegisterTo(s *TypeSet)
Marshal(id string, writer string) *Statement // returns an error
Unmarshal(reader string) *Statement // returns (type, err)
Reader() TypeReader
Type() reflect.Type
}
type typeConstructor struct {
signature string
signatureIDL string
typeName *Statement
marshal func(id string, writer string) *Statement // returns an error
unmarshal func(reader string) *Statement // returns (type, err)
reader TypeReader
typ reflect.Type
}
func (t *typeConstructor) Signature() string {
return t.signature
}
func (t *typeConstructor) SignatureIDL() string {
return t.signatureIDL
}
func (t *typeConstructor) TypeName() *Statement {
return t.typeName
}
func (t *typeConstructor) TypeDeclaration(f *jen.File) {
return
}
func (t *typeConstructor) RegisterTo(s *TypeSet) {
return
}
func (t *typeConstructor) Marshal(id string, writer string) *Statement {
return t.marshal(id, writer)
}
func (t *typeConstructor) Unmarshal(reader string) *Statement {
return t.unmarshal(reader)
}
func (t *typeConstructor) Reader() TypeReader {
return t.reader
}
func (t *typeConstructor) Type() reflect.Type {
return t.typ
}
// Print render the type into a string. It is only used for testing.
func Print(v Type) string {
buf := bytes.NewBufferString("")
v.TypeName().Render(buf)
return buf.String()
}
// NewInt8Type is a contructor for the representation of a uint64.
func NewInt8Type() Type {
return &typeConstructor{
signature: "c",
signatureIDL: "int8",
typeName: jen.Int8(),
marshal: func(id string, writer string) *Statement {
return jen.Qual("github.com/lugu/qiloop/type/basic",
"WriteInt8").Call(jen.Id(id), jen.Id(writer))
},
unmarshal: func(reader string) *Statement {
return jen.Qual("github.com/lugu/qiloop/type/basic",
"ReadInt8").Call(jen.Id(reader))
},
reader: constReader(1),
typ: reflect.TypeOf((int8)(0)),
}
}
// NewUint8Type is a contructor for the representation of a uint64.
func NewUint8Type() Type {
return &typeConstructor{
signature: "C",
signatureIDL: "uint8",
typeName: jen.Uint8(),
marshal: func(id string, writer string) *Statement {
return jen.Qual("github.com/lugu/qiloop/type/basic",
"WriteUint8").Call(jen.Id(id), jen.Id(writer))
},
unmarshal: func(reader string) *Statement {
return jen.Qual("github.com/lugu/qiloop/type/basic",
"ReadUint8").Call(jen.Id(reader))
},
reader: constReader(1),
typ: reflect.TypeOf((uint8)(0)),
}
}
// NewInt16Type is a contructor for the representation of a uint64.
func NewInt16Type() Type {
return &typeConstructor{
signature: "w",
signatureIDL: "int16",
typeName: jen.Int16(),
marshal: func(id string, writer string) *Statement {
return jen.Qual("github.com/lugu/qiloop/type/basic",
"WriteInt16").Call(jen.Id(id), jen.Id(writer))
},
unmarshal: func(reader string) *Statement {
return jen.Qual("github.com/lugu/qiloop/type/basic",
"ReadInt16").Call(jen.Id(reader))
},
reader: constReader(2),
typ: reflect.TypeOf((int16)(0)),
}
}
// NewUint16Type is a contructor for the representation of a uint64.
func NewUint16Type() Type {
return &typeConstructor{
signature: "W",
signatureIDL: "uint16",
typeName: jen.Uint16(),
marshal: func(id string, writer string) *Statement {
return jen.Qual("github.com/lugu/qiloop/type/basic",
"WriteUint16").Call(jen.Id(id), jen.Id(writer))
},
unmarshal: func(reader string) *Statement {
return jen.Qual("github.com/lugu/qiloop/type/basic",
"ReadUint16").Call(jen.Id(reader))
},
reader: constReader(2),
typ: reflect.TypeOf((uint16)(0)),
}
}
// NewIntType is a contructor for the representation of an int32.
func NewIntType() Type {
return &typeConstructor{
signature: "i",
signatureIDL: "int32",
typeName: jen.Int32(),
marshal: func(id string, writer string) *Statement {
return jen.Qual("github.com/lugu/qiloop/type/basic",
"WriteInt32").Call(jen.Id(id), jen.Id(writer))
},
unmarshal: func(reader string) *Statement {
return jen.Qual("github.com/lugu/qiloop/type/basic",
"ReadInt32").Call(jen.Id(reader))
},
reader: constReader(4),
typ: reflect.TypeOf((int32)(0)),
}
}
// NewUIntType is a contructor for the representation of an uint32.
func NewUintType() Type {
return &typeConstructor{
signature: "I",
signatureIDL: "uint32",
typeName: jen.Uint32(),
marshal: func(id string, writer string) *Statement {
return jen.Qual("github.com/lugu/qiloop/type/basic",
"WriteUint32").Call(jen.Id(id), jen.Id(writer))
},
unmarshal: func(reader string) *Statement {
return jen.Qual("github.com/lugu/qiloop/type/basic",
"ReadUint32").Call(jen.Id(reader))
},
reader: constReader(4),
typ: reflect.TypeOf((uint32)(0)),
}
}
// NewLongType is a contructor for the representation of a uint64.
func NewLongType() Type {
return &typeConstructor{
signature: "l",
signatureIDL: "int64",
typeName: jen.Int64(),
marshal: func(id string, writer string) *Statement {
return jen.Qual("github.com/lugu/qiloop/type/basic",
"WriteInt64").Call(jen.Id(id), jen.Id(writer))
},
unmarshal: func(reader string) *Statement {
return jen.Qual("github.com/lugu/qiloop/type/basic",
"ReadInt64").Call(jen.Id(reader))
},
reader: constReader(8),
typ: reflect.TypeOf((int64)(0)),
}
}
// NewULongType is a contructor for the representation of a uint64.
func NewULongType() Type {
return &typeConstructor{
signature: "L",
signatureIDL: "uint64",
typeName: jen.Uint64(),
marshal: func(id string, writer string) *Statement {
return jen.Qual("github.com/lugu/qiloop/type/basic",
"WriteUint64").Call(jen.Id(id), jen.Id(writer))
},
unmarshal: func(reader string) *Statement {
return jen.Qual("github.com/lugu/qiloop/type/basic",
"ReadUint64").Call(jen.Id(reader))
},
reader: constReader(8),
typ: reflect.TypeOf((uint64)(0)),
}
}
// NewFloatType is a contructor for the representation of a float32.
func NewFloatType() Type {
return &typeConstructor{
signature: "f",
signatureIDL: "float32",
typeName: jen.Float32(),
marshal: func(id string, writer string) *Statement {
return jen.Qual("github.com/lugu/qiloop/type/basic",
"WriteFloat32").Call(jen.Id(id), jen.Id(writer))
},
unmarshal: func(reader string) *Statement {
return jen.Qual("github.com/lugu/qiloop/type/basic",
"ReadFloat32").Call(jen.Id(reader))
},
reader: constReader(4),
typ: reflect.TypeOf((float32)(0)),
}
}
// NewDoubleType is a contructor for the representation of a float32.
func NewDoubleType() Type {
return &typeConstructor{
signature: "d",
signatureIDL: "float64",
typeName: jen.Float64(),
marshal: func(id string, writer string) *Statement {
return jen.Qual("github.com/lugu/qiloop/type/basic",
"WriteFloat64").Call(jen.Id(id), jen.Id(writer))
},
unmarshal: func(reader string) *Statement {
return jen.Qual("github.com/lugu/qiloop/type/basic",
"ReadFloat64").Call(jen.Id(reader))
},
reader: constReader(8),
typ: reflect.TypeOf((float64)(0)),
}
}
// NewStringType is a contructor for the representation of a string.
func NewStringType() Type {
return &typeConstructor{
signature: "s",
signatureIDL: "str",
typeName: jen.String(),
marshal: func(id string, writer string) *Statement {
return jen.Id("basic.WriteString").Call(jen.Id(id),
jen.Id(writer))
},
unmarshal: func(reader string) *Statement {
return jen.Qual("github.com/lugu/qiloop/type/basic",
"ReadString").Call(jen.Id(reader))
},
reader: stringReader{},
typ: reflect.TypeOf(string("")),
}
}
// NewVoidType is a contructor for the representation of the
// absence of a return type. Only used in the context of a returned
// type.
func NewVoidType() Type {
return &typeConstructor{
signature: "v",
signatureIDL: "nothing",
typeName: jen.Empty(),
marshal: func(id string, writer string) *Statement {
return jen.Nil()
},
unmarshal: func(reader string) *Statement {
return jen.Empty()
},
reader: constReader(0),
typ: reflect.TypeOf(struct{}{}),
}
}
// NewValueType is a contructor for the representation of a Value.
func NewValueType() Type {
return &typeConstructor{
signature: "m",
signatureIDL: "any",
typeName: jen.Qual("github.com/lugu/qiloop/type/value", "Value"),
marshal: func(id string, writer string) *Statement {
return jen.Id(id).Dot("Write").Call(jen.Id(writer))
},
unmarshal: func(reader string) *Statement {
return jen.Qual("github.com/lugu/qiloop/type/value", "NewValue").Call(jen.Id(reader))
},
reader: valueReader{},
typ: reflect.TypeOf((*interface{})(nil)),
}
}
// NewBoolType is a contructor for the representation of a bool.
func NewBoolType() Type {
return &typeConstructor{
signature: "b",
signatureIDL: "bool",
typeName: jen.Bool(),
marshal: func(id string, writer string) *Statement {
return jen.Qual("github.com/lugu/qiloop/type/basic", "WriteBool").Call(jen.Id(id), jen.Id(writer))
},
unmarshal: func(reader string) *Statement {
return jen.Qual("github.com/lugu/qiloop/type/basic", "ReadBool").Call(jen.Id(reader))
},
reader: constReader(1),
typ: reflect.TypeOf((bool)(true)),
}
}
// NewMetaObjectType is a contructor for the representation of an
// object.
func NewMetaObjectType() Type {
typ, _ := Parse(MetaObjectSignature)
reader, err := MakeReader(MetaObjectSignature)
if err != nil {
panic(fmt.Errorf("invalid MetaObjectSignature: %s",
MetaObjectSignature))
}
return &typeConstructor{
signature: MetaObjectSignature,
signatureIDL: "MetaObject",
typeName: jen.Qual("github.com/lugu/qiloop/type/object", "MetaObject"),
marshal: func(id string, writer string) *Statement {
return jen.Qual("github.com/lugu/qiloop/type/object", "WriteMetaObject").Call(jen.Id(id), jen.Id(writer))
},
unmarshal: func(reader string) *Statement {
return jen.Qual("github.com/lugu/qiloop/type/object", "ReadMetaObject").Call(jen.Id(reader))
},
reader: reader,
typ: typ.Type(),
}
}
// NewObjectType is a contructor for the representation of a Value.
func NewObjectType() Type {
sig := "(({I(Issss[(ss)<MetaMethodParameter,name,description>]s)<MetaMethod,uid,returnSignature,name,parametersSignature,description,parameters,returnDescription>}{I(Iss)<MetaSignal,uid,name,signature>}{I(Iss)<MetaProperty,uid,name,signature>}s)<MetaObject,methods,signals,properties,description>II)<ObjectReference,metaObject,serviceID,objectID>"
typ, _ := Parse(sig)
reader, _ := MakeReader(sig)
return &typeConstructor{
signature: "o",
signatureIDL: "obj",
typeName: jen.Qual("github.com/lugu/qiloop/type/object", "ObjectReference"),
marshal: func(id string, writer string) *Statement {
return jen.Qual("github.com/lugu/qiloop/type/object", "WriteObjectReference").Call(jen.Id(id), jen.Id(writer))
},
unmarshal: func(reader string) *Statement {
return jen.Qual("github.com/lugu/qiloop/type/object", "ReadObjectReference").Call(jen.Id(reader))
},
reader: reader,
typ: typ.Type(),
}
}
func TypeIsObjectReference(t Type) bool {
if t.Signature() != "o" {
return false
}
name := t.TypeName()
if reflect.DeepEqual(name,
jen.Qual("github.com/lugu/qiloop/type/object",
"ObjectReference"),
) {
return true
}
return false
}
// NewUnknownType is a contructor for an unknown type.
func NewUnknownType() Type {
return &typeConstructor{
signature: "X",
signatureIDL: "unknown",
typeName: jen.Id("interface{}"),
marshal: func(id string, writer string) *Statement {
return jen.Qual("fmt", "Errorf").Call(
jen.Lit("marshal unknown type: %v"),
jen.Id(id),
)
},
unmarshal: func(reader string) *Statement {
return jen.List(jen.Nil(),
jen.Qual("fmt", "Errorf").Call(
jen.Lit("unmarshal unknown type: %v"),
jen.Id(reader),
),
)
},
reader: UnknownReader("X"),
typ: reflect.TypeOf((*error)(nil)),
}
}
// NewListType is a contructor for the representation of a slice.
func NewListType(value Type) *ListType {
return &ListType{value}
}
// ListType represents a slice.
type ListType struct {
value Type
}
// Signature returns "[<signature>]" where <signature> is the
// signature of the type of the list.
func (l *ListType) Signature() string {
return fmt.Sprintf("[%s]", l.value.Signature())
}
// SignatureIDL returns "Vec<signature>" where "signature" is the IDL
// signature of the type of the list.
func (l *ListType) SignatureIDL() string {
return fmt.Sprintf("Vec<%s>", l.value.SignatureIDL())
}
// TypeName returns a statement to be inserted when the type is to be
// declared.
func (l *ListType) TypeName() *Statement {
return jen.Index().Add(l.value.TypeName())
}
// RegisterTo adds the type to the TypeSet.
func (l *ListType) RegisterTo(s *TypeSet) {
l.value.RegisterTo(s)
return
}
// TypeDeclaration writes the type declaration into file.
func (l *ListType) TypeDeclaration(file *jen.File) {
return
}
// Marshal returns a statement which represent the code needed to put
// the variable "id" into the io.Writer "writer" while returning an
// error.
func (l *ListType) Marshal(listID string, writer string) *Statement {
return jen.Func().Params().Params(jen.Error()).Block(
jen.Err().Op(":=").Qual("github.com/lugu/qiloop/type/basic", "WriteUint32").Call(jen.Id("uint32").Call(
jen.Id("len").Call(jen.Id(listID))),
jen.Id(writer)),
jen.Id(`if (err != nil) {
return fmt.Errorf("write slice size: %s", err)
}`),
jen.For(
jen.Id("_, v := range "+listID),
).Block(
jen.Err().Op("=").Add(l.value.Marshal("v", writer)),
jen.Id(`if (err != nil) {
return fmt.Errorf("write slice value: %s", err)
}`),
),
jen.Return(jen.Nil()),
).Call()
}
// Unmarshal returns a statement which represent the code needed to read
// from a reader "reader" of type io.Reader and returns both the value
// read and an error.
func (l *ListType) Unmarshal(reader string) *Statement {
return jen.Func().Params().Params(
jen.Id("b").Index().Add(l.value.TypeName()),
jen.Err().Error(),
).Block(
jen.Id("size, err := basic.ReadUint32").Call(jen.Id(reader)),
jen.If(jen.Id("err != nil")).Block(
jen.Return(jen.Id("b"), jen.Qual("fmt", "Errorf").Call(jen.Id(`"read slice size: %s", err`)))),
jen.Id("b").Op("=").Id("make").Call(l.TypeName(), jen.Id("size")),
jen.For(
jen.Id("i := 0; i < int(size); i++"),
).Block(
jen.Id("b[i], err =").Add(l.value.Unmarshal(reader)),
jen.Id(`if (err != nil) {
return b, fmt.Errorf("read slice value: %s", err)
}`),
),
jen.Return(jen.Id("b"), jen.Nil()),
).Call()
}
// Reader returns a list TypeReader.
func (l *ListType) Reader() TypeReader {
return varReader{
reader: l.value.Reader(),
}
}
// Type returns the Go representation of the type.
func (l *ListType) Type() reflect.Type {
return reflect.SliceOf(l.value.Type())
}
// NewMapType is a contructor for the representation of a map.
func NewMapType(key, value Type) *MapType {
return &MapType{key, value}
}
// MapType represents a map.
type MapType struct {
key Type
value Type
}
// Signature returns "{<signature key><signature value>}" where
// <signature key> is the signature of the key and <signature value>
// the signature of the value.
func (m *MapType) Signature() string {
return fmt.Sprintf("{%s%s}", m.key.Signature(), m.value.Signature())
}
// SignatureIDL returns "map<key><value>" where "key" is the IDL
// signature of the key and "value" the IDL signature of the value.
func (m *MapType) SignatureIDL() string {
return fmt.Sprintf("Map<%s,%s>", m.key.SignatureIDL(), m.value.SignatureIDL())
}
// TypeName returns a statement to be inserted when the type is to be
// declared.
func (m *MapType) TypeName() *Statement {
return jen.Map(m.key.TypeName()).Add(m.value.TypeName())
}
// RegisterTo adds the type to the TypeSet.
func (m *MapType) RegisterTo(s *TypeSet) {
m.key.RegisterTo(s)
m.value.RegisterTo(s)
return
}
// TypeDeclaration writes the type declaration into file.
func (m *MapType) TypeDeclaration(file *jen.File) {
return
}
// Reader returns a map TypeReader.
func (m *MapType) Reader() TypeReader {
return varReader{
reader: tupleReader([]memberReader{
memberReader{
name: "key",
reader: m.key.Reader(),
},
memberReader{
name: "value",
reader: m.value.Reader(),
},
}),
}
}
// Marshal returns a statement which represent the code needed to put
// the variable "id" into the io.Writer "writer" while returning an
// error.
func (m *MapType) Marshal(mapID string, writer string) *Statement {
return jen.Func().Params().Params(jen.Error()).Block(
jen.Err().Op(":=").Qual("github.com/lugu/qiloop/type/basic", "WriteUint32").Call(jen.Id("uint32").Call(
jen.Id("len").Call(jen.Id(mapID))),
jen.Id(writer)),
jen.Id(`if (err != nil) {
return fmt.Errorf("write map size: %s", err)
}`),
jen.For(
jen.Id("k, v := range "+mapID),
).Block(
jen.Err().Op("=").Add(m.key.Marshal("k", writer)),
jen.Id(`if (err != nil) {
return fmt.Errorf("write map key: %s", err)
}`),
jen.Err().Op("=").Add(m.value.Marshal("v", writer)),
jen.Id(`if (err != nil) {
return fmt.Errorf("write map value: %s", err)
}`),
),
jen.Return(jen.Nil()),
).Call()
}
// Unmarshal returns a statement which represent the code needed to read
// from a reader "reader" of type io.Reader and returns both the value
// read and an error.
func (m *MapType) Unmarshal(reader string) *Statement {
return jen.Func().Params().Params(
jen.Id("m").Map(m.key.TypeName()).Add(m.value.TypeName()),
jen.Err().Error(),
).Block(
jen.Id("size, err := basic.ReadUint32").Call(jen.Id(reader)),
jen.If(jen.Id("err != nil")).Block(
jen.Return(jen.Id("m"), jen.Qual("fmt", "Errorf").Call(jen.Id(`"read map size: %s", err`)))),
jen.Id("m").Op("=").Id("make").Call(m.TypeName(), jen.Id("size")),
jen.For(
jen.Id("i := 0; i < int(size); i++"),
).Block(
jen.Id("k, err :=").Add(m.key.Unmarshal(reader)),
jen.Id(`if (err != nil) {
return m, fmt.Errorf("read map key (%d/%d): %s", i+1, size, err)
}`),
jen.Id("v, err :=").Add(m.value.Unmarshal(reader)),
jen.Id(`if (err != nil) {
return m, fmt.Errorf("read map value (%d/%d): %s", i+1, size, err)
}`),
jen.Id("m[k] = v"),
),
jen.Return(jen.Id("m"), jen.Nil()),
).Call()
}
// Type returns the Go representation of the type.
func (m *MapType) Type() reflect.Type {
return reflect.MapOf(m.key.Type(), m.value.Type())
}
// NewMemberType is a contructor for the representation of a field in
// a struct.
func NewMemberType(name string, value Type) MemberType {
return MemberType{name, value}
}
// MemberType a field in a struct.
type MemberType struct {
Name string
Type Type
}
// Title is the public name of the field.
func (m MemberType) Title() string {
return CleanName(m.Name)
}
// NewTupleType is a contructor for the representation of a series of
// types. Used to describe a method parameters list.
func NewTupleType(values []Type) *TupleType {
var tuple TupleType
tuple.Members = make([]MemberType, 0)
for i, v := range values {
tuple.Members = append(tuple.Members,
MemberType{fmt.Sprintf("P%d", i), v})
}
return &tuple
}
// TupleType a list of a parameter of a method.
type TupleType struct {
Members []MemberType
}
// Signature returns "(<signature 1><signature 2>...)" where
// <signature X> is the signature of the elements.
func (t *TupleType) Signature() string {
sig := "("
for _, m := range t.Members {
sig += m.Type.Signature()
}
sig += ")"
return sig
}
// ParamIDL returns "name1 signature1, name2 signature2" where
// signatureX is the signature of the elements.
func (t *TupleType) ParamIDL() string {
var sig string
for i, typ := range t.Members {
sig += typ.Name + ": " + typ.Type.SignatureIDL()
if i != len(t.Members)-1 {
sig += ", "
}
}
return sig
}
// SignatureIDL returns "Tuple<signature1,signature2>" where
// signatureX is the signature of the elements.
func (t *TupleType) SignatureIDL() string {
var sig string
for i, typ := range t.Members {
sig += typ.Type.SignatureIDL()
if i != len(t.Members)-1 {
sig += ","
}
}
return fmt.Sprintf("Tuple<%s>", sig)
}
// Params returns a statement representing the list of parameter of
// a method.
func (t *TupleType) Params() *Statement {
arguments := make([]jen.Code, len(t.Members))
for i, m := range t.Members {
arguments[i] = jen.Id(m.Name).Add(m.Type.TypeName())
}
return jen.Params(arguments...)
}
// TypeName returns a statement to be inserted when the type is to be
// declared.
func (t *TupleType) TypeName() *Statement {
params := make([]jen.Code, 0)
for _, typ := range t.Members {
params = append(params, jen.Id(strings.Title(typ.Name)).Add(typ.Type.TypeName()))
}
return jen.Struct(params...)
}
// RegisterTo adds the type to the TypeSet.
func (t *TupleType) RegisterTo(s *TypeSet) {
for _, m := range t.Members {
m.Type.RegisterTo(s)
}
return
}
// TypeDeclaration writes the type declaration into file.
func (t *TupleType) TypeDeclaration(*jen.File) {
return
}
// Marshal returns a statement which represent the code needed to put
// the variable "id" into the io.Writer "writer" while returning an
// error.
func (t *TupleType) Marshal(tupleID string, writer string) *Statement {
statements := make([]jen.Code, 0)
for _, typ := range t.Members {
s1 := jen.Err().Op("=").Add(typ.Type.Marshal(tupleID+"."+strings.Title(typ.Name), writer))
s2 := jen.Id(`if (err != nil) {
return fmt.Errorf("write tuple member: %s", err)
}`)
statements = append(statements, s1)
statements = append(statements, s2)
}
statements = append(statements, jen.Return(jen.Nil()))
return jen.Func().Params().Params(jen.Error()).Block(
statements...,
).Call()
}
// Unmarshal returns a statement which represent the code needed to read
// from a reader "reader" of type io.Reader and returns both the value
// read and an error.
func (t *TupleType) Unmarshal(reader string) *Statement {
statements := make([]jen.Code, 0)
for _, typ := range t.Members {
s1 := jen.List(jen.Id("s."+strings.Title(typ.Name)), jen.Err()).Op("=").Add(typ.Type.Unmarshal(reader))
s2 := jen.Id(`if (err != nil) {
return s, fmt.Errorf("read tuple member: %s", err)
}`)
statements = append(statements, s1)
statements = append(statements, s2)
}
statements = append(statements, jen.Return(jen.Id("s"), jen.Nil()))
return jen.Func().Params().Params(
jen.Id("s").Add(t.TypeName()),
jen.Err().Error(),
).Block(
statements...,
).Call()
}
// Reader returns a map TypeReader.
func (t *TupleType) Reader() TypeReader {
readers := make([]memberReader, len(t.Members))
for i, m := range t.Members {
readers[i] = memberReader{
name: m.Name,
reader: m.Type.Reader(),
}
}
return tupleReader(readers)
}
// Type returns the Go representation of the type.
func (t *TupleType) Type() reflect.Type {
fields := make([]reflect.StructField, len(t.Members))
var offset uintptr = 0
for i, m := range t.Members {
typ := m.Type.Type()
fields[i] = reflect.StructField{
Name: CleanName(m.Name),
PkgPath: typ.PkgPath(),
Type: typ,
Index: []int{i},
Offset: offset,
Anonymous: false,
}
offset += typ.Size()
}
return reflect.StructOf(fields)
}
// ConvertMetaObjects replace any element type which has the same
// signature as MetaObject with an element of the type
// object.MetaObject. This is required to generate proxy services
// which implements the object.Object interface and avoid a circular
// dependency.
func (t *TupleType) ConvertMetaObjects() {
for i, m := range t.Members {
if m.Type.Signature() == MetaObjectSignature {
t.Members[i].Type = NewMetaObjectType()
}
}
}
// NewStructType is a contructor for the representation of a struct.
func NewStructType(name string, members []MemberType) *StructType {
return &StructType{name, members}
}
// StructType represents a struct.
type StructType struct {
Name string
Members []MemberType
}
// Signature returns the signature of the struct.
func (s *StructType) Signature() string {
if len(s.Members) == 0 {
return fmt.Sprintf("()<%s>", s.Name)
}
types := ""
names := make([]string, 0, len(s.Members))
for _, v := range s.Members {
names = append(names, v.Name)
types += v.Type.Signature()
}
return fmt.Sprintf("(%s)<%s,%s>", types,
s.Name, strings.Join(names, ","))
}
func (s *StructType) name() string {
return CleanName(s.Name)
}
// SignatureIDL returns the idl signature of the struct.
func (s *StructType) SignatureIDL() string {
return s.Name
}
// TypeName returns a statement to be inserted when the type is to be
// declared.
func (s *StructType) TypeName() *Statement {
return jen.Id(s.name())
}
// RegisterTo adds the type to the TypeSet.
// Structure name is updated if needed after collision
// resolution. Register search if a type is in the TypeSet under a
// given name. If the same name and signature is already present it
// does nothing. otherwise it adds the type and search for a new which
// does not conflict with the names already present.
func (s *StructType) RegisterTo(set *TypeSet) {
for _, v := range s.Members {
v.Type.RegisterTo(set)
}
s.Name = set.ResolveCollision(s.Name, s.Signature())
if set.Search(s.Name) == nil {
set.Types = append(set.Types, s)
set.Names = append(set.Names, s.Name)
}
}
// TypeDeclaration writes the type declaration into file.
func (s *StructType) TypeDeclaration(file *jen.File) {
fields := make([]jen.Code, len(s.Members))
for i, v := range s.Members {
fields[i] = jen.Id(v.Title()).Add(v.Type.TypeName())
}
file.Commentf("%s is serializable", s.name())
file.Type().Id(s.name()).Struct(fields...)
readFields := make([]jen.Code, len(s.Members)+1)
writeFields := make([]jen.Code, len(s.Members)+1)
for i, v := range s.Members {
readFields[i] = jen.If(
jen.Id("s."+v.Title()+", err =").Add(v.Type.Unmarshal("r")),
jen.Id("err != nil")).Block(
jen.Return(jen.Id("s"),
jen.Qual("fmt", "Errorf").Call(
jen.Lit(`read `+v.Title()+` field: %s`),
jen.Id("err"),
)),
)
writeFields[i] = jen.If(
jen.Id("err :=").Add(v.Type.Marshal("s."+v.Title(), "w")),
jen.Err().Op("!=").Nil(),
).Block(
jen.Return(jen.Qual("fmt", "Errorf").Call(
jen.Lit(`write `+v.Title()+` field: %s`),
jen.Id("err"),
)),
)
}
readFields[len(s.Members)] = jen.Return(jen.Id("s"), jen.Nil())
writeFields[len(s.Members)] = jen.Return(jen.Nil())
file.Commentf("read%s unmarshalls %s", s.name(), s.name())
file.Func().Id("read"+s.name()).Params(
jen.Id("r").Id("io.Reader"),
).Params(
jen.Id("s").Id(s.name()), jen.Err().Error(),
).Block(readFields...)
file.Commentf("write%s marshalls %s", s.name(), s.name())
file.Func().Id("write"+s.name()).Params(
jen.Id("s").Id(s.name()),
jen.Id("w").Qual("io", "Writer"),
).Params(jen.Err().Error()).Block(writeFields...)
}
// Marshal returns a statement which represent the code needed to put
// the variable "id" into the io.Writer "writer" while returning an
// error.
func (s *StructType) Marshal(structID string, writer string) *Statement {
return jen.Id("write"+s.name()).Call(jen.Id(structID), jen.Id(writer))
}
// Unmarshal returns a statement which represent the code needed to read
// from a reader "reader" of type io.Reader and returns both the value
// read and an error.
func (s *StructType) Unmarshal(reader string) *Statement {
return jen.Id("read" + s.name()).Call(jen.Id(reader))