-
Notifications
You must be signed in to change notification settings - Fork 1
/
starlarkproto.go
1566 lines (1406 loc) · 42.8 KB
/
starlarkproto.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
// Copyright 2021 Edward McFarlane. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package starlarkproto provides support for protocol buffers.
package starlarkproto
import (
"fmt"
"sort"
"strings"
"github.com/google/go-cmp/cmp"
"go.starlark.net/starlark"
"go.starlark.net/starlarkstruct"
"go.starlark.net/syntax"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/encoding/prototext"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protodesc"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/reflect/protoregistry"
"google.golang.org/protobuf/testing/protocmp"
"google.golang.org/protobuf/types/dynamicpb"
"github.com/emcfarlane/starlarkproto/internal"
)
// NewModule returns a new proto module.
func NewModule(resolver protodesc.Resolver) *starlarkstruct.Module {
p := NewProto(resolver)
return &starlarkstruct.Module{
Name: "proto",
Members: starlark.StringDict{
"new": internal.MakeBuiltin("proto.new", p.New),
"file": internal.MakeBuiltin("proto.file", p.File),
"marshal": internal.MakeBuiltin("proto.marshal", p.Marshal),
"unmarshal": internal.MakeBuiltin("proto.unmarshal", p.Unmarshal),
"marshal_json": internal.MakeBuiltin("proto.marshal_json", p.MarshalJSON),
"unmarshal_json": internal.MakeBuiltin("proto.unmarshal_json", p.UnmarshalJSON),
"marshal_text": internal.MakeBuiltin("proto.marshal_text", p.MarshalText),
"unmarshal_text": internal.MakeBuiltin("proto.unmarshal_text", p.UnmarshalText),
},
}
}
// Proto is a proto module.
type Proto struct {
resolver protodesc.Resolver
types protoregistry.Types // TODO: wrap resolver to register extensions.
}
func NewProto(resolver protodesc.Resolver) *Proto {
return &Proto{resolver: resolver}
}
// File returns the file descriptor for the given path.
// file(path)
func (p *Proto) File(thread *starlark.Thread, fnname string, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
var name string
if err := starlark.UnpackPositionalArgs(fnname, args, kwargs, 1, &name); err != nil {
return nil, err
}
fileDesc, err := p.resolver.FindFileByPath(name)
if err != nil {
return nil, err
}
return &Descriptor{desc: fileDesc}, nil
}
// New returns a new descriptor.
// new(name)
func (p *Proto) New(thread *starlark.Thread, fnname string, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
var name string
if err := starlark.UnpackPositionalArgs(fnname, args, kwargs, 1, &name); err != nil {
return nil, err
}
fullname := protoreflect.FullName(name)
desc, err := p.resolver.FindDescriptorByName(fullname)
if err != nil {
return nil, err
}
return &Descriptor{desc: desc}, nil
}
// Marshal marshals a message to binary string.
// marhsal(msg, allow_partial=False, deterministic=False, use_cache_size=False)
func (p *Proto) Marshal(thread *starlark.Thread, fnname string, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
var msg *Message
var options proto.MarshalOptions
if err := starlark.UnpackPositionalArgs(
fnname, args, kwargs, 1, &msg,
"allow_partial?", &options.AllowPartial,
"deterministic?", &options.Deterministic,
"use_cache_size?", &options.UseCachedSize,
); err != nil {
return nil, err
}
data, err := options.Marshal(msg)
if err != nil {
return nil, err
}
return starlark.String(string(data)), nil
}
// Unmarshal unmarshals a message from binary string.
// unmarshal(str, msg, merge=False, allow_partial=False, discard_unknown=False)
func (p *Proto) Unmarshal(thread *starlark.Thread, fnname string, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
var str string
var msg *Message
options := proto.UnmarshalOptions{
Resolver: &p.types, // TODO: types...
}
if err := starlark.UnpackPositionalArgs(
fnname, args, kwargs, 2, &str, &msg,
"merge?", &options.Merge,
"allow_partial?", &options.AllowPartial,
"discard_unknown?", &options.DiscardUnknown,
); err != nil {
return nil, err
}
if err := msg.checkMutable(fnname); err != nil {
return nil, err
}
if err := proto.Unmarshal([]byte(str), msg); err != nil {
return nil, err
}
return starlark.None, nil
}
// MarshalJSON marshals a message to json.
// marshal_json(msg, multiline=False, indent=None, allow_partial=False, use_proto_names=False, use_enum_numbers=False, emit_unpopulated=False)
func (p *Proto) MarshalJSON(thread *starlark.Thread, fnname string, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
var msg *Message
var options protojson.MarshalOptions
if err := starlark.UnpackPositionalArgs(
fnname, args, kwargs, 1, &msg,
"multiline?", &options.Multiline,
"indent?", &options.Indent,
"allow_partial?", &options.AllowPartial,
"use_proto_names?", &options.UseProtoNames,
"use_enum_numbers?", &options.UseEnumNumbers,
"emit_unpopulated?", &options.EmitUnpopulated,
); err != nil {
return nil, err
}
data, err := options.Marshal(msg)
if err != nil {
return nil, err
}
return starlark.String(string(data)), nil
}
// UnmarshalJSON unmarshals a json string to a message.
// unmarshal_json(str, msg, allow_partial=False, discard_unknown=False)
func (p *Proto) UnmarshalJSON(thread *starlark.Thread, fnname string, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
var str string
var msg *Message
options := protojson.UnmarshalOptions{
Resolver: &p.types, // TODO: types...
}
if err := starlark.UnpackPositionalArgs(
fnname, args, kwargs, 2, &str, &msg,
"allow_partial?", &options.AllowPartial,
"discard_unknown?", &options.DiscardUnknown,
); err != nil {
return nil, err
}
if err := msg.checkMutable(fnname); err != nil {
return nil, err
}
if err := options.Unmarshal([]byte(str), msg); err != nil {
return nil, err
}
return starlark.None, nil
}
// MarshalText marshals a message to text.
// marshal_text(msg, multiline=False, indent=None, allow_partial=False, emit_unknown=False)
func (p *Proto) MarshalText(thread *starlark.Thread, fnname string, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
var msg *Message
var options prototext.MarshalOptions
if err := starlark.UnpackPositionalArgs(
fnname, args, kwargs, 1, &msg,
"multiline?", &options.Multiline,
"indent?", &options.Indent,
"allow_partial?", &options.AllowPartial,
"emit_unknown?", &options.EmitUnknown,
); err != nil {
return nil, err
}
data, err := options.Marshal(msg)
if err != nil {
return nil, err
}
return starlark.String(string(data)), nil
}
// UnmarshalText unmarshals a text string to a message.
// unmarshal_text(str, msg, allow_partial=False, discard_unknown=False)
func (p *Proto) UnmarshalText(thread *starlark.Thread, fnname string, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
var str string
var msg *Message
options := prototext.UnmarshalOptions{
Resolver: &p.types, // TODO: types...
}
if err := starlark.UnpackPositionalArgs(
fnname, args, kwargs, 2, &str, &msg,
"allow_partial?", &options.AllowPartial,
"discard_unknown?", &options.DiscardUnknown,
); err != nil {
return nil, err
}
if err := msg.checkMutable(fnname); err != nil {
return nil, err
}
if err := options.Unmarshal([]byte(str), msg); err != nil {
return nil, err
}
return starlark.None, nil
}
func equalFullName(a, b protoreflect.FullName) error {
if a != b {
return fmt.Errorf("type mismatch %s != %s", a, b)
}
return nil
}
type Descriptor struct {
desc protoreflect.Descriptor
frozen bool
attrs map[string]protoreflect.Descriptor
}
// NewDescriptor creates a new descriptor.
func NewDescriptor(desc protoreflect.Descriptor) *Descriptor { return &Descriptor{desc: desc} }
// Descriptor exports proto.Descriptor
func (d *Descriptor) Descriptor() protoreflect.Descriptor { return d.desc }
func (d *Descriptor) String() string { return string(d.desc.Name()) }
func (d *Descriptor) Type() string { return "proto.desc" }
func (d *Descriptor) Freeze() { d.frozen = true }
func (d *Descriptor) Truth() starlark.Bool { return d.desc != nil }
func (d *Descriptor) Hash() (uint32, error) { return 0, fmt.Errorf("unhashable type: proto.desc") }
func (d *Descriptor) Name() string { return string(d.desc.Name()) } // TODO
// CallInternal creates a new message or enum from a descriptor.
func (d *Descriptor) CallInternal(thread *starlark.Thread, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
switch v := d.desc.(type) {
case protoreflect.FileDescriptor:
return nil, fmt.Errorf("proto: file descriptor not callable")
case protoreflect.EnumDescriptor:
if len(kwargs) > 0 {
return nil, fmt.Errorf("unexpected kwargs")
}
if len(args) != 1 {
return nil, fmt.Errorf("unexpected number of args")
}
vals := v.Values()
return NewEnum(vals, args[0])
case protoreflect.MessageDescriptor:
// Create the msg, try to use to Go type if avaliable.
var msg protoreflect.Message
if mt, err := protoregistry.GlobalTypes.FindMessageByName(
v.FullName(),
); err == nil {
msg = mt.New()
} else {
// Fallback to dynamic meessages.
msg = dynamicpb.NewMessage(v)
}
return NewMessage(msg, args, kwargs)
default:
return nil, fmt.Errorf("proto: desc missing call type %T", v)
}
}
func (d *Descriptor) getAttrs() map[string]protoreflect.Descriptor {
if d.attrs != nil {
return d.attrs
}
m := make(map[string]protoreflect.Descriptor)
switch v := d.desc.(type) {
case protoreflect.FileDescriptor:
for i, eds := 0, v.Enums(); i < eds.Len(); i++ {
ed := eds.Get(i)
m[string(ed.Name())] = ed
}
for i, mds := 0, v.Messages(); i < mds.Len(); i++ {
md := mds.Get(i)
m[string(md.Name())] = md
}
for i, eds := 0, v.Extensions(); i < eds.Len(); i++ {
ed := eds.Get(i)
m[string(ed.Name())] = ed
}
for i, sds := 0, v.Services(); i < sds.Len(); i++ {
sd := sds.Get(i)
m[string(sd.Name())] = sd
}
case protoreflect.EnumDescriptor:
for i, eds := 0, v.Values(); i < eds.Len(); i++ {
evd := eds.Get(i)
m[string(evd.Name())] = evd
}
case protoreflect.MessageDescriptor:
for i, eds := 0, v.Enums(); i < eds.Len(); i++ {
ed := eds.Get(i)
m[string(ed.Name())] = ed
}
for i, mds := 0, v.Messages(); i < mds.Len(); i++ {
md := mds.Get(i)
m[string(md.Name())] = md
}
for i, ods := 0, v.Oneofs(); i < ods.Len(); i++ {
od := ods.Get(i)
m[string(od.Name())] = od
}
case protoreflect.ServiceDescriptor:
for i, mds := 0, v.Methods(); i < mds.Len(); i++ {
md := mds.Get(i)
m[string(md.Name())] = md
}
default:
panic(fmt.Sprintf("proto: desc missing attr type %T", v))
}
if !d.frozen {
d.attrs = m
}
return m
}
func (d *Descriptor) Attr(name string) (starlark.Value, error) {
// TODO: can this just use the resolver?
attrs := d.getAttrs()
desc, ok := attrs[name]
if !ok {
return nil, nil
}
// Special descriptor type handling
switch v := desc.(type) {
case protoreflect.EnumValueDescriptor:
return Enum{edesc: v}, nil
default:
return &Descriptor{desc: desc}, nil
}
}
func (d *Descriptor) AttrNames() []string {
var names []string
for name := range d.getAttrs() {
names = append(names, name)
}
sort.Strings(names)
return names
}
// Message represents a proto.Message as a starlark.Value.
type Message struct {
msg protoreflect.Message
frozen *bool
}
// ProtoReflect implements proto.Message
func (m *Message) ProtoReflect() protoreflect.Message { return m.msg }
// Type conversions rules:
//
// ═══════════════╤════════════════════════════════════
// Starlark type │ Protobuf Type
// ═══════════════╪════════════════════════════════════
// NoneType │ MessageKind, GroupKind
// Bool │ BoolKind
// Int │ Int32Kind, Sint32Kind, Sfixed32Kind,
// │ Int64Kind, Sint64Kind, Sfixed64Kind,
// │ Uint32Kind, Fixed32Kind,
// │ Uint64Kind, Fixed64Kind
// Float │ FloatKind, DoubleKind
// String │ StringKind, BytesKind
// *List │ List<Kind>
// Tuple │ n/a
// *Dict │ Map<Kind><Kind>
// *Set │ n/a
func toStarlark(v protoreflect.Value, fd protoreflect.FieldDescriptor, frozen *bool) starlark.Value {
switch v := v.Interface().(type) {
case nil:
return starlark.None
case bool:
return starlark.Bool(v)
case int32:
return starlark.MakeInt(int(v))
case int64:
return starlark.MakeInt(int(v))
case uint32:
return starlark.MakeInt(int(v))
case uint64:
return starlark.MakeInt(int(v))
case float32:
return starlark.Float(float64(v))
case float64:
return starlark.Float(v)
case string:
return starlark.String(v)
case []byte:
return starlark.String(v)
case protoreflect.EnumNumber:
evdesc := fd.Enum().Values().ByNumber(v)
if evdesc == nil {
evdesc = fd.DefaultEnumValue() // TODO: error?
}
return Enum{edesc: evdesc}
case protoreflect.List:
return &List{list: v, fd: fd, frozen: frozen}
case protoreflect.Message:
return &Message{msg: v, frozen: frozen}
case protoreflect.Map:
return &Map{m: v, keyfd: fd.MapKey(), valfd: fd.MapValue(), frozen: frozen}
default:
panic(fmt.Sprintf("unhandled proto type %s %T", v, v))
}
}
func allocField(parent protoreflect.Value, fd protoreflect.FieldDescriptor) protoreflect.Value {
switch v := parent.Interface().(type) {
case protoreflect.List:
return v.NewElement()
case protoreflect.Map:
return v.NewValue()
case protoreflect.Message:
return v.NewField(fd)
default:
panic(fmt.Sprintf("unhandled parent value type: %T", v))
}
}
func toProtobuf(v starlark.Value, fd protoreflect.FieldDescriptor, parent protoreflect.Value) (protoreflect.Value, error) {
switch kind := fd.Kind(); kind {
case protoreflect.BoolKind:
if b, ok := v.(starlark.Bool); ok {
return protoreflect.ValueOfBool(bool(b)), nil
}
case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind:
if x, err := starlark.NumberToInt(v); err == nil {
v, err := starlark.AsInt32(x)
if err != nil {
return protoreflect.Value{}, err
}
return protoreflect.ValueOfInt32(int32(v)), nil
}
case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind:
if x, err := starlark.NumberToInt(v); err == nil {
v, _ := x.Int64()
return protoreflect.ValueOfInt64(v), nil
}
case protoreflect.Uint32Kind, protoreflect.Fixed32Kind:
if x, err := starlark.NumberToInt(v); err == nil {
v, _ := x.Uint64()
return protoreflect.ValueOfUint32(uint32(v)), nil
}
case protoreflect.Uint64Kind, protoreflect.Fixed64Kind:
if x, err := starlark.NumberToInt(v); err == nil {
v, _ := x.Uint64()
return protoreflect.ValueOfUint64(v), nil
}
case protoreflect.FloatKind:
if x, ok := starlark.AsFloat(v); ok {
return protoreflect.ValueOfFloat32(float32(x)), nil
}
case protoreflect.DoubleKind:
if x, ok := starlark.AsFloat(v); ok {
return protoreflect.ValueOfFloat64(float64(x)), nil
}
case protoreflect.StringKind:
if x, ok := v.(starlark.String); ok {
return protoreflect.ValueOfString(string(x)), nil
}
case protoreflect.BytesKind:
if x, ok := v.(starlark.String); ok {
return protoreflect.ValueOfBytes([]byte(x)), nil
}
case protoreflect.EnumKind:
switch v := v.(type) {
case starlark.String:
enumVal := fd.Enum().Values().ByName(protoreflect.Name(string(v)))
if enumVal == nil {
return protoreflect.Value{}, fmt.Errorf("proto: enum has no %s value", v)
}
return protoreflect.ValueOfEnum(enumVal.Number()), nil
case starlark.Int, starlark.Float:
i, err := starlark.NumberToInt(v)
if err != nil {
return protoreflect.Value{}, err
}
x, ok := i.Int64()
if !ok {
return protoreflect.Value{}, fmt.Errorf("proto: enum has no %s value", v)
}
return protoreflect.ValueOfEnum(protoreflect.EnumNumber(int32(x))), nil
case Enum:
return protoreflect.ValueOfEnum(v.edesc.Number()), nil
}
case protoreflect.MessageKind:
if fd.IsMap() {
switch v := v.(type) {
case *Map:
return protoreflect.ValueOfMap(v.m), nil
case starlark.IterableMapping:
val := allocField(parent, fd)
mm := val.Map()
kfd := fd.MapKey()
vfd := fd.MapValue()
items := v.Items()
for _, item := range items {
// can only be scalar.
kval, err := toProtobuf(item[0], kfd, val)
if err != nil {
return protoreflect.Value{}, err
}
mkey := kval.MapKey()
mval, err := toProtobuf(item[1], vfd, val)
if err != nil {
return protoreflect.Value{}, err
}
mm.Set(mkey, mval)
}
return val, nil
//return protoreflect.ValueOfMap(mm), nil
}
} else {
switch v := v.(type) {
case *Message:
return protoreflect.ValueOfMessage(v.msg), nil
case *List, *starlark.List:
return protoreflect.Value{}, fmt.Errorf("list can't be assigned to message of type: %q", fd.Message().FullName())
case starlark.NoneType:
msg := parent.Message()
msg.Clear(fd)
return msg.Get(fd), nil // RO
case starlark.IterableMapping:
val := allocField(parent, fd)
m := Message{msg: val.Message(), frozen: new(bool)} // wrap for set
for _, kv := range v.Items() {
key, ok := kv[0].(starlark.String)
if !ok {
return protoreflect.Value{}, fmt.Errorf("proto: invalid key type %s", kv[0].Type())
}
if err := m.SetField(string(key), kv[1]); err != nil {
return protoreflect.Value{}, err
}
}
return val, nil
case starlark.HasAttrs:
val := allocField(parent, fd)
m := Message{msg: val.Message(), frozen: new(bool)} // wrap for set
for _, name := range v.AttrNames() {
val, err := v.Attr(name)
if err != nil {
return protoreflect.Value{}, err
}
if err := m.SetField(name, val); err != nil {
return protoreflect.Value{}, err
}
}
return val, nil
}
}
default:
panic(fmt.Sprintf("unknown kind %q", kind))
}
return protoreflect.Value{}, fmt.Errorf(
"proto: unknown type conversion %s<%T> to %s", v, v, fd.Kind(),
)
}
func (m *Message) encodeField(v starlark.Value, fd protoreflect.FieldDescriptor) (protoreflect.Value, error) {
// It is equivalent to checking whether Cardinality is Repeated and
// that IsMap reports false.
if !fd.IsList() {
return toProtobuf(v, fd, protoreflect.ValueOfMessage(m.msg))
}
switch v := v.(type) {
case *List:
// Starlark type is wrapped in ref by caller.
return protoreflect.ValueOfList(v.list), nil
case starlark.Indexable:
val := m.msg.NewField(fd)
l := val.List()
for i := 0; i < v.Len(); i++ {
val, err := toProtobuf(v.Index(i), fd, val)
if err != nil {
return protoreflect.Value{}, err
}
l.Append(val)
}
return val, nil
case starlark.Iterable:
val := m.msg.NewField(fd)
l := val.List()
iter := v.Iterate()
defer iter.Done()
var p starlark.Value
for iter.Next(&p) {
val, err := toProtobuf(p, fd, val)
if err != nil {
return protoreflect.Value{}, err
}
l.Append(val)
}
return val, nil
}
return protoreflect.Value{}, fmt.Errorf("proto: unknown repeated type conversion %s", v.Type())
}
func (m *Message) checkMutable(verb string) error {
if *m.frozen {
return fmt.Errorf("cannot %s frozen message", verb)
}
if !m.msg.IsValid() {
return fmt.Errorf("cannot %s non mutable message", verb)
}
return nil
}
func MakeMessage(msg proto.Message) *Message {
return &Message{msg: msg.ProtoReflect(), frozen: new(bool)}
}
// NewMessage creates a *Message base on a protobuffer Message with the given
// starlark args and kwargs.
// If both args and kwargs are nil the message is unmodified.
// Args or kwargs are exclusive.
// Only one arg can be set of type *Message, None, IterableMapping or HasAttrs.
func NewMessage(msg protoreflect.Message, args starlark.Tuple, kwargs []starlark.Tuple) (*Message, error) {
hasArgs := len(args) > 0
hasKwargs := len(kwargs) > 0
if hasArgs && len(args) > 1 {
return nil, fmt.Errorf("unexpected number of args")
}
if hasArgs && hasKwargs {
return nil, fmt.Errorf("unxpected args and kwargs")
}
if hasArgs {
switch v := args[0].(type) {
case *Message:
if msg.Type() != v.msg.Type() {
return nil, fmt.Errorf("mismatching type")
}
// shallow copy.
v.msg.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool {
msg.Set(fd, v)
return true
})
return &Message{msg: msg, frozen: new(bool)}, nil
case starlark.NoneType:
return &Message{msg: msg.Type().Zero(), frozen: new(bool)}, nil // RO
case starlark.IterableMapping:
m := &Message{msg: msg, frozen: new(bool)}
for _, kv := range v.Items() {
key, ok := kv[0].(starlark.String)
if !ok {
return nil, fmt.Errorf("proto: invalid key type %s", kv[0].Type())
}
if err := m.SetField(string(key), kv[1]); err != nil {
return nil, err
}
}
return m, nil
case starlark.HasAttrs:
m := &Message{msg: msg, frozen: new(bool)}
for _, name := range v.AttrNames() {
val, err := v.Attr(name)
if err != nil {
return nil, err
}
if err := m.SetField(name, val); err != nil {
return nil, err
}
}
return m, nil
default:
return nil, fmt.Errorf("proto: unknown type conversion %s<%T> to proto.message", v, v)
}
}
m := &Message{msg: msg, frozen: new(bool)}
for _, kwarg := range kwargs {
k := string(kwarg[0].(starlark.String))
v := kwarg[1]
if err := m.SetField(k, v); err != nil {
return nil, err
}
}
return m, nil
}
func (m *Message) String() string {
desc := m.msg.Descriptor()
buf := new(strings.Builder)
buf.WriteString(string(desc.Name()))
buf.WriteByte('(')
if m.msg.IsValid() {
fds := desc.Fields()
for i := 0; i < fds.Len(); i++ {
if i > 0 {
buf.WriteString(", ")
}
fd := fds.Get(i)
buf.WriteString(string(fd.Name()))
buf.WriteString(" = ")
v := m.msg.Get(fd)
s := toStarlark(v, fd, nil).String()
buf.WriteString(s)
}
} else {
buf.WriteString("None")
}
buf.WriteByte(')')
return buf.String()
}
func (m *Message) Type() string { return "proto.message" }
func (m *Message) Truth() starlark.Bool { return starlark.Bool(m.msg.IsValid()) }
func (m *Message) Hash() (uint32, error) {
return 0, fmt.Errorf("unhashable type: proto.message")
}
func (m *Message) Freeze() { *m.frozen = true }
// Attr returns the value of the specified field.
func (m *Message) Attr(name string) (starlark.Value, error) {
fd, err := m.fieldDesc(name)
if err != nil {
return nil, err
}
// Get mutable references if we can.
if fd.IsMap() || fd.IsList() || (fd.Kind() == protoreflect.MessageKind && m.msg.Has(fd)) {
return toStarlark(m.msg.Mutable(fd), fd, m.frozen), nil
}
return toStarlark(m.msg.Get(fd), fd, m.frozen), nil
}
func (x *Message) Binary(op syntax.Token, y starlark.Value, side starlark.Side) (starlark.Value, error) {
return nil, nil // unhandled
}
// AttrNames returns a new sorted list of the message fields.
func (m *Message) AttrNames() []string {
desc := m.msg.Descriptor()
fds := desc.Fields()
ods := desc.Oneofs()
names := make([]string, fds.Len()+ods.Len())
for i := 0; i < fds.Len(); i++ {
fd := fds.Get(i)
names[i] = string(fd.Name())
}
offset := fds.Len()
for i := 0; i < ods.Len(); i++ {
od := ods.Get(i)
names[offset+i] = string(od.Name())
}
sort.Strings(names) // TODO: sort by protobuf number
return names
}
func (m *Message) fieldDesc(name string) (protoreflect.FieldDescriptor, error) {
desc := m.msg.Descriptor()
if fd := desc.Fields().ByName(protoreflect.Name(name)); fd != nil {
return fd, nil
}
if od := desc.Oneofs().ByName(protoreflect.Name(name)); od != nil {
return m.msg.WhichOneof(od), nil
}
return nil, starlark.NoSuchAttrError(
fmt.Sprintf("%s has no .%s attribute", desc.Name(), name),
)
}
func (m *Message) SetField(name string, val starlark.Value) error {
if err := m.checkMutable("set field"); err != nil {
return err
}
fd, err := m.fieldDesc(name)
if err != nil {
return err
}
if val == starlark.None {
m.msg.Clear(fd)
return nil
}
v, err := m.encodeField(val, fd)
if err != nil {
return err
}
m.msg.Set(fd, v)
return nil
}
func (x *Message) CompareSameType(op syntax.Token, y_ starlark.Value, depth int) (bool, error) {
y := y_.(*Message)
switch op {
case syntax.EQL:
return proto.Equal(x, y), nil
case syntax.NEQ:
return !proto.Equal(x, y), nil
case syntax.LE, syntax.LT, syntax.GE, syntax.GT:
return false, fmt.Errorf("%v not implemented", op)
default:
panic(op)
}
}
func (x *Message) DiffSameType(y_ starlark.Value) (string, error) {
y := y_.(*Message)
return cmp.Diff(x.msg.Interface(), y.msg.Interface(), protocmp.Transform()), nil
}
// List represents a repeated field as a starlark.List.
type List struct {
list protoreflect.List
fd protoreflect.FieldDescriptor
frozen *bool
itercount uint32
}
type listAttr func(l *List) starlark.Value
// methods from starlark/library.go
var listAttrs = map[string]listAttr{
"append": func(l *List) starlark.Value { return internal.MakeMethod(l, "append", l.append) },
"clear": func(l *List) starlark.Value { return internal.MakeMethod(l, "clear", l.clear) },
"extend": func(l *List) starlark.Value { return internal.MakeMethod(l, "extend", l.extend) },
"index": func(l *List) starlark.Value { return internal.MakeMethod(l, "index", l.index) },
"insert": func(l *List) starlark.Value { return internal.MakeMethod(l, "insert", l.insert) },
"pop": func(l *List) starlark.Value { return internal.MakeMethod(l, "pop", l.pop) },
"remove": func(l *List) starlark.Value { return internal.MakeMethod(l, "remove", l.remove) },
}
func (l *List) Attr(name string) (starlark.Value, error) {
if a := listAttrs[name]; a != nil {
return a(l), nil
}
return nil, nil
}
func (l *List) AttrNames() []string {
names := make([]string, 0, len(listAttrs))
for name := range listAttrs {
names = append(names, name)
}
sort.Strings(names)
return names
}
func (l *List) String() string {
buf := new(strings.Builder)
buf.WriteByte('[')
if l.list.IsValid() {
for i := 0; i < l.Len(); i++ {
if i > 0 {
buf.WriteString(", ")
}
buf.WriteString(l.Index(i).String())
}
}
buf.WriteByte(']')
return buf.String()
}
func (l *List) Freeze() { *l.frozen = true }
func (l *List) Hash() (uint32, error) {
return 0, fmt.Errorf("unhashable type: proto.list")
}
func (l *List) checkMutable(verb string) error {
if *l.frozen {
return fmt.Errorf("cannot %s frozen list", verb)
}
if l.itercount > 0 {
return fmt.Errorf("cannot %s list during iteration", verb)
}
if !l.list.IsValid() {
return fmt.Errorf("cannot %s non mutable list", verb)
}
return nil
}
func (l *List) Index(i int) starlark.Value {
return toStarlark(l.list.Get(i), l.fd, l.frozen)
}
type listIterator struct {
l *List
i int
}
func (it *listIterator) Next(p *starlark.Value) bool {
if it.i < it.l.Len() {
v := it.l.list.Get(it.i)
*p = toStarlark(v, it.l.fd, it.l.frozen)
it.i++
return true
}
return false
}
func (it *listIterator) Done() {
if !*it.l.frozen {
it.l.itercount--
}
}
func (l *List) Iterate() starlark.Iterator {
if !*l.frozen {
l.itercount++
}
return &listIterator{l: l}
}
// From Hacker's Delight, section 2.8.
func signum(x int64) int { return int(uint64(x>>63) | uint64(-x)>>63) }
// Slice copies values to a starlark.List
func (l *List) Slice(start, end, step int) starlark.Value {
sign := signum(int64(step))
var elems []starlark.Value
for i := start; signum(int64(end-i)) == sign; i += step {
elems = append(elems, l.Index(i))
}
return starlark.NewList(elems)
}
func (l *List) Clear() error {
if err := l.checkMutable("clear"); err != nil {
return err
}
if l.list.Len() > 0 {
l.list.Truncate(0)
}
return nil
}
// Type is a typed list.
func (l *List) Type() string { return "list<" + l.fd.Kind().String() + ">" }
func (l *List) Len() int { return l.list.Len() }
func (l *List) Truth() starlark.Bool { return l.Len() > 0 }
func (l *List) SetIndex(i int, v starlark.Value) error {
if err := l.checkMutable("assign to element of"); err != nil {
return err
}
val, err := toProtobuf(v, l.fd, protoreflect.ValueOfList(l.list))
if err != nil {
return err
}
l.list.Set(i, val)
return nil
}
func (l *List) Append(v starlark.Value) error {
if err := l.checkMutable("append to"); err != nil {
return err
}