-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmain.go
More file actions
executable file
·824 lines (757 loc) · 32.1 KB
/
main.go
File metadata and controls
executable file
·824 lines (757 loc) · 32.1 KB
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
// Copyright 2025 International Digital Economy Academy
//
// Licensed 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.
package main
import (
"flag"
"fmt"
"regexp"
"slices"
"strings"
"golang.org/x/text/cases"
"golang.org/x/text/language"
"google.golang.org/protobuf/compiler/protogen"
"google.golang.org/protobuf/encoding/protowire"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/types/pluginpb"
)
func main() {
var (
flags flag.FlagSet
name = flags.String("name", "protoc_gen", "The project name to use in the generated package")
)
protogen.Options{
ParamFunc: flags.Set,
}.Run(func(gen *protogen.Plugin) error {
gen.SupportedFeatures = uint64(pluginpb.CodeGeneratorResponse_FEATURE_PROTO3_OPTIONAL)
genPackageMod(gen, name)
for _, f := range gen.Files {
if f.Generate {
genPackage(gen, f, name)
}
}
return nil
})
}
func genPackageMod(gen *protogen.Plugin, name *string) *protogen.GeneratedFile {
g := gen.NewGeneratedFile("moon.mod.json", "path")
fmt.Fprintf(g, "{\n")
fmt.Fprintf(g, " \"name\": \"%s\",\n", *name)
fmt.Fprintf(g, " \"version\": \"0.1.0\",\n")
fmt.Fprintf(g, " \"readme\": \"\",\n")
fmt.Fprintf(g, " \"repository\": \"\",\n")
fmt.Fprintf(g, " \"license\": \"\",\n")
fmt.Fprintf(g, " \"keywords\": [],\n")
fmt.Fprintf(g, " \"description\": \"\",\n")
fmt.Fprintf(g, " \"source\": \"src\"\n")
fmt.Fprintf(g, "}\n")
return g
}
func genPackage(gen *protogen.Plugin, file *protogen.File, projectName *string) *protogen.GeneratedFile {
filename := fmt.Sprintf("src/%s/moon.pkg.json", strings.ReplaceAll(string(file.Desc.Package()), ".", "/"))
g := gen.NewGeneratedFile(filename, "path")
fmt.Fprint(g, "{\n")
fmt.Fprint(g, " \"import\": [\n")
fmt.Fprint(g, " \"moonbitlang/protobuf/lib\"")
if file.Desc.Imports().Len() > 0 {
fmt.Fprint(g, ",\n")
}
importList := make([]string, 0, file.Desc.Imports().Len())
for i := 0; i < file.Desc.Imports().Len(); i++ {
importPkg := file.Desc.Imports().Get(i).Package()
importList = append(importList, fmt.Sprintf("\"%s/%s\"", *projectName, strings.ReplaceAll(string(importPkg), ".", "/")))
}
fmt.Fprintf(g, " %s\n", strings.Join(importList, ",\n "))
fmt.Fprintf(g, " ]\n")
fmt.Fprintf(g, "}\n")
genFile(gen, file)
return g
}
func genFile(gen *protogen.Plugin, file *protogen.File) *protogen.GeneratedFile {
filename := fmt.Sprintf("src/%s/top.mbt", strings.ReplaceAll(string(file.Desc.Package()), ".", "/"))
g := gen.NewGeneratedFile(filename, "path")
fmt.Fprintf(g, "// Code generated from %s.proto by protoc-gen-mbt. DO NOT EDIT.\n\n", file.GeneratedFilenamePrefix)
for i := 0; i < file.Desc.Imports().Len(); i++ {
importPkgName := file.Desc.Imports().Get(i).Package().Name()
importMessage := file.Desc.Imports().Get(i).Messages()
for j := 0; j < importMessage.Len(); j++ {
importMessage := importMessage.Get(j)
fmt.Fprintf(g, "typealias @%s.%s as %s\n", importPkgName, importMessage.Name(), importMessage.Name())
}
importEnum := file.Desc.Imports().Get(i).Enums()
for j := 0; j < importEnum.Len(); j++ {
importEnum := importEnum.Get(j)
fmt.Fprintf(g, "typealias @%s.%s as %s\n", importPkgName, importEnum.Name(), importEnum.Name())
}
}
for _, enum := range file.Enums {
genEnum(g, enum)
}
genMessages(g, file.Messages)
return g
}
func genEnum(g *protogen.GeneratedFile, enum *protogen.Enum) {
fmt.Fprintf(g, "pub(all) enum %s {\n", enum.GoIdent.GoName)
for _, value := range enum.Values {
fmt.Fprintf(g, " %s\n", value.GoIdent.GoName)
}
fmt.Fprintf(g, "} derive(Eq, Show)\n")
// To enum
fmt.Fprintf(g, "pub fn %s::to_enum(self : %s) -> @lib.Enum {\n", enum.GoIdent.GoName, enum.GoIdent.GoName)
fmt.Fprintf(g, " match self {\n")
for _, value := range enum.Values {
fmt.Fprintf(g, " %s::%s => %d\n", enum.GoIdent.GoName, value.GoIdent.GoName, value.Desc.Number())
}
fmt.Fprintf(g, " }\n")
fmt.Fprintf(g, "}\n")
// From enum
fmt.Fprintf(g, "pub fn %s::from_enum(i : @lib.Enum) -> %s {\n", enum.GoIdent.GoName, enum.GoIdent.GoName)
fmt.Fprintf(g, " match i._ {\n")
for _, value := range enum.Values {
fmt.Fprintf(g, " %d => %s::%s\n", value.Desc.Number(), enum.GoIdent.GoName, value.GoIdent.GoName)
}
fmt.Fprintf(g, " _ => Default::default()\n")
fmt.Fprintf(g, " }\n")
fmt.Fprintf(g, "}\n")
// Default
fmt.Fprintf(g, "pub impl Default for %s with default() -> %s {\n", enum.GoIdent.GoName, enum.GoIdent.GoName)
fmt.Fprintf(g, " %s::%s\n", enum.GoIdent.GoName, enum.Values[0].GoIdent.GoName)
fmt.Fprintf(g, "}\n")
// Sized
fmt.Fprintf(g, "pub impl @lib.Sized for %s with size_of(self : %s) {\n", enum.GoIdent.GoName, enum.GoIdent.GoName)
fmt.Fprintf(g, " @lib.Sized::size_of(self.to_enum())\n")
fmt.Fprintf(g, "}\n")
// End
}
func genMessages(g *protogen.GeneratedFile, messages []*protogen.Message) {
for _, m := range messages {
// Generate nested enums first
for _, enum := range m.Enums {
genEnum(g, enum)
}
// Recursively process nested messages (if any)
genMessages(g, m.Messages)
// Generate the message itself
genMessage(g, m)
}
}
func PascalToSnake(s string) string {
// Use regex to identify the positions where we need to insert an underscore.
// This regex looks for transitions between a lowercase letter and an uppercase letter.
regex := regexp.MustCompile("([a-z])([A-Z])")
// Insert underscores and convert the string to lowercase.
snake := regex.ReplaceAllString(s, "${1}_${2}")
// Handle MoonBit keywords by appending underscore
moonbitKeywords := []string{
"module", "move", "ref", "static", "super", "unsafe", "use", "where",
"await", "dyn", "abstract", "do", "final", "macro", "override", "typeof",
"virtual", "yield", "local", "method", "alias", "assert", "as", "else",
"extern", "fn", "if", "let", "const", "match", "mut", "type", "typealias",
"struct", "enum", "trait", "traitalias", "derive", "while", "break",
"continue", "import", "return", "throw", "raise", "try", "catch", "pub",
"priv", "readonly", "true", "false", "_", "test", "loop", "for", "in",
"impl", "with", "guard", "async", "is", "init", "main",
}
if slices.Contains(moonbitKeywords, snake) {
return snake + "_"
}
// Convert the entire string to lowercase
return strings.ToLower(snake)
}
func genMessage(g *protogen.GeneratedFile, m *protogen.Message) {
fmt.Fprintf(g, "pub(all) struct %s {\n", m.GoIdent.GoName)
// Regular fields
for _, field := range m.Fields {
if field.Oneof != nil && !field.Oneof.Desc.IsSynthetic() {
// Skip fields that are part of a non-synthetic oneof; they'll be handled separately
continue
}
fieldType := getFieldMbtType(g, field)
fieldName := PascalToSnake(field.Desc.JSONName())
if field.Oneof != nil && field.Oneof.Desc.IsSynthetic() {
fmt.Fprintf(g, " mut %s : %s?\n", fieldName, fieldType)
} else if field.Desc.HasOptionalKeyword() {
fmt.Fprintf(g, " mut %s : %s?\n", fieldName, fieldType)
} else {
fmt.Fprintf(g, " mut %s : %s\n", fieldName, fieldType)
}
}
// Oneof fields
// Fields in oneofs must not have labels (required / optional / repeated).
for _, oneof := range m.Oneofs {
if oneof.Desc.IsSynthetic() {
// Skip synthetic oneofs; they're not part of the user-defined message
continue
}
enumName := oneOfEnumName(m, oneof)
fieldName := PascalToSnake(oneof.GoName)
fmt.Fprintf(g, " mut %s : %s\n", fieldName, enumName)
// Generate the enum for the oneof
// defer to ensure the enum is generated after the struct (not nested)
defer genOneofEnum(g, m, oneof)
}
g.P("} derive(Eq, Show)")
genMessageSize(g, m)
genMessageRead(g, m)
genMessageWrite(g, m)
genMessageDefault(g, m)
}
func genMessageDefault(g *protogen.GeneratedFile, m *protogen.Message) {
fmt.Fprintf(g, "pub impl Default for %s with default() -> %s {\n", m.GoIdent.GoName, m.GoIdent.GoName)
fmt.Fprintf(g, " {\n")
// Initialize all fields to their default values
for _, field := range m.Fields {
fieldName := PascalToSnake(field.Desc.JSONName())
if field.Oneof != nil && field.Oneof.Desc.IsSynthetic() {
fmt.Fprintf(g, " %s: None,\n", fieldName)
} else if field.Desc.HasOptionalKeyword() {
if field.Desc.HasDefault() {
switch field.Desc.Kind() {
case protoreflect.BoolKind:
fmt.Fprintf(g, " %s: Some(%t),\n", fieldName, field.Desc.Default().Bool())
case protoreflect.Int32Kind, protoreflect.Sfixed32Kind, protoreflect.Sint32Kind, protoreflect.Uint32Kind:
fmt.Fprintf(g, " %s: Some(%d),\n", fieldName, field.Desc.Default().Int())
case protoreflect.Int64Kind, protoreflect.Sfixed64Kind, protoreflect.Sint64Kind, protoreflect.Uint64Kind:
fmt.Fprintf(g, " %s: Some(%d),\n", fieldName, field.Desc.Default().Int())
case protoreflect.FloatKind:
fmt.Fprintf(g, " %s: Some(%f),\n", fieldName, field.Desc.Default().Float())
case protoreflect.DoubleKind:
fmt.Fprintf(g, " %s: Some(%f),\n", fieldName, field.Desc.Default().Float())
case protoreflect.StringKind:
fmt.Fprintf(g, " %s: Some(\"%s\"),\n", fieldName, field.Desc.Default().String())
case protoreflect.BytesKind:
fmt.Fprintf(g, " %s: Some(b\"%s\"),\n", fieldName, field.Desc.Default().Bytes())
case protoreflect.EnumKind:
fmt.Fprintf(g, " %s: Some(%s::from_enum(%v)),\n", fieldName, field.Enum.GoIdent.GoName, field.Desc.Default().Enum())
}
} else {
fmt.Fprintf(g, " %s: None,\n", fieldName)
}
} else if field.Desc.IsList() {
fmt.Fprintf(g, " %s: Array::new(),\n", fieldName)
} else {
fmt.Fprintf(g, " %s: Default::default(),\n", fieldName)
}
}
for _, oneof := range m.Oneofs {
if oneof.Desc.IsSynthetic() {
continue
}
enumName := oneOfEnumName(m, oneof)
fieldName := PascalToSnake(oneof.GoName)
fmt.Fprintf(g, " %s: %s::NotSet,\n", fieldName, enumName)
}
fmt.Fprint(g, " }\n")
fmt.Fprint(g, "}\n")
}
func genOneofEnum(g *protogen.GeneratedFile, m *protogen.Message, oneof *protogen.Oneof) {
enumName := oneOfEnumName(m, oneof)
fmt.Fprintf(g, "pub(all) enum %s {\n", enumName)
for _, field := range oneof.Fields {
fieldType := getFieldMbtType(g, field)
fmt.Fprintf(g, " %s(%s)\n", field.GoName, fieldType)
}
fmt.Fprintf(g, " NotSet\n")
fmt.Fprintf(g, "} derive(Eq, Show)\n")
// Default
fmt.Fprintf(g, "pub impl Default for %s with default() -> %s {\n", enumName, enumName)
fmt.Fprintf(g, " NotSet\n")
fmt.Fprintf(g, "}\n")
}
func getFieldMbtType(g *protogen.GeneratedFile, field *protogen.Field) string {
fieldType := getMbtType(field)
// Check if the field is repeated or map
if field.Desc.IsMap() {
keyType := getFieldMbtType(g, field.Message.Fields[0])
valueType := getFieldMbtType(g, field.Message.Fields[1])
fieldType = fmt.Sprintf("Map[%s, %s]", keyType, valueType)
} else if field.Desc.Cardinality() == protoreflect.Repeated {
fieldType = fmt.Sprintf("Array[%s]", fieldType)
}
return fieldType
}
func getMbtType(field *protogen.Field) string {
var fieldType string
switch field.Desc.Kind() {
case protoreflect.BoolKind:
fieldType = "Bool"
case protoreflect.Int32Kind:
fieldType = "Int"
case protoreflect.Int64Kind:
fieldType = "Int64"
case protoreflect.Sfixed32Kind:
fieldType = "Int"
case protoreflect.Sfixed64Kind:
fieldType = "Int64"
case protoreflect.Sint32Kind:
fieldType = "Int"
case protoreflect.Sint64Kind:
fieldType = "Int64"
case protoreflect.Fixed32Kind:
fieldType = "UInt"
case protoreflect.Uint32Kind:
fieldType = "UInt"
case protoreflect.Fixed64Kind:
fieldType = "UInt64"
case protoreflect.Uint64Kind:
fieldType = "UInt64"
case protoreflect.FloatKind:
fieldType = "Float"
case protoreflect.DoubleKind:
fieldType = "Double"
case protoreflect.StringKind:
fieldType = "String"
case protoreflect.BytesKind:
fieldType = "Bytes"
case protoreflect.MessageKind:
fieldType = field.Message.GoIdent.GoName
case protoreflect.EnumKind:
fieldType = field.Enum.GoIdent.GoName
default:
panic("unreachable")
}
return fieldType
}
func genMessageSize(g *protogen.GeneratedFile, m *protogen.Message) {
fmt.Fprintf(g, "pub impl @lib.Sized for %s with size_of(self) {\n", m.GoIdent.GoName)
if len(m.Fields) == 0 {
g.P(" 0")
} else {
g.P(" let mut size = 0U")
for _, field := range m.Fields {
fieldName := PascalToSnake(field.Desc.JSONName())
if field.Oneof != nil {
continue
}
if field.Desc.IsPacked() {
switch field.Desc.Kind() {
case protoreflect.Fixed32Kind, protoreflect.Sfixed32Kind, protoreflect.FloatKind:
fmt.Fprintf(g, " size += %dU + { let size = self.%s.length().reinterpret_as_uint() * %d; @lib.size_of(size) + size}\n", protowire.SizeTag(field.Desc.Number()), fieldName, protowire.SizeFixed32())
case protoreflect.Fixed64Kind, protoreflect.Sfixed64Kind, protoreflect.DoubleKind:
fmt.Fprintf(g, " size += %dU + { let size = self.%s.length().reinterpret_as_uint() * %d; @lib.size_of(size) + size}\n", protowire.SizeTag(field.Desc.Number()), fieldName, protowire.SizeFixed64())
case protoreflect.Int32Kind, protoreflect.Int64Kind, protoreflect.Sint32Kind, protoreflect.Sint64Kind, protoreflect.Uint32Kind, protoreflect.Uint64Kind, protoreflect.BoolKind, protoreflect.EnumKind:
fmt.Fprintf(g, " size += %dU + { let size = self.%s.iter().map(@lib.size_of).fold(init=0U, UInt::op_add); @lib.size_of(size) + size }\n", protowire.SizeTag(field.Desc.Number()), fieldName)
default:
panic(fmt.Sprintf("unreachable: %s can't be packed", field.Desc.Kind()))
}
} else if field.Desc.IsList() {
fmt.Fprintf(g, " size += self.%s.iter().map(@lib.size_of).map(s => %dU + @lib.size_of(s) + s).fold(init=0U, UInt::op_add)\n", fieldName, protowire.SizeTag(field.Desc.Number()))
} else if field.Desc.IsMap() {
fmt.Fprintf(g, " size += self.%s.iter().map(fn(key_value) {\n", fieldName)
g.P(" let (k, v) = key_value")
switch field.Desc.MapKey().Kind() {
case protoreflect.StringKind, protoreflect.BytesKind, protoreflect.MessageKind:
fmt.Fprintf(g, " let key_size = %dU + { let size = @lib.size_of(k); @lib.size_of(size) + size }\n", protowire.SizeTag(0))
case protoreflect.Fixed32Kind, protoreflect.Sfixed32Kind, protoreflect.FloatKind:
fmt.Fprintf(g, " let key_size = %dU + %dU\n", protowire.SizeTag(0), protowire.SizeFixed32())
case protoreflect.Fixed64Kind, protoreflect.Sfixed64Kind, protoreflect.DoubleKind:
fmt.Fprintf(g, " let key_size = %dU + %dU\n", protowire.SizeTag(0), protowire.SizeFixed64())
default:
fmt.Fprintf(g, " let key_size = %dU + @lib.size_of(k)\n", protowire.SizeTag(0))
}
switch field.Desc.MapValue().Kind() {
case protoreflect.StringKind, protoreflect.BytesKind, protoreflect.MessageKind:
fmt.Fprintf(g, " let value_size = %dU + { let size = @lib.size_of(v); @lib.size_of(size) + size }\n", protowire.SizeTag(1))
case protoreflect.Fixed32Kind, protoreflect.Sfixed32Kind, protoreflect.FloatKind:
fmt.Fprintf(g, " let value_size = %dU + %dU\n", protowire.SizeTag(1), protowire.SizeFixed32())
case protoreflect.Fixed64Kind, protoreflect.Sfixed64Kind, protoreflect.DoubleKind:
fmt.Fprintf(g, " let value_size = %dU + %dU\n", protowire.SizeTag(1), protowire.SizeFixed64())
default:
fmt.Fprintf(g, " let value_size = %dU + @lib.size_of(v)\n", protowire.SizeTag(1))
}
fmt.Fprintf(g, " %dU + @lib.size_of(key_size + value_size) + key_size + value_size }).fold(init=0U, UInt::op_add)\n", protowire.SizeTag(field.Desc.Number()))
} else if field.Desc.HasOptionalKeyword() {
fmt.Fprintf(g, " match self.%s {\n", fieldName)
fmt.Fprint(g, " Some(v) =>")
switch field.Desc.Kind() {
case protoreflect.StringKind, protoreflect.BytesKind, protoreflect.MessageKind:
fmt.Fprintf(g, "size += %dU + { let size = @lib.size_of(v); @lib.size_of(size) + size }\n", protowire.SizeTag(field.Desc.Number()))
case protoreflect.Fixed32Kind, protoreflect.Sfixed32Kind, protoreflect.FloatKind:
fmt.Fprintf(g, "size += %dU + %dU\n", protowire.SizeTag(field.Desc.Number()), protowire.SizeFixed32())
case protoreflect.Fixed64Kind, protoreflect.Sfixed64Kind, protoreflect.DoubleKind:
fmt.Fprintf(g, "size += %dU + %dU\n", protowire.SizeTag(field.Desc.Number()), protowire.SizeFixed64())
default:
fmt.Fprintf(g, "size += %dU + @lib.size_of(v)\n", protowire.SizeTag(field.Desc.Number()))
}
if field.Desc.HasOptionalKeyword() {
g.P(" None => ()")
g.P(" }")
}
} else {
switch field.Desc.Kind() {
case protoreflect.StringKind, protoreflect.BytesKind, protoreflect.MessageKind:
fmt.Fprintf(g, " size += %dU + { let size = @lib.size_of(self.%s); @lib.size_of(size) + size }\n", protowire.SizeTag(field.Desc.Number()), fieldName)
case protoreflect.Fixed32Kind, protoreflect.Sfixed32Kind, protoreflect.FloatKind:
fmt.Fprintf(g, " size += %dU + %dU\n", protowire.SizeTag(field.Desc.Number()), protowire.SizeFixed32())
case protoreflect.Fixed64Kind, protoreflect.Sfixed64Kind, protoreflect.DoubleKind:
fmt.Fprintf(g, " size += %dU + %dU\n", protowire.SizeTag(field.Desc.Number()), protowire.SizeFixed64())
default:
fmt.Fprintf(g, " size += %dU + @lib.size_of(self.%s)\n", protowire.SizeTag(field.Desc.Number()), fieldName)
}
}
}
for _, oneof := range m.Oneofs {
var fieldName = PascalToSnake(oneof.GoName)
if oneof.Desc.IsSynthetic() {
fieldName = PascalToSnake(oneof.Fields[0].Desc.JSONName())
}
fmt.Fprintf(g, " match self.%s {\n", fieldName)
for _, field := range oneof.Fields {
if oneof.Desc.IsSynthetic() {
fmt.Fprint(g, " Some(v) => ")
} else {
fmt.Fprintf(g, " %s(v) => ", field.GoName)
}
switch field.Desc.Kind() {
case protoreflect.StringKind, protoreflect.BytesKind, protoreflect.MessageKind:
fmt.Fprintf(g, "size += %dU + { let size = @lib.size_of(v); @lib.size_of(size) + size }\n", protowire.SizeTag(field.Desc.Number()))
case protoreflect.Fixed32Kind, protoreflect.Sfixed32Kind, protoreflect.FloatKind:
fmt.Fprintf(g, "size += %dU + %dU\n", protowire.SizeTag(field.Desc.Number()), protowire.SizeFixed32())
case protoreflect.Fixed64Kind, protoreflect.Sfixed64Kind, protoreflect.DoubleKind:
fmt.Fprintf(g, "size += %dU + %dU\n", protowire.SizeTag(field.Desc.Number()), protowire.SizeFixed64())
default:
fmt.Fprintf(g, "size += %dU + @lib.size_of(v)\n", protowire.SizeTag(field.Desc.Number()))
}
}
if oneof.Desc.IsSynthetic() {
g.P(" None => ()")
} else {
g.P(" NotSet => ()")
}
g.P(" }")
}
g.P(" size")
}
g.P("}")
}
func genMessageRead(g *protogen.GeneratedFile, m *protogen.Message) {
fmt.Fprintf(g, "pub impl @lib.Read for %s with read(reader : &@lib.Reader) {\n", m.GoIdent.GoName)
defaultStr := fmt.Sprintf(" %s::default()", m.GoIdent.GoName)
if len(m.Fields) == 0 {
// Empty message, generate default
g.P(defaultStr)
} else {
g.P(fmt.Sprintf("\tlet msg = %s", defaultStr))
g.P(" while not(reader |> @lib.is_eof()) {")
g.P(" match (reader |> @lib.read_tag()) {")
for _, field := range m.Fields {
if field.Desc.Cardinality() == protoreflect.Repeated {
genRepeatedFieldRead(field, g)
} else {
genFieldRead(field, m, g)
}
}
g.P(" (_, wire) => reader |> @lib.read_unknown(wire)")
g.P(" }")
g.P(" }")
g.P(" msg")
}
g.P("}")
}
func tag(kind protoreflect.Kind, number protowire.Number, isPacked bool) uint64 {
if isPacked {
return protowire.EncodeTag(number, protowire.BytesType)
}
switch kind {
case protoreflect.BoolKind, protoreflect.EnumKind, protoreflect.Int32Kind, protoreflect.Int64Kind,
protoreflect.Sint32Kind, protoreflect.Sint64Kind, protoreflect.Uint32Kind, protoreflect.Uint64Kind:
return protowire.EncodeTag(number, protowire.VarintType)
case protoreflect.Fixed32Kind, protoreflect.Sfixed32Kind, protoreflect.FloatKind:
return protowire.EncodeTag(number, protowire.Fixed32Type)
case protoreflect.Fixed64Kind, protoreflect.Sfixed64Kind, protoreflect.DoubleKind:
return protowire.EncodeTag(number, protowire.Fixed64Type)
case protoreflect.StringKind, protoreflect.BytesKind, protoreflect.MessageKind:
return protowire.EncodeTag(number, protowire.BytesType)
default:
panic("todo: tag deprecated group")
}
}
func kindReadFunc(kind protoreflect.Kind) string {
switch kind {
case protoreflect.BoolKind:
return "@lib.read_bool"
case protoreflect.Int32Kind:
return "@lib.read_int32"
case protoreflect.Int64Kind:
return "@lib.read_int64"
case protoreflect.Sint32Kind:
return "@lib.read_sint32"
case protoreflect.Sint64Kind:
return "@lib.read_sint64"
case protoreflect.Uint32Kind:
return "@lib.read_uint32"
case protoreflect.Uint64Kind:
return "@lib.read_uint64"
case protoreflect.Fixed32Kind:
return "@lib.read_fixed32"
case protoreflect.Fixed64Kind:
return "@lib.read_fixed64"
case protoreflect.Sfixed32Kind:
return "@lib.read_sfixed32"
case protoreflect.Sfixed64Kind:
return "@lib.read_sfixed64"
case protoreflect.FloatKind:
return "@lib.read_float"
case protoreflect.DoubleKind:
return "@lib.read_double"
case protoreflect.StringKind:
return "@lib.read_string"
case protoreflect.BytesKind:
return "@lib.read_bytes"
case protoreflect.EnumKind:
return "@lib.read_enum"
case protoreflect.MessageKind:
return "@lib.Read::read"
case protoreflect.GroupKind:
return "panic()"
default:
panic("unreachable")
}
}
func genKindRead(kind protoreflect.Kind, typeName string) string {
switch kind {
case protoreflect.BoolKind,
protoreflect.Int32Kind,
protoreflect.Int64Kind,
protoreflect.Uint32Kind,
protoreflect.Uint64Kind,
protoreflect.Fixed32Kind,
protoreflect.Fixed64Kind,
protoreflect.Sfixed32Kind,
protoreflect.Sfixed64Kind,
protoreflect.FloatKind,
protoreflect.DoubleKind,
protoreflect.StringKind,
protoreflect.BytesKind:
return fmt.Sprintf("reader |> %s()", kindReadFunc(kind))
case protoreflect.Sint32Kind,
protoreflect.Sint64Kind:
return fmt.Sprintf("(reader |> %s())._", kindReadFunc(kind))
case protoreflect.EnumKind:
return "reader |> @lib.read_enum() |> " + typeName + "::from_enum"
case protoreflect.MessageKind:
return fmt.Sprintf("((reader |> @lib.read_message()) : %s)", typeName)
case protoreflect.GroupKind:
return "panic()"
default:
panic("unreachable")
}
}
func genFieldRead(field *protogen.Field, m *protogen.Message, g *protogen.GeneratedFile) {
kind := field.Desc.Kind()
fieldNumber := field.Desc.Number()
var fieldName = PascalToSnake(field.Desc.JSONName())
var oneOfConstructor = ""
var optionalConstructor = ""
if field.Oneof != nil {
if field.Oneof.Desc.IsSynthetic() {
optionalConstructor = " |> Some"
} else {
fieldName = PascalToSnake(field.Oneof.GoName)
oneOfConstructor = fmt.Sprintf(" |> %s::%s", oneOfEnumName(m, field.Oneof), field.GoName)
}
} else if field.Desc.HasOptionalKeyword() {
optionalConstructor = " |> Some"
}
var name string = ""
if field.Enum != nil {
name = getMbtType(field)
}
if field.Message != nil {
name = getMbtType(field)
}
fmt.Fprintf(g, " (%d, _) => msg.%s = %s%s%s\n", fieldNumber, fieldName, genKindRead(kind, name), oneOfConstructor, optionalConstructor)
}
func genRepeatedFieldRead(field *protogen.Field, g *protogen.GeneratedFile) {
kind := field.Desc.Kind()
fieldNumber := field.Desc.Number()
fieldName := PascalToSnake(field.Desc.JSONName())
var name string = ""
if field.Enum != nil {
name = getMbtType(field)
}
if field.Message != nil {
name = getMbtType(field)
}
if field.Desc.IsPacked() {
switch field.Desc.Kind() {
// VARINT except enum which is not scalar
case protoreflect.BoolKind, protoreflect.Int32Kind, protoreflect.Int64Kind, protoreflect.Uint32Kind, protoreflect.Uint64Kind, protoreflect.Sint32Kind, protoreflect.Sint64Kind:
fmt.Fprintf(g, " (%d, _) => { msg.%s.push_iter((reader |> @lib.read_packed(%s, None)).iter()) }\n", fieldNumber, fieldName, kindReadFunc(kind))
// I64
case protoreflect.Sfixed64Kind, protoreflect.Fixed64Kind, protoreflect.DoubleKind:
fmt.Fprintf(g, " (%d, _) => { msg.%s.push_iter((reader |> @lib.read_packed(%s, Some(64))).iter()) }\n", fieldNumber, fieldName, kindReadFunc(kind))
// I32
case protoreflect.Sfixed32Kind, protoreflect.Fixed32Kind, protoreflect.FloatKind:
fmt.Fprintf(g, " (%d, _) => { msg.%s.push_iter((reader |> @lib.read_packed(%s, Some(32))).iter()) }\n", fieldNumber, fieldName, kindReadFunc(kind))
default:
panic("unreachable")
}
} else if field.Desc.IsMap() {
fmt.Fprintf(g, " (%d, _) => { let {key, value} = %s; msg.%s[key] = value}\n", fieldNumber, genKindRead(kind, name), fieldName)
} else {
fmt.Fprintf(g, " (%d, _) => msg.%s.push(%s)\n", fieldNumber, fieldName, genKindRead(kind, name))
}
}
func genMessageWrite(g *protogen.GeneratedFile, m *protogen.Message) {
fmt.Fprintf(g, "pub impl @lib.Write for %s with write(self, writer) {\n", m.GoIdent.GoName)
if len(m.Fields) != 0 {
for _, field := range m.Fields {
fieldName := PascalToSnake(field.Desc.JSONName())
if field.Oneof != nil {
continue
}
if field.Desc.IsPacked() {
fmt.Fprintf(g, " writer |> @lib.write_varint(%dUL)\n", tag(field.Desc.Kind(), field.Desc.Number(), true))
switch field.Desc.Kind() {
case protoreflect.Fixed32Kind, protoreflect.Sfixed32Kind, protoreflect.FloatKind:
fmt.Fprintf(g, " let size = self.%s.length().reinterpret_as_uint() * %d\n", fieldName, protowire.SizeFixed32())
case protoreflect.Fixed64Kind, protoreflect.Sfixed64Kind, protoreflect.DoubleKind:
fmt.Fprintf(g, " let size = self.%s.length().reinterpret_as_uint() * %d\n", fieldName, protowire.SizeFixed64())
case protoreflect.Int32Kind, protoreflect.Int64Kind, protoreflect.Sint32Kind, protoreflect.Sint64Kind, protoreflect.Uint32Kind, protoreflect.Uint64Kind, protoreflect.BoolKind, protoreflect.EnumKind:
fmt.Fprintf(g, " let size = self.%s.iter().map(@lib.size_of).fold(init=0U, UInt::op_add)\n", fieldName)
default:
panic(fmt.Sprintf("unreachable: %s can't be packed", field.Desc.Kind()))
}
g.P(" writer |> @lib.write_uint32(size)")
fmt.Fprintf(g, " self.%s.iter().each(fn(v) {\n ", fieldName)
genFieldWrite(g, field.Desc.Kind(), "v")
g.P(" })")
} else if field.Desc.IsList() {
fmt.Fprintf(g, " self.%s.iter().each(fn(v) {\n", fieldName)
fmt.Fprintf(g, " writer |> @lib.write_varint(%dUL)\n ", tag(field.Desc.Kind(), field.Desc.Number(), false))
genFieldWrite(g, field.Desc.Kind(), "v")
g.P(" })")
} else if field.Desc.IsMap() {
fmt.Fprintf(g, " self.%s.iter().each(fn(key_value) {\n", fieldName)
g.P(" let (k, v) = key_value")
fmt.Fprintf(g, " writer |> @lib.write_varint(%dUL)\n", tag(field.Desc.Kind(), field.Desc.Number(), false))
switch field.Desc.MapKey().Kind() {
case protoreflect.StringKind, protoreflect.BytesKind, protoreflect.MessageKind:
fmt.Fprintf(g, " let key_size = %dU + { let size = @lib.size_of(k); @lib.size_of(size) + size }\n", protowire.SizeTag(0))
case protoreflect.Fixed32Kind, protoreflect.Sfixed32Kind, protoreflect.FloatKind:
fmt.Fprintf(g, " let key_size = %dU + %dU\n", protowire.SizeTag(0), protowire.SizeFixed32())
case protoreflect.Fixed64Kind, protoreflect.Sfixed64Kind, protoreflect.DoubleKind:
fmt.Fprintf(g, " let key_size = %dU + %dU\n", protowire.SizeTag(0), protowire.SizeFixed64())
default:
fmt.Fprintf(g, " let key_size = %dU + @lib.size_of(k)\n", protowire.SizeTag(0))
}
switch field.Desc.MapValue().Kind() {
case protoreflect.StringKind, protoreflect.BytesKind, protoreflect.MessageKind:
fmt.Fprintf(g, " let value_size = %dU + { let size = @lib.size_of(v); @lib.size_of(size) + size }\n", protowire.SizeTag(1))
case protoreflect.Fixed32Kind, protoreflect.Sfixed32Kind, protoreflect.FloatKind:
fmt.Fprintf(g, " let value_size = %dU + %dU\n", protowire.SizeTag(1), protowire.SizeFixed32())
case protoreflect.Fixed64Kind, protoreflect.Sfixed64Kind, protoreflect.DoubleKind:
fmt.Fprintf(g, " let value_size = %dU + %dU\n", protowire.SizeTag(1), protowire.SizeFixed64())
default:
fmt.Fprintf(g, " let value_size = %dU + @lib.size_of(v)\n", protowire.SizeTag(1))
}
fmt.Fprintf(g, " writer |> @lib.write_uint32(@lib.size_of(key_size + value_size) + key_size + value_size)\n")
mapKey := field.Desc.MapKey()
mapValue := field.Desc.MapValue()
fmt.Fprint(g, " ")
fmt.Fprintf(g, "writer |> @lib.write_varint(%dUL);", tag(mapKey.Kind(), mapKey.Number(), false))
genFieldWrite(g, mapKey.Kind(), "k")
fmt.Fprint(g, " ")
fmt.Fprintf(g, "writer |> @lib.write_varint(%dUL);", tag(mapValue.Kind(), mapValue.Number(), false))
genFieldWrite(g, mapValue.Kind(), "v")
g.P(" })")
} else if field.Desc.HasOptionalKeyword() {
if field.Desc.HasOptionalKeyword() {
fmt.Fprintf(g, " match self.%s {\n", fieldName)
fmt.Fprint(g, " Some(v) => {")
fmt.Fprint(g, " ")
fmt.Fprintf(g, "writer |> @lib.write_varint(%dUL);", tag(field.Desc.Kind(), field.Desc.Number(), false))
genFieldWrite(g, field.Desc.Kind(), "v")
if field.Desc.HasOptionalKeyword() {
g.P(" }")
g.P(" None => ()")
g.P(" }")
}
}
} else {
fmt.Fprint(g, " ")
fmt.Fprintf(g, "writer |> @lib.write_varint(%dUL);", tag(field.Desc.Kind(), field.Desc.Number(), false))
genFieldWrite(g, field.Desc.Kind(), "self."+fieldName)
}
}
for _, oneof := range m.Oneofs {
var fieldName = PascalToSnake(oneof.GoName)
if oneof.Desc.IsSynthetic() {
fieldName = PascalToSnake(oneof.Fields[0].Desc.JSONName())
}
fmt.Fprintf(g, " match self.%s {\n", fieldName)
for _, field := range oneof.Fields {
if oneof.Desc.IsSynthetic() {
g.P(" Some(v) => {")
} else {
fmt.Fprintf(g, " %s(v) => {\n", field.GoName)
}
fmt.Fprint(g, " ")
fmt.Fprintf(g, "writer |> @lib.write_varint(%dUL);", tag(field.Desc.Kind(), field.Desc.Number(), false))
genFieldWrite(g, field.Desc.Kind(), "v")
g.P(" }")
}
if oneof.Desc.IsSynthetic() {
g.P(" None => ()")
} else {
g.P(" NotSet => ()")
}
g.P(" }")
}
}
g.P("}")
}
func genFieldWrite(g *protogen.GeneratedFile, kind protoreflect.Kind, variable string) {
switch kind {
case protoreflect.StringKind:
fmt.Fprintf(g, "writer |> @lib.write_string(%s)\n", variable)
case protoreflect.BytesKind:
fmt.Fprintf(g, "writer |> @lib.write_bytes(%s)\n", variable)
case protoreflect.MessageKind:
fmt.Fprintf(g, "writer |> @lib.write_uint32(@lib.size_of(%s)); @lib.Write::write(%s, writer)\n", variable, variable)
case protoreflect.Fixed32Kind:
fmt.Fprintf(g, "writer |> @lib.write_fixed32(%s)\n", variable)
case protoreflect.Sfixed32Kind:
fmt.Fprintf(g, "writer |> @lib.write_sfixed32(%s)\n", variable)
case protoreflect.FloatKind:
fmt.Fprintf(g, "writer |> @lib.write_float(%s)\n", variable)
case protoreflect.Fixed64Kind:
fmt.Fprintf(g, "writer |> @lib.write_fixed64(%s)\n", variable)
case protoreflect.Sfixed64Kind:
fmt.Fprintf(g, "writer |> @lib.write_sfixed64(%s)\n", variable)
case protoreflect.DoubleKind:
fmt.Fprintf(g, "writer |> @lib.write_double(%s)\n", variable)
case protoreflect.BoolKind:
fmt.Fprintf(g, "writer |> @lib.write_bool(%s)\n", variable)
case protoreflect.Int32Kind:
fmt.Fprintf(g, "writer |> @lib.write_int32(%s)\n", variable)
case protoreflect.Int64Kind:
fmt.Fprintf(g, "writer |> @lib.write_int64(%s)\n", variable)
case protoreflect.Sint32Kind:
fmt.Fprintf(g, "writer |> @lib.write_sint32(%s)\n", variable)
case protoreflect.Sint64Kind:
fmt.Fprintf(g, "writer |> @lib.write_sint64(%s)\n", variable)
case protoreflect.Uint32Kind:
fmt.Fprintf(g, "writer |> @lib.write_uint32(%s)\n", variable)
case protoreflect.Uint64Kind:
fmt.Fprintf(g, "writer |> @lib.write_uint64(%s)\n", variable)
case protoreflect.EnumKind:
fmt.Fprintf(g, "writer |> @lib.write_enum(%s.to_enum())\n", variable)
default:
panic("todo: support deprecated group")
}
}
func oneOfEnumName(m *protogen.Message, oneof *protogen.Oneof) string {
return m.GoIdent.GoName + "_" + cases.Title(language.English).String(oneof.GoName)
}