Debian Codegraph @

lib/proto/proto.go

raw
1 // Copyright 2020 The Bazel Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Package proto defines a module of utilities for constructing and
6 // accessing protocol messages within Starlark programs.
7 //
8 // THIS PACKAGE IS EXPERIMENTAL AND ITS INTERFACE MAY CHANGE.
9 //
10 // This package defines several types of Starlark value:
11 //
12 // Message -- a protocol message
13 // RepeatedField -- a repeated field of a message, like a list
14 // MapField -- a map field of a message, like a dict
15 //
16 // FileDescriptor -- information about a .proto file
17 // FieldDescriptor -- information about a message field (or extension field)
18 // MessageDescriptor -- information about the type of a message
19 // EnumDescriptor -- information about an enumerated type
20 // EnumValueDescriptor -- a value of an enumerated type
21 //
22 // A Message value is a wrapper around a protocol message instance.
23 // Starlark programs may access and update Messages using dot notation:
24 //
25 // x = msg.field
26 // msg.field = x + 1
27 // msg.field += 1
28 //
29 // Assignments to message fields perform dynamic checks on the type and
30 // range of the value to ensure that the message is at all times valid.
31 //
32 // The value of a repeated field of a message is represented by the
33 // list-like data type, RepeatedField. Its elements may be accessed,
34 // iterated, and updated in the usual ways. As with assignments to
35 // message fields, an assignment to an element of a RepeatedField
36 // performs a dynamic check to ensure that the RepeatedField holds
37 // only elements of the correct type.
38 //
39 // type(msg.uint32s) # "proto.repeated<uint32>"
40 // msg.uint32s[0] = 1
41 // msg.uint32s[0] = -1 # error: invalid uint32: -1
42 //
43 // Any iterable may be assigned to a repeated field of a message. If
44 // the iterable is itself a value of type RepeatedField, the message
45 // field holds a reference to it.
46 //
47 // msg2.uint32s = msg.uint32s # both messages share one RepeatedField
48 // msg.uint32s[0] = 123
49 // print(msg2.uint32s[0]) # "123"
50 //
51 // The RepeatedFields' element types must match.
52 // It is not enough for the values to be merely valid:
53 //
54 // msg.uint32s = [1, 2, 3] # makes a copy
55 // msg.uint64s = msg.uint32s # error: repeated field has wrong type
56 // msg.uint64s = list(msg.uint32s) # ok; makes a copy
57 //
58 // For all other iterables, a new RepeatedField is constructed from the
59 // elements of the iterable.
60 //
61 // msg.uints32s = [1, 2, 3]
62 // print(type(msg.uints32s)) # "proto.repeated<uint32>"
63 //
64 // The value of a map field of a message is represented by the dict-like data
65 // type, MapField. Its items can be set and access in the usual ways. As with
66 // assignments to message fields, and assignment to a MapField performs a
67 // dynamic check to ensure the key and value are of the correct type.
68 //
69 // msg.string_map = {"a": "A", "b", "B"}
70 // msg.string_map["c"] = "C"
71 // print(type(msg.string_map)) # "proto.map<string, string>"
72 //
73 // To construct a Message from encoded binary or text data, call
74 // Unmarshal or UnmarshalText. These two functions are exposed to
75 // Starlark programs as proto.unmarshal{,_text}.
76 //
77 // To construct a Message from an existing Go proto.Message instance,
78 // you must first encode the Go message to binary, then decode it using
79 // Unmarshal. This ensures that messages visible to Starlark are
80 // encapsulated and cannot be mutated once their Starlark wrapper values
81 // are frozen.
82 //
83 // TODO(adonovan): document descriptors, enums, message instantiation.
84 package proto
85
86 // TODO(adonovan): Go and Starlark API improvements:
87 // - Make Message and RepeatedField comparable.
88 // (NOTE: proto.Equal works only with generated message types.)
89 // - Support oneof, any. But not messageset if we can avoid it.
90 // - Support "well-known types".
91 // - Defend against cycles in object graph.
92 // - Test missing required fields in marshalling.
93
94 import (
95 "bytes"
96 "fmt"
97 "iter"
98 "sort"
99 "strings"
100 "unsafe"
101 _ "unsafe" // for linkname hack
102
103 "google.golang.org/protobuf/encoding/prototext"
104 "google.golang.org/protobuf/proto"
105 "google.golang.org/protobuf/reflect/protoreflect"
106 "google.golang.org/protobuf/reflect/protoregistry"
107 "google.golang.org/protobuf/types/dynamicpb"
108
109 "go.starlark.net/starlark"
110 "go.starlark.net/starlarkstruct"
111 "go.starlark.net/syntax"
112 )
113
114 // SetPool associates with the specified Starlark thread the
115 // descriptor pool used to find descriptors for .proto files and to
116 // instantiate messages from descriptors. Clients must call SetPool
117 // for a Starlark thread to use this package.
118 //
119 // For example:
120 //
121 // SetPool(thread, protoregistry.GlobalFiles)
122 func SetPool(thread *starlark.Thread, pool DescriptorPool) {
123 thread.SetLocal(contextKey, pool)
124 }
125
126 // Pool returns the descriptor pool previously associated with this thread.
127 func Pool(thread *starlark.Thread) DescriptorPool {
128 pool, _ := thread.Local(contextKey).(DescriptorPool)
129 return pool
130 }
131
132 const contextKey = "proto.DescriptorPool"
133
134 // A DescriptorPool loads FileDescriptors by path name or package name,
135 // possibly on demand.
136 //
137 // It is a superinterface of protodesc.Resolver, so any Resolver
138 // implementation is a valid pool. For example.
139 // protoregistry.GlobalFiles, which loads FileDescriptors from the
140 // compressed binary information in all the *.pb.go files linked into
141 // the process; and protodesc.NewFiles, which holds a set of
142 // FileDescriptorSet messages. See star2proto for example usage.
143 type DescriptorPool interface {
144 FindFileByPath(string) (protoreflect.FileDescriptor, error)
145 }
146
147 var Module = &starlarkstruct.Module{
148 Name: "proto",
149 Members: starlark.StringDict{
150 "file": starlark.NewBuiltin("proto.file", file),
151 "has": starlark.NewBuiltin("proto.has", has),
152 "marshal": starlark.NewBuiltin("proto.marshal", marshal),
153 "marshal_text": starlark.NewBuiltin("proto.marshal_text", marshal),
154 "set_field": starlark.NewBuiltin("proto.set_field", setFieldStarlark),
155 "get_field": starlark.NewBuiltin("proto.get_field", getFieldStarlark),
156 "unmarshal": starlark.NewBuiltin("proto.unmarshal", unmarshal),
157 "unmarshal_text": starlark.NewBuiltin("proto.unmarshal_text", unmarshal_text),
158
159 // TODO(adonovan):
160 // - merge(msg, msg) -> msg
161 // - equals(msg, msg) -> bool
162 // - diff(msg, msg) -> string
163 // - clone(msg) -> msg
164 },
165 }
166
167 // file(filename) loads the FileDescriptor of the given name, or the
168 // first if the pool contains more than one.
169 //
170 // It's unfortunate that renaming a .proto file in effect breaks the
171 // interface it presents to Starlark. Ideally one would import
172 // descriptors by package name, but there may be many FileDescriptors
173 // for the same package name, and there is no "package descriptor".
174 // (Technically a pool may also have many FileDescriptors with the same
175 // file name, but this can't happen with a single consistent snapshot.)
176 func file(thread *starlark.Thread, fn *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
177 var filename string
178 if err := starlark.UnpackPositionalArgs(fn.Name(), args, kwargs, 1, &filename); err != nil {
179 return nil, err
180 }
181
182 pool := Pool(thread)
183 if pool == nil {
184 return nil, fmt.Errorf("internal error: SetPool was not called")
185 }
186
187 desc, err := pool.FindFileByPath(filename)
188 if err != nil {
189 return nil, err
190 }
191
192 return FileDescriptor{Desc: desc}, nil
193 }
194
195 // has(msg, field) reports whether the specified field of the message is present.
196 // A field may be specified by name (string) or FieldDescriptor.
197 // has reports an error if the message type has no such field.
198 func has(thread *starlark.Thread, fn *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
199 var x, field starlark.Value
200 if err := starlark.UnpackPositionalArgs(fn.Name(), args, kwargs, 2, &x, &field); err != nil {
201 return nil, err
202 }
203 msg, ok := x.(*Message)
204 if !ok {
205 return nil, fmt.Errorf("%s: got %s, want proto.Message", fn.Name(), x.Type())
206 }
207
208 var fdesc protoreflect.FieldDescriptor
209 switch field := field.(type) {
210 case starlark.String:
211 var err error
212 fdesc, err = fieldDesc(msg.desc(), string(field))
213 if err != nil {
214 return nil, err
215 }
216
217 case FieldDescriptor:
218 if field.Desc.ContainingMessage() != msg.desc() {
219 return nil, fmt.Errorf("%s: %v does not have field %v", fn.Name(), msg.desc().FullName(), field)
220 }
221 fdesc = field.Desc
222 if fdesc.IsExtension() {
223 // The protoreflect.Message.NewField method must be able
224 // to return a new instance of the field type. Without
225 // having the Go type information available for extensions,
226 // the implementation of NewField won't know what to do.
227 //
228 // Thus we must augment the FieldDescriptor to one that
229 // additional holds Go representation type information
230 // (based in this case on dynamicpb).
231 fdesc = dynamicpb.NewExtensionType(fdesc).TypeDescriptor()
232 }
233
234 default:
235 return nil, fmt.Errorf("%s: for field argument, got %s, want string or proto.FieldDescriptor", fn.Name(), field.Type())
236 }
237
238 return starlark.Bool(msg.msg.Has(fdesc)), nil
239 }
240
241 // marshal{,_text}(msg) encodes a Message value to binary or text form.
242 func marshal(_ *starlark.Thread, fn *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
243 var m *Message
244 if err := starlark.UnpackPositionalArgs(fn.Name(), args, kwargs, 1, &m); err != nil {
245 return nil, err
246 }
247 if fn.Name() == "proto.marshal" {
248 data, err := proto.Marshal(m.Message())
249 if err != nil {
250 return nil, fmt.Errorf("%s: %v", fn.Name(), err)
251 }
252 return starlark.Bytes(data), nil
253 } else {
254 text, err := prototext.MarshalOptions{Indent: " "}.Marshal(m.Message())
255 if err != nil {
256 return nil, fmt.Errorf("%s: %v", fn.Name(), err)
257 }
258 return starlark.String(text), nil
259 }
260 }
261
262 // unmarshal(msg) decodes a binary protocol message to a Message.
263 func unmarshal(thread *starlark.Thread, fn *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
264 var desc MessageDescriptor
265 var data starlark.Bytes
266 if err := starlark.UnpackPositionalArgs(fn.Name(), args, kwargs, 2, &desc, &data); err != nil {
267 return nil, err
268 }
269 return unmarshalData(desc.Desc, []byte(data), true)
270 }
271
272 // unmarshal_text(msg) decodes a text protocol message to a Message.
273 func unmarshal_text(thread *starlark.Thread, fn *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
274 var desc MessageDescriptor
275 var data string
276 if err := starlark.UnpackPositionalArgs(fn.Name(), args, kwargs, 2, &desc, &data); err != nil {
277 return nil, err
278 }
279 return unmarshalData(desc.Desc, []byte(data), false)
280 }
281
282 // set_field(msg, field, value) updates the value of a field.
283 // It is typically used for extensions, which cannot be updated using msg.field = v notation.
284 func setFieldStarlark(thread *starlark.Thread, fn *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
285 // TODO(adonovan): allow field to be specified by name (for non-extension fields), like has?
286 var m *Message
287 var field FieldDescriptor
288 var v starlark.Value
289 if err := starlark.UnpackPositionalArgs(fn.Name(), args, kwargs, 3, &m, &field, &v); err != nil {
290 return nil, err
291 }
292
293 if *m.frozen {
294 return nil, fmt.Errorf("%s: cannot set %v field of frozen %v message", fn.Name(), field, m.desc().FullName())
295 }
296
297 if field.Desc.ContainingMessage() != m.desc() {
298 return nil, fmt.Errorf("%s: %v does not have field %v", fn.Name(), m.desc().FullName(), field)
299 }
300
301 return starlark.None, setField(m.msg, field.Desc, v)
302 }
303
304 // get_field(msg, field) retrieves the value of a field.
305 // It is typically used for extension fields, which cannot be accessed using msg.field notation.
306 func getFieldStarlark(thread *starlark.Thread, fn *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
307 // TODO(adonovan): allow field to be specified by name (for non-extension fields), like has?
308 var msg *Message
309 var field FieldDescriptor
310 if err := starlark.UnpackPositionalArgs(fn.Name(), args, kwargs, 2, &msg, &field); err != nil {
311 return nil, err
312 }
313
314 if field.Desc.ContainingMessage() != msg.desc() {
315 return nil, fmt.Errorf("%s: %v does not have field %v", fn.Name(), msg.desc().FullName(), field)
316 }
317
318 return msg.getField(field.Desc), nil
319 }
320
321 // The Call method implements the starlark.Callable interface.
322 // When a message descriptor is called, it returns a new instance of the
323 // protocol message it describes.
324 //
325 // Message(msg) -- return a shallow copy of an existing message
326 // Message(k=v, ...) -- return a new message with the specified fields
327 // Message(dict(...)) -- return a new message with the specified fields
328 func (d MessageDescriptor) CallInternal(thread *starlark.Thread, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
329 dest := &Message{
330 msg: newMessage(d.Desc),
331 frozen: new(bool),
332 }
333
334 // Single positional argument?
335 if len(args) > 0 {
336 if len(kwargs) > 0 {
337 return nil, fmt.Errorf("%s: got both positional and named arguments", d.Desc.Name())
338 }
339 if len(args) > 1 {
340 return nil, fmt.Errorf("%s: got %d positional arguments, want at most 1", d.Desc.Name(), len(args))
341 }
342
343 // Keep consistent with MessageKind case of toProto.
344 // (support the same argument types).
345 switch src := args[0].(type) {
346 case *Message:
347 if dest.desc() != src.desc() {
348 return nil, fmt.Errorf("%s: got message of type %s, want type %s", d.Desc.Name(), src.desc().FullName(), dest.desc().FullName())
349 }
350
351 // Make shallow copy of message.
352 // TODO(adonovan): How does frozen work if we have shallow copy?
353 src.msg.Range(func(fdesc protoreflect.FieldDescriptor, v protoreflect.Value) bool {
354 dest.msg.Set(fdesc, v)
355 return true
356 })
357 return dest, nil
358
359 case *starlark.Dict:
360 kwargs = src.Items()
361 // fall through
362
363 default:
364 return nil, fmt.Errorf("%s: got %s, want dict or message", d.Desc.Name(), src.Type())
365 }
366 }
367
368 // Convert named arguments to field values.
369 err := setFields(dest.msg, kwargs)
370 return dest, err
371 }
372
373 // setFields updates msg as if by msg.name=value for each (name, value) in items.
374 func setFields(msg protoreflect.Message, items []starlark.Tuple) error {
375 for _, item := range items {
376 name, ok := starlark.AsString(item[0])
377 if !ok {
378 return fmt.Errorf("got %s, want string", item[0].Type())
379 }
380 fdesc, err := fieldDesc(msg.Descriptor(), name)
381 if err != nil {
382 return err
383 }
384 if err := setField(msg, fdesc, item[1]); err != nil {
385 return err
386 }
387 }
388 return nil
389 }
390
391 // setField validates a Starlark field value, converts it to canonical form,
392 // and assigns to the field of msg. If value is None, the field is unset.
393 func setField(msg protoreflect.Message, fdesc protoreflect.FieldDescriptor, value starlark.Value) error {
394 // None unsets a field.
395 if value == starlark.None {
396 msg.Clear(fdesc)
397 return nil
398 }
399
400 // Assigning to a repeated field must make a copy,
401 // because the fields.Set doesn't specify whether
402 // it aliases the list or not, so we cannot assume.
403 //
404 // This is potentially surprising as
405 // x = []; msg.x = x; y = msg.x
406 // causes x and y not to alias.
407 if fdesc.IsList() {
408 iter := starlark.Iterate(value)
409 if iter == nil {
410 return fmt.Errorf("got %s for .%s field, want iterable", value.Type(), fdesc.Name())
411 }
412 defer iter.Done()
413
414 list := msg.Mutable(fdesc).List()
415 list.Truncate(0)
416 var x starlark.Value
417 for i := 0; iter.Next(&x); i++ {
418 v, err := toProto(fdesc, x)
419 if err != nil {
420 return fmt.Errorf("index %d: %v", i, err)
421 }
422 list.Append(v)
423 }
424 return nil
425 }
426
427 if fdesc.IsMap() {
428 mapping, ok := value.(starlark.IterableMapping)
429 if !ok {
430 return fmt.Errorf("in map field %s: expected mappable type, but got %s", fdesc.Name(), value.Type())
431 }
432
433 iter := mapping.Iterate()
434 defer iter.Done()
435
436 // Each value is converted using toProto as usual, passing the key/value
437 // field descriptors to check their types.
438 msg.Clear(fdesc)
439 mutMap := msg.Mutable(fdesc).Map()
440 var k starlark.Value
441 for iter.Next(&k) {
442 kproto, err := toProto(fdesc.MapKey(), k)
443 if err != nil {
444 return fmt.Errorf("in key of map field %s: %w", fdesc.Name(), err)
445 }
446
447 // `found` is discarded, as the presence of the key in the
448 // iterator guarantees the presence of some value (even if it is
449 // starlark.None). Mismatching values will be caught in toProto
450 // below.
451 v, _, err := mapping.Get(k)
452 if err != nil {
453 return fmt.Errorf("in map field %s, at key %s: %w", fdesc.Name(), k.String(), err)
454 }
455
456 vproto, err := toProto(fdesc.MapValue(), v)
457 if err != nil {
458 return fmt.Errorf("in map field %s, at key %s: %w", fdesc.Name(), k.String(), err)
459 }
460
461 mutMap.Set(kproto.MapKey(), vproto)
462 }
463
464 return nil
465 }
466
467 v, err := toProto(fdesc, value)
468 if err != nil {
469 return fmt.Errorf("in field %s: %v", fdesc.Name(), err)
470 }
471
472 if fdesc.IsExtension() {
473 // The protoreflect.Message.NewField method must be able
474 // to return a new instance of the field type. Without
475 // having the Go type information available for extensions,
476 // the implementation of NewField won't know what to do.
477 //
478 // Thus we must augment the FieldDescriptor to one that
479 // additional holds Go representation type information
480 // (based in this case on dynamicpb).
481 fdesc = dynamicpb.NewExtensionType(fdesc).TypeDescriptor()
482 }
483
484 msg.Set(fdesc, v)
485 return nil
486 }
487
488 // toProto converts a Starlark value for a message field into protoreflect form.
489 func toProto(fdesc protoreflect.FieldDescriptor, v starlark.Value) (protoreflect.Value, error) {
490 switch fdesc.Kind() {
491 case protoreflect.BoolKind:
492 // To avoid mistakes, we require v be exactly a bool.
493 if v, ok := v.(starlark.Bool); ok {
494 return protoreflect.ValueOfBool(bool(v)), nil
495 }
496
497 case protoreflect.Fixed32Kind,
498 protoreflect.Uint32Kind:
499 // uint32
500 if i, ok := v.(starlark.Int); ok {
501 if u, ok := i.Uint64(); ok && uint64(uint32(u)) == u {
502 return protoreflect.ValueOfUint32(uint32(u)), nil
503 }
504 return noValue, fmt.Errorf("invalid %s: %v", typeString(fdesc), i)
505 }
506
507 case protoreflect.Int32Kind,
508 protoreflect.Sfixed32Kind,
509 protoreflect.Sint32Kind:
510 // int32
511 if i, ok := v.(starlark.Int); ok {
512 if i, ok := i.Int64(); ok && int64(int32(i)) == i {
513 return protoreflect.ValueOfInt32(int32(i)), nil
514 }
515 return noValue, fmt.Errorf("invalid %s: %v", typeString(fdesc), i)
516 }
517
518 case protoreflect.Uint64Kind,
519 protoreflect.Fixed64Kind:
520 // uint64
521 if i, ok := v.(starlark.Int); ok {
522 if u, ok := i.Uint64(); ok {
523 return protoreflect.ValueOfUint64(u), nil
524 }
525 return noValue, fmt.Errorf("invalid %s: %v", typeString(fdesc), i)
526 }
527
528 case protoreflect.Int64Kind,
529 protoreflect.Sfixed64Kind,
530 protoreflect.Sint64Kind:
531 // int64
532 if i, ok := v.(starlark.Int); ok {
533 if i, ok := i.Int64(); ok {
534 return protoreflect.ValueOfInt64(i), nil
535 }
536 return noValue, fmt.Errorf("invalid %s: %v", typeString(fdesc), i)
537 }
538
539 case protoreflect.StringKind:
540 if s, ok := starlark.AsString(v); ok {
541 return protoreflect.ValueOfString(s), nil
542 } else if b, ok := v.(starlark.Bytes); ok {
543 // TODO(adonovan): allow bytes for string? Not friendly to a Java port.
544 return protoreflect.ValueOfBytes([]byte(b)), nil
545 }
546
547 case protoreflect.BytesKind:
548 if s, ok := starlark.AsString(v); ok {
549 // TODO(adonovan): don't allow string for bytes: it's hostile to a Java port.
550 // Instead provide b"..." literals in the core
551 // and a bytes(str) conversion.
552 return protoreflect.ValueOfBytes([]byte(s)), nil
553 } else if b, ok := v.(starlark.Bytes); ok {
554 return protoreflect.ValueOfBytes([]byte(b)), nil
555 }
556
557 case protoreflect.DoubleKind:
558 switch v := v.(type) {
559 case starlark.Float:
560 return protoreflect.ValueOfFloat64(float64(v)), nil
561 case starlark.Int:
562 return protoreflect.ValueOfFloat64(float64(v.Float())), nil
563 }
564
565 case protoreflect.FloatKind:
566 switch v := v.(type) {
567 case starlark.Float:
568 return protoreflect.ValueOfFloat32(float32(v)), nil
569 case starlark.Int:
570 return protoreflect.ValueOfFloat32(float32(v.Float())), nil
571 }
572
573 case protoreflect.GroupKind,
574 protoreflect.MessageKind:
575 // Keep consistent with MessageDescriptor.CallInternal!
576 desc := fdesc.Message()
577 switch v := v.(type) {
578 case *Message:
579 if desc != v.desc() {
580 return noValue, fmt.Errorf("got %s, want %s", v.desc().FullName(), desc.FullName())
581 }
582 return protoreflect.ValueOfMessage(v.msg), nil // alias it directly
583
584 case *starlark.Dict:
585 dest := newMessage(desc)
586 err := setFields(dest, v.Items())
587 return protoreflect.ValueOfMessage(dest), err
588 }
589
590 case protoreflect.EnumKind:
591 enumval, err := enumValueOf(fdesc.Enum(), v)
592 if err != nil {
593 return noValue, err
594 }
595 return protoreflect.ValueOfEnum(enumval.Number()), nil
596 }
597
598 return noValue, fmt.Errorf("got %s, want %s", v.Type(), typeString(fdesc))
599 }
600
601 var noValue protoreflect.Value
602
603 // toStarlark returns a Starlark value for the value x of a message field.
604 // If the result is a repeated field or message,
605 // the result aliases the original and has the specified "frozenness" flag.
606 //
607 // fdesc is only used for the type, not other properties of the field.
608 func toStarlark(typ protoreflect.FieldDescriptor, x protoreflect.Value, frozen *bool) starlark.Value {
609 if list, ok := x.Interface().(protoreflect.List); ok {
610 return &RepeatedField{
611 typ: typ,
612 list: list,
613 frozen: frozen,
614 }
615 }
616
617 if mp, ok := x.Interface().(protoreflect.Map); ok {
618 return &MapField{
619 typ: typ,
620 mp: mp,
621 frozen: frozen,
622 }
623 }
624
625 return toStarlark1(typ, x, frozen)
626 }
627
628 // toStarlark1, for scalar (non-repeated) values only.
629 func toStarlark1(typ protoreflect.FieldDescriptor, x protoreflect.Value, frozen *bool) starlark.Value {
630
631 switch typ.Kind() {
632 case protoreflect.BoolKind:
633 return starlark.Bool(x.Bool())
634
635 case protoreflect.Fixed32Kind,
636 protoreflect.Uint32Kind,
637 protoreflect.Uint64Kind,
638 protoreflect.Fixed64Kind:
639 return starlark.MakeUint64(x.Uint())
640
641 case protoreflect.Int32Kind,
642 protoreflect.Sfixed32Kind,
643 protoreflect.Sint32Kind,
644 protoreflect.Int64Kind,
645 protoreflect.Sfixed64Kind,
646 protoreflect.Sint64Kind:
647 return starlark.MakeInt64(x.Int())
648
649 case protoreflect.StringKind:
650 return starlark.String(x.String())
651
652 case protoreflect.BytesKind:
653 return starlark.Bytes(x.Bytes())
654
655 case protoreflect.DoubleKind, protoreflect.FloatKind:
656 return starlark.Float(x.Float())
657
658 case protoreflect.GroupKind, protoreflect.MessageKind:
659 return &Message{
660 msg: x.Message(),
661 frozen: frozen,
662 }
663
664 case protoreflect.EnumKind:
665 // Invariant: only EnumValueDescriptor may appear here.
666 enumval := typ.Enum().Values().ByNumber(x.Enum())
667 return EnumValueDescriptor{Desc: enumval}
668 }
669
670 panic(fmt.Sprintf("got %T, want %s", x, typeString(typ)))
671 }
672
673 // A Message is a Starlark value that wraps a protocol message.
674 //
675 // Two Messages are equivalent if and only if they are identical.
676 //
677 // When a Message value becomes frozen, a Starlark program may
678 // not modify the underlying protocol message, nor any Message
679 // or RepeatedField wrapper values derived from it.
680 type Message struct {
681 msg protoreflect.Message // any concrete type is allowed
682 frozen *bool // shared by a group of related Message/RepeatedField/MapField wrappers
683 }
684
685 // Message returns the wrapped message.
686 func (m *Message) Message() protoreflect.ProtoMessage { return m.msg.Interface() }
687
688 func (m *Message) desc() protoreflect.MessageDescriptor { return m.msg.Descriptor() }
689
690 var _ starlark.HasSetField = (*Message)(nil)
691
692 // Unmarshal parses the data as a binary protocol message of the specified type,
693 // and returns it as a new Starlark message value.
694 func Unmarshal(desc protoreflect.MessageDescriptor, data []byte) (*Message, error) {
695 return unmarshalData(desc, data, true)
696 }
697
698 // UnmarshalText parses the data as a text protocol message of the specified type,
699 // and returns it as a new Starlark message value.
700 func UnmarshalText(desc protoreflect.MessageDescriptor, data []byte) (*Message, error) {
701 return unmarshalData(desc, data, false)
702 }
703
704 // unmarshalData constructs a Starlark proto.Message by decoding binary or text data.
705 func unmarshalData(desc protoreflect.MessageDescriptor, data []byte, binary bool) (*Message, error) {
706 m := &Message{
707 msg: newMessage(desc),
708 frozen: new(bool),
709 }
710 var err error
711 if binary {
712 err = proto.Unmarshal(data, m.Message())
713 } else {
714 err = prototext.Unmarshal(data, m.Message())
715 }
716 if err != nil {
717 return nil, fmt.Errorf("unmarshalling %s failed: %v", desc.FullName(), err)
718 }
719 return m, nil
720 }
721
722 func (m *Message) String() string {
723 buf := new(bytes.Buffer)
724 buf.WriteString(string(m.desc().FullName()))
725 buf.WriteByte('(')
726
727 // Sort fields (including extensions) by number.
728 var fields []protoreflect.FieldDescriptor
729 m.msg.Range(func(fdesc protoreflect.FieldDescriptor, v protoreflect.Value) bool {
730 // TODO(adonovan): opt: save v in table too.
731 fields = append(fields, fdesc)
732 return true
733 })
734 sort.Slice(fields, func(i, j int) bool {
735 return fields[i].Number() < fields[j].Number()
736 })
737
738 for i, fdesc := range fields {
739 if i > 0 {
740 buf.WriteString(", ")
741 }
742 if fdesc.IsExtension() {
743 // extension field: "[pkg.Msg.field]"
744 buf.WriteString(string(fdesc.FullName()))
745 } else if fdesc.Kind() != protoreflect.GroupKind {
746 // ordinary field: "field"
747 buf.WriteString(string(fdesc.Name()))
748 } else {
749 // group field: "MyGroup"
750 //
751 // The name of a group is the mangled version,
752 // while the true name of a group is the message itself.
753 // For example, for a group called "MyGroup",
754 // the inlined message will be called "MyGroup",
755 // but the field will be named "mygroup".
756 // This rule complicates name logic everywhere.
757 buf.WriteString(string(fdesc.Message().Name()))
758 }
759 buf.WriteString("=")
760 writeString(buf, fdesc, m.msg.Get(fdesc))
761 }
762 buf.WriteByte(')')
763 return buf.String()
764 }
765
766 func (m *Message) Type() string { return "proto.Message" }
767 func (m *Message) Truth() starlark.Bool { return true }
768 func (m *Message) Freeze() { *m.frozen = true }
769 func (m *Message) Hash() (h uint32, err error) { return uint32(uintptr(unsafe.Pointer(m))), nil } // identity hash
770
771 // Attr returns the value of this message's field of the specified name.
772 // Extension fields are not accessible this way as their names are not unique.
773 func (m *Message) Attr(name string) (starlark.Value, error) {
774 // The name 'descriptor' is already effectively reserved
775 // by the Go API for generated message types.
776 if name == "descriptor" {
777 return MessageDescriptor{Desc: m.desc()}, nil
778 }
779
780 fdesc, err := fieldDesc(m.desc(), name)
781 if err != nil {
782 return nil, err
783 }
784 return m.getField(fdesc), nil
785 }
786
787 func (m *Message) getField(fdesc protoreflect.FieldDescriptor) starlark.Value {
788 if fdesc.IsExtension() {
789 // See explanation in setField.
790 fdesc = dynamicpb.NewExtensionType(fdesc).TypeDescriptor()
791 }
792
793 if m.msg.Has(fdesc) {
794 return toStarlark(fdesc, m.msg.Get(fdesc), m.frozen)
795 }
796 return defaultValue(fdesc)
797 }
798
799 //go:linkname detrandDisable google.golang.org/protobuf/internal/detrand.Disable
800 func detrandDisable()
801
802 func init() {
803 // Nasty hack to disable the randomization of output that occurs in textproto.
804 // TODO(adonovan): once go/proto-proposals/canonical-serialization
805 // is resolved the need for the hack should go away. See also go/go-proto-stability.
806 // If the proposal is rejected, we will need our own text-mode formatter.
807 detrandDisable()
808 }
809
810 // defaultValue returns the (frozen) default Starlark value for a given message field.
811 func defaultValue(fdesc protoreflect.FieldDescriptor) starlark.Value {
812 frozen := true
813
814 // The default value of a repeated field is an empty list.
815 if fdesc.IsList() {
816 return &RepeatedField{typ: fdesc, list: emptyList{}, frozen: &frozen}
817 }
818
819 // The default value of a map field is an empty map.
820 if fdesc.IsMap() {
821 return &MapField{typ: fdesc, mp: emptyMap{}, frozen: &frozen}
822 }
823
824 // The zero value for a message type is an empty instance of that message.
825 if desc := fdesc.Message(); desc != nil {
826 return &Message{msg: newMessage(desc), frozen: &frozen}
827 }
828
829 // Convert the default value, which is not necessarily zero, to Starlark.
830 // The frozenness isn't used as the remaining types are all immutable.
831 return toStarlark1(fdesc, fdesc.Default(), &frozen)
832 }
833
834 // A frozen empty implementation of protoreflect.List.
835 type emptyList struct{ protoreflect.List }
836
837 func (emptyList) Len() int { return 0 }
838
839 type emptyMap struct{ protoreflect.Map }
840
841 func (emptyMap) Len() int { return 0 }
842
843 func (emptyMap) Get(_ protoreflect.MapKey) protoreflect.Value {
844 // An invalid value, signalling the supplied key does not exist.
845 return protoreflect.Value{}
846 }
847
848 func (emptyMap) Range(_ func(protoreflect.MapKey, protoreflect.Value) bool) {}
849
850 // newMessage returns a new empty instance of the message type described by desc.
851 func newMessage(desc protoreflect.MessageDescriptor) protoreflect.Message {
852 // If desc refers to a built-in message,
853 // use the more efficient generated type descriptor (a Go struct).
854 mt, err := protoregistry.GlobalTypes.FindMessageByName(desc.FullName())
855 if err == nil && mt.Descriptor() == desc {
856 return mt.New()
857 }
858
859 // For all others, use the generic dynamicpb representation.
860 return dynamicpb.NewMessage(desc).ProtoReflect()
861 }
862
863 // fieldDesc returns the descriptor for the named non-extension field.
864 func fieldDesc(desc protoreflect.MessageDescriptor, name string) (protoreflect.FieldDescriptor, error) {
865 if fdesc := desc.Fields().ByName(protoreflect.Name(name)); fdesc != nil {
866 return fdesc, nil
867 }
868 return nil, starlark.NoSuchAttrError(fmt.Sprintf("%s has no .%s field", desc.FullName(), name))
869 }
870
871 // SetField updates a non-extension field of this message.
872 // It implements the HasSetField interface.
873 func (m *Message) SetField(name string, v starlark.Value) error {
874 fdesc, err := fieldDesc(m.desc(), name)
875 if err != nil {
876 return err
877 }
878 if *m.frozen {
879 return fmt.Errorf("cannot set .%s field of frozen %s message",
880 name, m.desc().FullName())
881 }
882 return setField(m.msg, fdesc, v)
883 }
884
885 // AttrNames returns the set of field names defined for this message.
886 // It satisfies the starlark.HasAttrs interface.
887 func (m *Message) AttrNames() []string {
888 seen := make(map[string]bool)
889
890 // standard fields
891 seen["descriptor"] = true
892
893 // non-extension fields
894 fields := m.desc().Fields()
895 for i := 0; i < fields.Len(); i++ {
896 fdesc := fields.Get(i)
897 if !fdesc.IsExtension() {
898 seen[string(fdesc.Name())] = true
899 }
900 }
901
902 names := make([]string, 0, len(seen))
903 for name := range seen {
904 names = append(names, name)
905 }
906 sort.Strings(names)
907 return names
908 }
909
910 // typeString returns a user-friendly description of the type of a
911 // protocol message field (or element of a repeated field).
912 func typeString(fdesc protoreflect.FieldDescriptor) string {
913 switch fdesc.Kind() {
914 case protoreflect.GroupKind,
915 protoreflect.MessageKind:
916 return string(fdesc.Message().FullName())
917
918 case protoreflect.EnumKind:
919 return string(fdesc.Enum().FullName())
920
921 default:
922 return strings.ToLower(strings.TrimPrefix(fdesc.Kind().String(), "TYPE_"))
923 }
924 }
925
926 // A RepeatedField is a Starlark value that wraps a repeated field of a protocol message.
927 //
928 // An assignment to an element of a repeated field incurs a dynamic
929 // check that the new value has (or can be converted to) the correct
930 // type using conversions similar to those done when calling a
931 // MessageDescriptor to construct a message.
932 //
933 // TODO(adonovan): make RepeatedField implement starlark.Comparable.
934 // Should the comparison include type, or be defined on the elements alone?
935 type RepeatedField struct {
936 typ protoreflect.FieldDescriptor // only for type information, not field name
937 list protoreflect.List
938 frozen *bool
939 itercount int
940 }
941
942 var (
943 _ starlark.Iterable = (*RepeatedField)(nil)
944 _ starlark.HasSetIndex = (*RepeatedField)(nil)
945 _ starlark.HasAttrs = (*RepeatedField)(nil)
946 )
947
948 func (rf *RepeatedField) AttrNames() []string {
949 return []string{"append"}
950 }
951
952 func (rf *RepeatedField) Attr(name string) (starlark.Value, error) {
953 switch name {
954 case "append":
955 return starlark.NewBuiltin("append", repeatedFieldAppend).BindReceiver(rf), nil
956 default:
957 return nil, nil
958 }
959 }
960
961 func repeatedFieldAppend(_ *starlark.Thread, b *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
962 var object starlark.Value
963 if err := starlark.UnpackPositionalArgs(b.Name(), args, kwargs, 1, &object); err != nil {
964 return nil, err
965 }
966 rf := b.Receiver().(*RepeatedField)
967
968 if err := rf.checkMutable("append to"); err != nil {
969 return nil, err
970 }
971
972 po, err := toProto(rf.typ, object)
973 if err != nil {
974 return nil, fmt.Errorf("appending to repeated field: %v", err)
975 }
976 rf.list.Append(po)
977
978 return starlark.None, nil
979 }
980
981 func (rf *RepeatedField) Type() string {
982 return fmt.Sprintf("proto.repeated<%s>", typeString(rf.typ))
983 }
984
985 func (rf *RepeatedField) SetIndex(i int, v starlark.Value) error {
986 if err := rf.checkMutable("insert into"); err != nil {
987 return err
988 }
989 x, err := toProto(rf.typ, v)
990 if err != nil {
991 // The repeated field value cannot know which field it
992 // belongs to---it might be shared by several of the
993 // same type---so the error message is suboptimal.
994 return fmt.Errorf("setting element of repeated field: %v", err)
995 }
996 rf.list.Set(i, x)
997 return nil
998 }
999
1000 // checkMutable reports an error if the repeated field should not be mutated.
1001 // verb+" repeated field" should describe the operation.
1002 func (rf *RepeatedField) checkMutable(verb string) error {
1003 if *rf.frozen {
1004 return fmt.Errorf("cannot %s frozen repeated field", verb)
1005 }
1006 if rf.itercount > 0 {
1007 return fmt.Errorf("cannot %s repeated field during iteration", verb)
1008 }
1009 return nil
1010 }
1011
1012 func (rf *RepeatedField) Freeze() { *rf.frozen = true }
1013 func (rf *RepeatedField) Hash() (uint32, error) { return 0, fmt.Errorf("unhashable: %s", rf.Type()) }
1014 func (rf *RepeatedField) Index(i int) starlark.Value {
1015 return toStarlark1(rf.typ, rf.list.Get(i), rf.frozen)
1016 }
1017 func (rf *RepeatedField) Iterate() starlark.Iterator {
1018 if !*rf.frozen {
1019 rf.itercount++
1020 }
1021 return &repeatedFieldIterator{rf, 0}
1022 }
1023
1024 // Elements returns an iterator over the sequence of elements of a repeated field.
1025 // For example:
1026 //
1027 // for val := range repeatedField.Elements() { ... }
1028 func (rf *RepeatedField) Elements() iter.Seq[starlark.Value] {
1029 return func(yield func(starlark.Value) bool) {
1030 for i := range rf.list.Len() {
1031 if !yield(rf.Index(i)) {
1032 return
1033 }
1034 }
1035 }
1036 }
1037 func (rf *RepeatedField) Len() int { return rf.list.Len() }
1038 func (rf *RepeatedField) String() string {
1039 // We use list [...] notation even though it not exactly a list.
1040 buf := new(bytes.Buffer)
1041 buf.WriteByte('[')
1042 for i := 0; i < rf.list.Len(); i++ {
1043 if i > 0 {
1044 buf.WriteString(", ")
1045 }
1046 writeString(buf, rf.typ, rf.list.Get(i))
1047 }
1048 buf.WriteByte(']')
1049 return buf.String()
1050 }
1051 func (rf *RepeatedField) Truth() starlark.Bool { return rf.list.Len() > 0 }
1052
1053 type repeatedFieldIterator struct {
1054 rf *RepeatedField
1055 i int
1056 }
1057
1058 func (it *repeatedFieldIterator) Next(p *starlark.Value) bool {
1059 if it.i < it.rf.Len() {
1060 *p = it.rf.Index(it.i)
1061 it.i++
1062 return true
1063 }
1064 return false
1065 }
1066
1067 func (it *repeatedFieldIterator) Done() {
1068 if !*it.rf.frozen {
1069 it.rf.itercount--
1070 }
1071 }
1072
1073 // MapField represents a protocol message field of type 'map'.
1074 //
1075 // Assigning value in the map incurs a dynamic check that the new value has (or
1076 // can be converted to) the correct type using conversions similar to those done
1077 // when calling a MessageDescriptor to construct a message.
1078 type MapField struct {
1079 typ protoreflect.FieldDescriptor
1080
1081 mp protoreflect.Map
1082 frozen *bool
1083 itercount int
1084 }
1085
1086 var (
1087 _ starlark.HasSetKey = (*MapField)(nil)
1088 _ starlark.IterableMapping = (*MapField)(nil)
1089 )
1090
1091 func (mf *MapField) Type() string {
1092 return fmt.Sprintf("proto.map<%s, %s>", typeString(mf.typ.MapKey()), typeString(mf.typ.MapValue()))
1093 }
1094
1095 func (mf *MapField) checkKeyType() error {
1096 switch mf.typ.MapKey().Kind() {
1097 case protoreflect.BoolKind, protoreflect.StringKind,
1098 protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Uint32Kind,
1099 protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Uint64Kind,
1100 protoreflect.Fixed32Kind, protoreflect.Sfixed32Kind,
1101 protoreflect.Fixed64Kind, protoreflect.Sfixed64Kind:
1102 return nil
1103 default:
1104 return fmt.Errorf("map key is %s, want string, int, or bool", mf.typ.MapKey().Kind())
1105 }
1106 }
1107
1108 func (mf *MapField) SetKey(k, v starlark.Value) error {
1109 if err := mf.checkKeyType(); err != nil {
1110 return err
1111 }
1112 if err := mf.checkMutable("insert into"); err != nil {
1113 return err
1114 }
1115
1116 kx, err := toProto(mf.typ.MapKey(), k)
1117 if err != nil {
1118 return fmt.Errorf("converting map key: %v", err)
1119 }
1120 vx, err := toProto(mf.typ.MapValue(), v)
1121 if err != nil {
1122 return fmt.Errorf("converting map value: %v", err)
1123 }
1124
1125 mf.mp.Set(kx.MapKey(), vx)
1126 return nil
1127 }
1128
1129 // checkMutable reports an error if the map field should not be mutated.
1130 // verb+" map field" should describe the operation.
1131 func (mf *MapField) checkMutable(verb string) error {
1132 if *mf.frozen {
1133 return fmt.Errorf("cannot %s frozen map field", verb)
1134 }
1135 if mf.itercount > 0 {
1136 return fmt.Errorf("cannot %s map field during iteration", verb)
1137 }
1138 return nil
1139 }
1140
1141 func (mf *MapField) Get(k starlark.Value) (starlark.Value, bool, error) {
1142 if err := mf.checkKeyType(); err != nil {
1143 return nil, false, err
1144 }
1145 pk, err := toProto(mf.typ.MapKey(), k)
1146 if err != nil {
1147 return nil, false, fmt.Errorf("converting map key: %v", err)
1148 }
1149
1150 v := mf.mp.Get(pk.MapKey())
1151 if !v.IsValid() {
1152 return nil, false, nil
1153 }
1154
1155 return toStarlark1(mf.typ.MapValue(), v, mf.frozen), true, nil
1156 }
1157
1158 func (mf *MapField) Freeze() { *mf.frozen = true }
1159 func (mf *MapField) Hash() (uint32, error) { return 0, fmt.Errorf("unhashable: %s", mf.Type()) }
1160
1161 func (mf *MapField) Iterate() starlark.Iterator {
1162 if !*mf.frozen {
1163 mf.itercount++
1164 }
1165
1166 it := &mapFieldIterator{mf: mf, keys: make([]starlark.Value, 0, mf.mp.Len())}
1167 mf.mp.Range(func(mk protoreflect.MapKey, v protoreflect.Value) bool {
1168 it.keys = append(it.keys, toStarlark1(mf.typ.MapKey(), mk.Value(), mf.frozen))
1169 return true
1170 })
1171 // Ensure we iterate in sorted order.
1172 sort.Slice(it.keys, func(i, j int) bool {
1173 less, _ := starlark.Compare(syntax.LT, it.keys[i], it.keys[j])
1174 return less
1175 })
1176 return it
1177 }
1178
1179 // Entries returns an iterator over the sequence of entries of a map field. For
1180 // example:
1181 //
1182 // for k, v := range mapField.Entries() { ... }
1183 func (mf *MapField) Entries() iter.Seq2[starlark.Value, starlark.Value] {
1184 return func(yield func(k, v starlark.Value) bool) {
1185 mf.mp.Range(func(mk protoreflect.MapKey, v protoreflect.Value) bool {
1186 return yield(
1187 toStarlark1(mf.typ.MapKey(), mk.Value(), mf.frozen),
1188 toStarlark1(mf.typ.MapValue(), v, mf.frozen),
1189 )
1190 })
1191 }
1192 }
1193
1194 // Items returns a slice of key-value pairs, sorted in key order.
1195 func (mf *MapField) Items() []starlark.Tuple {
1196 out := make([]starlark.Tuple, 0, mf.mp.Len())
1197 array := make([]starlark.Value, 2*mf.mp.Len()) // allocate a single backing array
1198
1199 mf.mp.Range(func(mk protoreflect.MapKey, v protoreflect.Value) bool {
1200 pair := array[:2:2]
1201 array = array[2:]
1202 pair[0] = toStarlark1(mf.typ.MapKey(), mk.Value(), mf.frozen)
1203 pair[1] = toStarlark1(mf.typ.MapValue(), v, mf.frozen)
1204 out = append(out, pair)
1205 return true // Keep iterating.
1206 })
1207
1208 // A map key can be any scalar protobuf type except floats and bytes.
1209 // In practice in starlark they should be Int, String, or Bool and thus
1210 // either TotallyOrdered or Comparable. None of these return errors when
1211 // compared to the same type.
1212 //
1213 // Other key types are rejected, but only when an individual entry is
1214 // accessed (as this is the only place with error reporting).
1215 sort.Slice(out, func(i, j int) bool {
1216 less, _ := starlark.Compare(syntax.LT, out[i][0], out[j][0])
1217 return less
1218 })
1219
1220 return out
1221 }
1222
1223 func (mf *MapField) Len() int { return mf.mp.Len() }
1224
1225 func (mf *MapField) String() string {
1226 // We want to use {k1: v1, k2: v2} notation, like a dict.
1227 buf := new(strings.Builder)
1228 buf.WriteByte('{')
1229
1230 for i, kv := range mf.Items() {
1231 if i > 0 {
1232 buf.WriteString(", ")
1233 }
1234 buf.WriteString(kv[0].String())
1235 buf.WriteString(": ")
1236 buf.WriteString(kv[1].String())
1237 }
1238
1239 buf.WriteByte('}')
1240 return buf.String()
1241 }
1242
1243 func (rf *MapField) Truth() starlark.Bool { return rf.mp.Len() > 0 }
1244
1245 type mapFieldIterator struct {
1246 mf *MapField
1247
1248 keys []starlark.Value
1249 i int
1250 }
1251
1252 func (it *mapFieldIterator) Next(p *starlark.Value) bool {
1253 if it.i < len(it.keys) {
1254 *p = it.keys[it.i]
1255 it.i++
1256 return true
1257 }
1258 return false
1259 }
1260
1261 func (it *mapFieldIterator) Done() {
1262 if !*it.mf.frozen {
1263 it.mf.itercount--
1264 }
1265 }
1266
1267 func writeString(buf *bytes.Buffer, fdesc protoreflect.FieldDescriptor, v protoreflect.Value) {
1268 // TODO(adonovan): opt: don't materialize the Starlark value.
1269 // TODO(adonovan): skip message type when printing submessages? {...}?
1270 var frozen bool // ignored
1271 x := toStarlark(fdesc, v, &frozen)
1272 buf.WriteString(x.String())
1273 }
1274
1275 // -------- descriptor values --------
1276
1277 // A FileDescriptor is an immutable Starlark value that describes a
1278 // .proto file. It is a reference to a protoreflect.FileDescriptor.
1279 // Two FileDescriptor values compare equal if and only if they refer to
1280 // the same protoreflect.FileDescriptor.
1281 //
1282 // Its fields are the names of the message types (MessageDescriptor) and enum
1283 // types (EnumDescriptor).
1284 type FileDescriptor struct {
1285 Desc protoreflect.FileDescriptor // TODO(adonovan): hide field, expose method?
1286 }
1287
1288 var _ starlark.HasAttrs = FileDescriptor{}
1289
1290 func (f FileDescriptor) String() string { return string(f.Desc.Path()) }
1291 func (f FileDescriptor) Type() string { return "proto.FileDescriptor" }
1292 func (f FileDescriptor) Truth() starlark.Bool { return true }
1293 func (f FileDescriptor) Freeze() {} // immutable
1294 func (f FileDescriptor) Hash() (h uint32, err error) { return starlark.String(f.Desc.Path()).Hash() }
1295 func (f FileDescriptor) Attr(name string) (starlark.Value, error) {
1296 if desc := f.Desc.Messages().ByName(protoreflect.Name(name)); desc != nil {
1297 return MessageDescriptor{Desc: desc}, nil
1298 }
1299 if desc := f.Desc.Extensions().ByName(protoreflect.Name(name)); desc != nil {
1300 return FieldDescriptor{desc}, nil
1301 }
1302 if enum := f.Desc.Enums().ByName(protoreflect.Name(name)); enum != nil {
1303 return EnumDescriptor{Desc: enum}, nil
1304 }
1305 return nil, nil
1306 }
1307 func (f FileDescriptor) AttrNames() []string {
1308 var names []string
1309 messages := f.Desc.Messages()
1310 for i, n := 0, messages.Len(); i < n; i++ {
1311 names = append(names, string(messages.Get(i).Name()))
1312 }
1313 extensions := f.Desc.Extensions()
1314 for i, n := 0, extensions.Len(); i < n; i++ {
1315 names = append(names, string(extensions.Get(i).Name()))
1316 }
1317 enums := f.Desc.Enums()
1318 for i, n := 0, enums.Len(); i < n; i++ {
1319 names = append(names, string(enums.Get(i).Name()))
1320 }
1321 sort.Strings(names)
1322 return names
1323 }
1324
1325 // A MessageDescriptor is an immutable Starlark value that describes a protocol
1326 // message type.
1327 //
1328 // A MessageDescriptor value contains a reference to a protoreflect.MessageDescriptor.
1329 // Two MessageDescriptor values compare equal if and only if they refer to the
1330 // same protoreflect.MessageDescriptor.
1331 //
1332 // The fields of a MessageDescriptor value are the names of any message types
1333 // (MessageDescriptor), fields or extension fields (FieldDescriptor),
1334 // and enum types (EnumDescriptor) nested within the declaration of this message type.
1335 type MessageDescriptor struct {
1336 Desc protoreflect.MessageDescriptor
1337 }
1338
1339 var (
1340 _ starlark.Callable = MessageDescriptor{}
1341 _ starlark.HasAttrs = MessageDescriptor{}
1342 )
1343
1344 func (d MessageDescriptor) String() string { return string(d.Desc.FullName()) }
1345 func (d MessageDescriptor) Type() string { return "proto.MessageDescriptor" }
1346 func (d MessageDescriptor) Truth() starlark.Bool { return true }
1347 func (d MessageDescriptor) Freeze() {} // immutable
1348 func (d MessageDescriptor) Hash() (h uint32, err error) {
1349 return starlark.String(d.Desc.FullName()).Hash()
1350 }
1351 func (d MessageDescriptor) Attr(name string) (starlark.Value, error) {
1352 if desc := d.Desc.Messages().ByName(protoreflect.Name(name)); desc != nil {
1353 return MessageDescriptor{desc}, nil
1354 }
1355 if desc := d.Desc.Extensions().ByName(protoreflect.Name(name)); desc != nil {
1356 return FieldDescriptor{desc}, nil
1357 }
1358 if desc := d.Desc.Fields().ByName(protoreflect.Name(name)); desc != nil {
1359 return FieldDescriptor{desc}, nil
1360 }
1361 if desc := d.Desc.Enums().ByName(protoreflect.Name(name)); desc != nil {
1362 return EnumDescriptor{desc}, nil
1363 }
1364 return nil, nil
1365 }
1366 func (d MessageDescriptor) AttrNames() []string {
1367 var names []string
1368 messages := d.Desc.Messages()
1369 for i, n := 0, messages.Len(); i < n; i++ {
1370 names = append(names, string(messages.Get(i).Name()))
1371 }
1372 enums := d.Desc.Enums()
1373 for i, n := 0, enums.Len(); i < n; i++ {
1374 names = append(names, string(enums.Get(i).Name()))
1375 }
1376 sort.Strings(names)
1377 return names
1378 }
1379 func (d MessageDescriptor) Name() string { return string(d.Desc.Name()) } // for Callable
1380
1381 // A FieldDescriptor is an immutable Starlark value that describes
1382 // a field (possibly an extension field) of protocol message.
1383 //
1384 // A FieldDescriptor value contains a reference to a protoreflect.FieldDescriptor.
1385 // Two FieldDescriptor values compare equal if and only if they refer to the
1386 // same protoreflect.FieldDescriptor.
1387 //
1388 // The primary use for FieldDescriptors is to access extension fields of a message.
1389 //
1390 // A FieldDescriptor value has not attributes.
1391 // TODO(adonovan): expose metadata fields (e.g. name, type).
1392 type FieldDescriptor struct {
1393 Desc protoreflect.FieldDescriptor
1394 }
1395
1396 var (
1397 _ starlark.HasAttrs = FieldDescriptor{}
1398 )
1399
1400 func (d FieldDescriptor) String() string { return string(d.Desc.FullName()) }
1401 func (d FieldDescriptor) Type() string { return "proto.FieldDescriptor" }
1402 func (d FieldDescriptor) Truth() starlark.Bool { return true }
1403 func (d FieldDescriptor) Freeze() {} // immutable
1404 func (d FieldDescriptor) Hash() (h uint32, err error) {
1405 return starlark.String(d.Desc.FullName()).Hash()
1406 }
1407 func (d FieldDescriptor) Attr(name string) (starlark.Value, error) {
1408 // TODO(adonovan): expose metadata fields of Desc?
1409 return nil, nil
1410 }
1411 func (d FieldDescriptor) AttrNames() []string {
1412 var names []string
1413 // TODO(adonovan): expose metadata fields of Desc?
1414 sort.Strings(names)
1415 return names
1416 }
1417
1418 // An EnumDescriptor is an immutable Starlark value that describes an
1419 // protocol enum type.
1420 //
1421 // An EnumDescriptor contains a reference to a protoreflect.EnumDescriptor.
1422 // Two EnumDescriptor values compare equal if and only if they
1423 // refer to the same protoreflect.EnumDescriptor.
1424 //
1425 // An EnumDescriptor may be called like a function. It converts its
1426 // sole argument, which must be an int, string, or EnumValueDescriptor,
1427 // to an EnumValueDescriptor.
1428 //
1429 // The fields of an EnumDescriptor value are the values of the
1430 // enumeration, each of type EnumValueDescriptor.
1431 type EnumDescriptor struct {
1432 Desc protoreflect.EnumDescriptor
1433 }
1434
1435 var (
1436 _ starlark.HasAttrs = EnumDescriptor{}
1437 _ starlark.Callable = EnumDescriptor{}
1438 )
1439
1440 func (e EnumDescriptor) String() string { return string(e.Desc.FullName()) }
1441 func (e EnumDescriptor) Type() string { return "proto.EnumDescriptor" }
1442 func (e EnumDescriptor) Truth() starlark.Bool { return true }
1443 func (e EnumDescriptor) Freeze() {} // immutable
1444 func (e EnumDescriptor) Hash() (h uint32, err error) { return 0, nil } // TODO(adonovan): number?
1445 func (e EnumDescriptor) Attr(name string) (starlark.Value, error) {
1446 if v := e.Desc.Values().ByName(protoreflect.Name(name)); v != nil {
1447 return EnumValueDescriptor{v}, nil
1448 }
1449 return nil, nil
1450 }
1451 func (e EnumDescriptor) AttrNames() []string {
1452 var names []string
1453 values := e.Desc.Values()
1454 for i, n := 0, values.Len(); i < n; i++ {
1455 names = append(names, string(values.Get(i).Name()))
1456 }
1457 sort.Strings(names)
1458 return names
1459 }
1460 func (e EnumDescriptor) Name() string { return string(e.Desc.Name()) } // for Callable
1461
1462 // The Call method implements the starlark.Callable interface.
1463 // A call to an enum descriptor converts its argument to a value of that enum type.
1464 func (e EnumDescriptor) CallInternal(_ *starlark.Thread, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
1465 var x starlark.Value
1466 if err := starlark.UnpackPositionalArgs(string(e.Desc.Name()), args, kwargs, 1, &x); err != nil {
1467 return nil, err
1468 }
1469 v, err := enumValueOf(e.Desc, x)
1470 if err != nil {
1471 return nil, fmt.Errorf("%s: %v", e.Desc.Name(), err)
1472 }
1473 return EnumValueDescriptor{Desc: v}, nil
1474 }
1475
1476 // enumValueOf converts an int, string, or enum value to a value of the specified enum type.
1477 func enumValueOf(enum protoreflect.EnumDescriptor, x starlark.Value) (protoreflect.EnumValueDescriptor, error) {
1478 switch x := x.(type) {
1479 case starlark.Int:
1480 i, err := starlark.AsInt32(x)
1481 if err != nil {
1482 return nil, fmt.Errorf("invalid number %s for %s enum", x, enum.Name())
1483 }
1484 desc := enum.Values().ByNumber(protoreflect.EnumNumber(i))
1485 if desc == nil {
1486 return nil, fmt.Errorf("invalid number %d for %s enum", i, enum.Name())
1487 }
1488 return desc, nil
1489
1490 case starlark.String:
1491 name := protoreflect.Name(x)
1492 desc := enum.Values().ByName(name)
1493 if desc == nil {
1494 return nil, fmt.Errorf("invalid name %q for %s enum", name, enum.Name())
1495 }
1496 return desc, nil
1497
1498 case EnumValueDescriptor:
1499 if parent := x.Desc.Parent(); parent != enum {
1500 return nil, fmt.Errorf("invalid value %s.%s for %s enum",
1501 parent.Name(), x.Desc.Name(), enum.Name())
1502 }
1503 return x.Desc, nil
1504 }
1505
1506 return nil, fmt.Errorf("cannot convert %s to %s enum", x.Type(), enum.Name())
1507 }
1508
1509 // An EnumValueDescriptor is an immutable Starlark value that represents one value of an enumeration.
1510 //
1511 // An EnumValueDescriptor contains a reference to a protoreflect.EnumValueDescriptor.
1512 // Two EnumValueDescriptor values compare equal if and only if they
1513 // refer to the same protoreflect.EnumValueDescriptor.
1514 //
1515 // An EnumValueDescriptor has the following fields:
1516 //
1517 // index -- int, index of this value within the enum sequence
1518 // name -- string, name of this enum value
1519 // number -- int, numeric value of this enum value
1520 // type -- EnumDescriptor, the enum type to which this value belongs
1521 type EnumValueDescriptor struct {
1522 Desc protoreflect.EnumValueDescriptor
1523 }
1524
1525 var (
1526 _ starlark.HasAttrs = EnumValueDescriptor{}
1527 _ starlark.Comparable = EnumValueDescriptor{}
1528 )
1529
1530 func (e EnumValueDescriptor) String() string {
1531 enum := e.Desc.Parent()
1532 return string(enum.Name() + "." + e.Desc.Name()) // "Enum.EnumValue"
1533 }
1534 func (e EnumValueDescriptor) Type() string { return "proto.EnumValueDescriptor" }
1535 func (e EnumValueDescriptor) Truth() starlark.Bool { return true }
1536 func (e EnumValueDescriptor) Freeze() {} // immutable
1537 func (e EnumValueDescriptor) Hash() (h uint32, err error) { return uint32(e.Desc.Number()), nil }
1538 func (e EnumValueDescriptor) AttrNames() []string {
1539 return []string{"index", "name", "number", "type"}
1540 }
1541 func (e EnumValueDescriptor) Attr(name string) (starlark.Value, error) {
1542 switch name {
1543 case "index":
1544 return starlark.MakeInt(e.Desc.Index()), nil
1545 case "name":
1546 return starlark.String(e.Desc.Name()), nil
1547 case "number":
1548 return starlark.MakeInt(int(e.Desc.Number())), nil
1549 case "type":
1550 enum := e.Desc.Parent()
1551 return EnumDescriptor{Desc: enum.(protoreflect.EnumDescriptor)}, nil
1552 }
1553 return nil, nil
1554 }
1555 func (x EnumValueDescriptor) CompareSameType(op syntax.Token, y_ starlark.Value, depth int) (bool, error) {
1556 y := y_.(EnumValueDescriptor)
1557 switch op {
1558 case syntax.EQL:
1559 return x.Desc == y.Desc, nil
1560 case syntax.NEQ:
1561 return x.Desc != y.Desc, nil
1562 default:
1563 return false, fmt.Errorf("%s %s %s not implemented", x.Type(), op, y_.Type())
1564 }
1565 }