1// Copyright 2020 The Go 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 5package internal_gengo 6 7import ( 8 "strings" 9 10 "google.golang.org/protobuf/compiler/protogen" 11 "google.golang.org/protobuf/internal/genid" 12) 13 14// Specialized support for well-known types are hard-coded into the generator 15// as opposed to being injected in adjacent .go sources in the generated package 16// in order to support specialized build systems like Bazel that always generate 17// dynamically from the source .proto files. 18 19func genPackageKnownComment(f *fileInfo) protogen.Comments { 20 switch f.Desc.Path() { 21 case genid.File_google_protobuf_any_proto: 22 return ` Package anypb contains generated types for ` + genid.File_google_protobuf_any_proto + `. 23 24 The Any message is a dynamic representation of any other message value. 25 It is functionally a tuple of the full name of the remote message type and 26 the serialized bytes of the remote message value. 27 28 29 Constructing an Any 30 31 An Any message containing another message value is constructed using New: 32 33 any, err := anypb.New(m) 34 if err != nil { 35 ... // handle error 36 } 37 ... // make use of any 38 39 40 Unmarshaling an Any 41 42 With a populated Any message, the underlying message can be serialized into 43 a remote concrete message value in a few ways. 44 45 If the exact concrete type is known, then a new (or pre-existing) instance 46 of that message can be passed to the UnmarshalTo method: 47 48 m := new(foopb.MyMessage) 49 if err := any.UnmarshalTo(m); err != nil { 50 ... // handle error 51 } 52 ... // make use of m 53 54 If the exact concrete type is not known, then the UnmarshalNew method can be 55 used to unmarshal the contents into a new instance of the remote message type: 56 57 m, err := any.UnmarshalNew() 58 if err != nil { 59 ... // handle error 60 } 61 ... // make use of m 62 63 UnmarshalNew uses the global type registry to resolve the message type and 64 construct a new instance of that message to unmarshal into. In order for a 65 message type to appear in the global registry, the Go type representing that 66 protobuf message type must be linked into the Go binary. For messages 67 generated by protoc-gen-go, this is achieved through an import of the 68 generated Go package representing a .proto file. 69 70 A common pattern with UnmarshalNew is to use a type switch with the resulting 71 proto.Message value: 72 73 switch m := m.(type) { 74 case *foopb.MyMessage: 75 ... // make use of m as a *foopb.MyMessage 76 case *barpb.OtherMessage: 77 ... // make use of m as a *barpb.OtherMessage 78 case *bazpb.SomeMessage: 79 ... // make use of m as a *bazpb.SomeMessage 80 } 81 82 This pattern ensures that the generated packages containing the message types 83 listed in the case clauses are linked into the Go binary and therefore also 84 registered in the global registry. 85 86 87 Type checking an Any 88 89 In order to type check whether an Any message represents some other message, 90 then use the MessageIs method: 91 92 if any.MessageIs((*foopb.MyMessage)(nil)) { 93 ... // make use of any, knowing that it contains a foopb.MyMessage 94 } 95 96 The MessageIs method can also be used with an allocated instance of the target 97 message type if the intention is to unmarshal into it if the type matches: 98 99 m := new(foopb.MyMessage) 100 if any.MessageIs(m) { 101 if err := any.UnmarshalTo(m); err != nil { 102 ... // handle error 103 } 104 ... // make use of m 105 } 106 107` 108 case genid.File_google_protobuf_timestamp_proto: 109 return ` Package timestamppb contains generated types for ` + genid.File_google_protobuf_timestamp_proto + `. 110 111 The Timestamp message represents a timestamp, 112 an instant in time since the Unix epoch (January 1st, 1970). 113 114 115 Conversion to a Go Time 116 117 The AsTime method can be used to convert a Timestamp message to a 118 standard Go time.Time value in UTC: 119 120 t := ts.AsTime() 121 ... // make use of t as a time.Time 122 123 Converting to a time.Time is a common operation so that the extensive 124 set of time-based operations provided by the time package can be leveraged. 125 See https://golang.org/pkg/time for more information. 126 127 The AsTime method performs the conversion on a best-effort basis. Timestamps 128 with denormal values (e.g., nanoseconds beyond 0 and 99999999, inclusive) 129 are normalized during the conversion to a time.Time. To manually check for 130 invalid Timestamps per the documented limitations in timestamp.proto, 131 additionally call the CheckValid method: 132 133 if err := ts.CheckValid(); err != nil { 134 ... // handle error 135 } 136 137 138 Conversion from a Go Time 139 140 The timestamppb.New function can be used to construct a Timestamp message 141 from a standard Go time.Time value: 142 143 ts := timestamppb.New(t) 144 ... // make use of ts as a *timestamppb.Timestamp 145 146 In order to construct a Timestamp representing the current time, use Now: 147 148 ts := timestamppb.Now() 149 ... // make use of ts as a *timestamppb.Timestamp 150 151` 152 case genid.File_google_protobuf_duration_proto: 153 return ` Package durationpb contains generated types for ` + genid.File_google_protobuf_duration_proto + `. 154 155 The Duration message represents a signed span of time. 156 157 158 Conversion to a Go Duration 159 160 The AsDuration method can be used to convert a Duration message to a 161 standard Go time.Duration value: 162 163 d := dur.AsDuration() 164 ... // make use of d as a time.Duration 165 166 Converting to a time.Duration is a common operation so that the extensive 167 set of time-based operations provided by the time package can be leveraged. 168 See https://golang.org/pkg/time for more information. 169 170 The AsDuration method performs the conversion on a best-effort basis. 171 Durations with denormal values (e.g., nanoseconds beyond -99999999 and 172 +99999999, inclusive; or seconds and nanoseconds with opposite signs) 173 are normalized during the conversion to a time.Duration. To manually check for 174 invalid Duration per the documented limitations in duration.proto, 175 additionally call the CheckValid method: 176 177 if err := dur.CheckValid(); err != nil { 178 ... // handle error 179 } 180 181 Note that the documented limitations in duration.proto does not protect a 182 Duration from overflowing the representable range of a time.Duration in Go. 183 The AsDuration method uses saturation arithmetic such that an overflow clamps 184 the resulting value to the closest representable value (e.g., math.MaxInt64 185 for positive overflow and math.MinInt64 for negative overflow). 186 187 188 Conversion from a Go Duration 189 190 The durationpb.New function can be used to construct a Duration message 191 from a standard Go time.Duration value: 192 193 dur := durationpb.New(d) 194 ... // make use of d as a *durationpb.Duration 195 196` 197 case genid.File_google_protobuf_struct_proto: 198 return ` Package structpb contains generated types for ` + genid.File_google_protobuf_struct_proto + `. 199 200 The messages (i.e., Value, Struct, and ListValue) defined in struct.proto are 201 used to represent arbitrary JSON. The Value message represents a JSON value, 202 the Struct message represents a JSON object, and the ListValue message 203 represents a JSON array. See https://json.org for more information. 204 205 The Value, Struct, and ListValue types have generated MarshalJSON and 206 UnmarshalJSON methods such that they serialize JSON equivalent to what the 207 messages themselves represent. Use of these types with the 208 "google.golang.org/protobuf/encoding/protojson" package 209 ensures that they will be serialized as their JSON equivalent. 210 211 # Conversion to and from a Go interface 212 213 The standard Go "encoding/json" package has functionality to serialize 214 arbitrary types to a large degree. The Value.AsInterface, Struct.AsMap, and 215 ListValue.AsSlice methods can convert the protobuf message representation into 216 a form represented by interface{}, map[string]interface{}, and []interface{}. 217 This form can be used with other packages that operate on such data structures 218 and also directly with the standard json package. 219 220 In order to convert the interface{}, map[string]interface{}, and []interface{} 221 forms back as Value, Struct, and ListValue messages, use the NewStruct, 222 NewList, and NewValue constructor functions. 223 224 # Example usage 225 226 Consider the following example JSON object: 227 228 { 229 "firstName": "John", 230 "lastName": "Smith", 231 "isAlive": true, 232 "age": 27, 233 "address": { 234 "streetAddress": "21 2nd Street", 235 "city": "New York", 236 "state": "NY", 237 "postalCode": "10021-3100" 238 }, 239 "phoneNumbers": [ 240 { 241 "type": "home", 242 "number": "212 555-1234" 243 }, 244 { 245 "type": "office", 246 "number": "646 555-4567" 247 } 248 ], 249 "children": [], 250 "spouse": null 251 } 252 253 To construct a Value message representing the above JSON object: 254 255 m, err := structpb.NewValue(map[string]interface{}{ 256 "firstName": "John", 257 "lastName": "Smith", 258 "isAlive": true, 259 "age": 27, 260 "address": map[string]interface{}{ 261 "streetAddress": "21 2nd Street", 262 "city": "New York", 263 "state": "NY", 264 "postalCode": "10021-3100", 265 }, 266 "phoneNumbers": []interface{}{ 267 map[string]interface{}{ 268 "type": "home", 269 "number": "212 555-1234", 270 }, 271 map[string]interface{}{ 272 "type": "office", 273 "number": "646 555-4567", 274 }, 275 }, 276 "children": []interface{}{}, 277 "spouse": nil, 278 }) 279 if err != nil { 280 ... // handle error 281 } 282 ... // make use of m as a *structpb.Value 283` 284 case genid.File_google_protobuf_field_mask_proto: 285 return ` Package fieldmaskpb contains generated types for ` + genid.File_google_protobuf_field_mask_proto + `. 286 287 The FieldMask message represents a set of symbolic field paths. 288 The paths are specific to some target message type, 289 which is not stored within the FieldMask message itself. 290 291 292 Constructing a FieldMask 293 294 The New function is used construct a FieldMask: 295 296 var messageType *descriptorpb.DescriptorProto 297 fm, err := fieldmaskpb.New(messageType, "field.name", "field.number") 298 if err != nil { 299 ... // handle error 300 } 301 ... // make use of fm 302 303 The "field.name" and "field.number" paths are valid paths according to the 304 google.protobuf.DescriptorProto message. Use of a path that does not correlate 305 to valid fields reachable from DescriptorProto would result in an error. 306 307 Once a FieldMask message has been constructed, 308 the Append method can be used to insert additional paths to the path set: 309 310 var messageType *descriptorpb.DescriptorProto 311 if err := fm.Append(messageType, "options"); err != nil { 312 ... // handle error 313 } 314 315 316 Type checking a FieldMask 317 318 In order to verify that a FieldMask represents a set of fields that are 319 reachable from some target message type, use the IsValid method: 320 321 var messageType *descriptorpb.DescriptorProto 322 if fm.IsValid(messageType) { 323 ... // make use of fm 324 } 325 326 IsValid needs to be passed the target message type as an input since the 327 FieldMask message itself does not store the message type that the set of paths 328 are for. 329` 330 default: 331 return "" 332 } 333} 334 335func genMessageKnownFunctions(g *protogen.GeneratedFile, f *fileInfo, m *messageInfo) { 336 switch m.Desc.FullName() { 337 case genid.Any_message_fullname: 338 g.P("// New marshals src into a new Any instance.") 339 g.P("func New(src ", protoPackage.Ident("Message"), ") (*Any, error) {") 340 g.P(" dst := new(Any)") 341 g.P(" if err := dst.MarshalFrom(src); err != nil {") 342 g.P(" return nil, err") 343 g.P(" }") 344 g.P(" return dst, nil") 345 g.P("}") 346 g.P() 347 348 g.P("// MarshalFrom marshals src into dst as the underlying message") 349 g.P("// using the provided marshal options.") 350 g.P("//") 351 g.P("// If no options are specified, call dst.MarshalFrom instead.") 352 g.P("func MarshalFrom(dst *Any, src ", protoPackage.Ident("Message"), ", opts ", protoPackage.Ident("MarshalOptions"), ") error {") 353 g.P(" const urlPrefix = \"type.googleapis.com/\"") 354 g.P(" if src == nil {") 355 g.P(" return ", protoimplPackage.Ident("X"), ".NewError(\"invalid nil source message\")") 356 g.P(" }") 357 g.P(" b, err := opts.Marshal(src)") 358 g.P(" if err != nil {") 359 g.P(" return err") 360 g.P(" }") 361 g.P(" dst.TypeUrl = urlPrefix + string(src.ProtoReflect().Descriptor().FullName())") 362 g.P(" dst.Value = b") 363 g.P(" return nil") 364 g.P("}") 365 g.P() 366 367 g.P("// UnmarshalTo unmarshals the underlying message from src into dst") 368 g.P("// using the provided unmarshal options.") 369 g.P("// It reports an error if dst is not of the right message type.") 370 g.P("//") 371 g.P("// If no options are specified, call src.UnmarshalTo instead.") 372 g.P("func UnmarshalTo(src *Any, dst ", protoPackage.Ident("Message"), ", opts ", protoPackage.Ident("UnmarshalOptions"), ") error {") 373 g.P(" if src == nil {") 374 g.P(" return ", protoimplPackage.Ident("X"), ".NewError(\"invalid nil source message\")") 375 g.P(" }") 376 g.P(" if !src.MessageIs(dst) {") 377 g.P(" got := dst.ProtoReflect().Descriptor().FullName()") 378 g.P(" want := src.MessageName()") 379 g.P(" return ", protoimplPackage.Ident("X"), ".NewError(\"mismatched message type: got %q, want %q\", got, want)") 380 g.P(" }") 381 g.P(" return opts.Unmarshal(src.GetValue(), dst)") 382 g.P("}") 383 g.P() 384 385 g.P("// UnmarshalNew unmarshals the underlying message from src into dst,") 386 g.P("// which is newly created message using a type resolved from the type URL.") 387 g.P("// The message type is resolved according to opt.Resolver,") 388 g.P("// which should implement protoregistry.MessageTypeResolver.") 389 g.P("// It reports an error if the underlying message type could not be resolved.") 390 g.P("//") 391 g.P("// If no options are specified, call src.UnmarshalNew instead.") 392 g.P("func UnmarshalNew(src *Any, opts ", protoPackage.Ident("UnmarshalOptions"), ") (dst ", protoPackage.Ident("Message"), ", err error) {") 393 g.P(" if src.GetTypeUrl() == \"\" {") 394 g.P(" return nil, ", protoimplPackage.Ident("X"), ".NewError(\"invalid empty type URL\")") 395 g.P(" }") 396 g.P(" if opts.Resolver == nil {") 397 g.P(" opts.Resolver = ", protoregistryPackage.Ident("GlobalTypes")) 398 g.P(" }") 399 g.P(" r, ok := opts.Resolver.(", protoregistryPackage.Ident("MessageTypeResolver"), ")") 400 g.P(" if !ok {") 401 g.P(" return nil, ", protoregistryPackage.Ident("NotFound")) 402 g.P(" }") 403 g.P(" mt, err := r.FindMessageByURL(src.GetTypeUrl())") 404 g.P(" if err != nil {") 405 g.P(" if err == ", protoregistryPackage.Ident("NotFound"), " {") 406 g.P(" return nil, err") 407 g.P(" }") 408 g.P(" return nil, ", protoimplPackage.Ident("X"), ".NewError(\"could not resolve %q: %v\", src.GetTypeUrl(), err)") 409 g.P(" }") 410 g.P(" dst = mt.New().Interface()") 411 g.P(" return dst, opts.Unmarshal(src.GetValue(), dst)") 412 g.P("}") 413 g.P() 414 415 g.P("// MessageIs reports whether the underlying message is of the same type as m.") 416 g.P("func (x *Any) MessageIs(m ", protoPackage.Ident("Message"), ") bool {") 417 g.P(" if m == nil {") 418 g.P(" return false") 419 g.P(" }") 420 g.P(" url := x.GetTypeUrl()") 421 g.P(" name := string(m.ProtoReflect().Descriptor().FullName())") 422 g.P(" if !", stringsPackage.Ident("HasSuffix"), "(url, name) {") 423 g.P(" return false") 424 g.P(" }") 425 g.P(" return len(url) == len(name) || url[len(url)-len(name)-1] == '/'") 426 g.P("}") 427 g.P() 428 429 g.P("// MessageName reports the full name of the underlying message,") 430 g.P("// returning an empty string if invalid.") 431 g.P("func (x *Any) MessageName() ", protoreflectPackage.Ident("FullName"), " {") 432 g.P(" url := x.GetTypeUrl()") 433 g.P(" name := ", protoreflectPackage.Ident("FullName"), "(url)") 434 g.P(" if i := ", stringsPackage.Ident("LastIndexByte"), "(url, '/'); i >= 0 {") 435 g.P(" name = name[i+len(\"/\"):]") 436 g.P(" }") 437 g.P(" if !name.IsValid() {") 438 g.P(" return \"\"") 439 g.P(" }") 440 g.P(" return name") 441 g.P("}") 442 g.P() 443 444 g.P("// MarshalFrom marshals m into x as the underlying message.") 445 g.P("func (x *Any) MarshalFrom(m ", protoPackage.Ident("Message"), ") error {") 446 g.P(" return MarshalFrom(x, m, ", protoPackage.Ident("MarshalOptions"), "{})") 447 g.P("}") 448 g.P() 449 450 g.P("// UnmarshalTo unmarshals the contents of the underlying message of x into m.") 451 g.P("// It resets m before performing the unmarshal operation.") 452 g.P("// It reports an error if m is not of the right message type.") 453 g.P("func (x *Any) UnmarshalTo(m ", protoPackage.Ident("Message"), ") error {") 454 g.P(" return UnmarshalTo(x, m, ", protoPackage.Ident("UnmarshalOptions"), "{})") 455 g.P("}") 456 g.P() 457 458 g.P("// UnmarshalNew unmarshals the contents of the underlying message of x into") 459 g.P("// a newly allocated message of the specified type.") 460 g.P("// It reports an error if the underlying message type could not be resolved.") 461 g.P("func (x *Any) UnmarshalNew() (", protoPackage.Ident("Message"), ", error) {") 462 g.P(" return UnmarshalNew(x, ", protoPackage.Ident("UnmarshalOptions"), "{})") 463 g.P("}") 464 g.P() 465 466 case genid.Timestamp_message_fullname: 467 g.P("// Now constructs a new Timestamp from the current time.") 468 g.P("func Now() *Timestamp {") 469 g.P(" return New(", timePackage.Ident("Now"), "())") 470 g.P("}") 471 g.P() 472 473 g.P("// New constructs a new Timestamp from the provided time.Time.") 474 g.P("func New(t ", timePackage.Ident("Time"), ") *Timestamp {") 475 g.P(" return &Timestamp{Seconds: int64(t.Unix()), Nanos: int32(t.Nanosecond())}") 476 g.P("}") 477 g.P() 478 479 g.P("// AsTime converts x to a time.Time.") 480 g.P("func (x *Timestamp) AsTime() ", timePackage.Ident("Time"), " {") 481 g.P(" return ", timePackage.Ident("Unix"), "(int64(x.GetSeconds()), int64(x.GetNanos())).UTC()") 482 g.P("}") 483 g.P() 484 485 g.P("// IsValid reports whether the timestamp is valid.") 486 g.P("// It is equivalent to CheckValid == nil.") 487 g.P("func (x *Timestamp) IsValid() bool {") 488 g.P(" return x.check() == 0") 489 g.P("}") 490 g.P() 491 492 g.P("// CheckValid returns an error if the timestamp is invalid.") 493 g.P("// In particular, it checks whether the value represents a date that is") 494 g.P("// in the range of 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.") 495 g.P("// An error is reported for a nil Timestamp.") 496 g.P("func (x *Timestamp) CheckValid() error {") 497 g.P(" switch x.check() {") 498 g.P(" case invalidNil:") 499 g.P(" return ", protoimplPackage.Ident("X"), ".NewError(\"invalid nil Timestamp\")") 500 g.P(" case invalidUnderflow:") 501 g.P(" return ", protoimplPackage.Ident("X"), ".NewError(\"timestamp (%v) before 0001-01-01\", x)") 502 g.P(" case invalidOverflow:") 503 g.P(" return ", protoimplPackage.Ident("X"), ".NewError(\"timestamp (%v) after 9999-12-31\", x)") 504 g.P(" case invalidNanos:") 505 g.P(" return ", protoimplPackage.Ident("X"), ".NewError(\"timestamp (%v) has out-of-range nanos\", x)") 506 g.P(" default:") 507 g.P(" return nil") 508 g.P(" }") 509 g.P("}") 510 g.P() 511 512 g.P("const (") 513 g.P(" _ = iota") 514 g.P(" invalidNil") 515 g.P(" invalidUnderflow") 516 g.P(" invalidOverflow") 517 g.P(" invalidNanos") 518 g.P(")") 519 g.P() 520 521 g.P("func (x *Timestamp) check() uint {") 522 g.P(" const minTimestamp = -62135596800 // Seconds between 1970-01-01T00:00:00Z and 0001-01-01T00:00:00Z, inclusive") 523 g.P(" const maxTimestamp = +253402300799 // Seconds between 1970-01-01T00:00:00Z and 9999-12-31T23:59:59Z, inclusive") 524 g.P(" secs := x.GetSeconds()") 525 g.P(" nanos := x.GetNanos()") 526 g.P(" switch {") 527 g.P(" case x == nil:") 528 g.P(" return invalidNil") 529 g.P(" case secs < minTimestamp:") 530 g.P(" return invalidUnderflow") 531 g.P(" case secs > maxTimestamp:") 532 g.P(" return invalidOverflow") 533 g.P(" case nanos < 0 || nanos >= 1e9:") 534 g.P(" return invalidNanos") 535 g.P(" default:") 536 g.P(" return 0") 537 g.P(" }") 538 g.P("}") 539 g.P() 540 541 case genid.Duration_message_fullname: 542 g.P("// New constructs a new Duration from the provided time.Duration.") 543 g.P("func New(d ", timePackage.Ident("Duration"), ") *Duration {") 544 g.P(" nanos := d.Nanoseconds()") 545 g.P(" secs := nanos / 1e9") 546 g.P(" nanos -= secs * 1e9") 547 g.P(" return &Duration{Seconds: int64(secs), Nanos: int32(nanos)}") 548 g.P("}") 549 g.P() 550 551 g.P("// AsDuration converts x to a time.Duration,") 552 g.P("// returning the closest duration value in the event of overflow.") 553 g.P("func (x *Duration) AsDuration() ", timePackage.Ident("Duration"), " {") 554 g.P(" secs := x.GetSeconds()") 555 g.P(" nanos := x.GetNanos()") 556 g.P(" d := ", timePackage.Ident("Duration"), "(secs) * ", timePackage.Ident("Second")) 557 g.P(" overflow := d/", timePackage.Ident("Second"), " != ", timePackage.Ident("Duration"), "(secs)") 558 g.P(" d += ", timePackage.Ident("Duration"), "(nanos) * ", timePackage.Ident("Nanosecond")) 559 g.P(" overflow = overflow || (secs < 0 && nanos < 0 && d > 0)") 560 g.P(" overflow = overflow || (secs > 0 && nanos > 0 && d < 0)") 561 g.P(" if overflow {") 562 g.P(" switch {") 563 g.P(" case secs < 0:") 564 g.P(" return ", timePackage.Ident("Duration"), "(", mathPackage.Ident("MinInt64"), ")") 565 g.P(" case secs > 0:") 566 g.P(" return ", timePackage.Ident("Duration"), "(", mathPackage.Ident("MaxInt64"), ")") 567 g.P(" }") 568 g.P(" }") 569 g.P(" return d") 570 g.P("}") 571 g.P() 572 573 g.P("// IsValid reports whether the duration is valid.") 574 g.P("// It is equivalent to CheckValid == nil.") 575 g.P("func (x *Duration) IsValid() bool {") 576 g.P(" return x.check() == 0") 577 g.P("}") 578 g.P() 579 580 g.P("// CheckValid returns an error if the duration is invalid.") 581 g.P("// In particular, it checks whether the value is within the range of") 582 g.P("// -10000 years to +10000 years inclusive.") 583 g.P("// An error is reported for a nil Duration.") 584 g.P("func (x *Duration) CheckValid() error {") 585 g.P(" switch x.check() {") 586 g.P(" case invalidNil:") 587 g.P(" return ", protoimplPackage.Ident("X"), ".NewError(\"invalid nil Duration\")") 588 g.P(" case invalidUnderflow:") 589 g.P(" return ", protoimplPackage.Ident("X"), ".NewError(\"duration (%v) exceeds -10000 years\", x)") 590 g.P(" case invalidOverflow:") 591 g.P(" return ", protoimplPackage.Ident("X"), ".NewError(\"duration (%v) exceeds +10000 years\", x)") 592 g.P(" case invalidNanosRange:") 593 g.P(" return ", protoimplPackage.Ident("X"), ".NewError(\"duration (%v) has out-of-range nanos\", x)") 594 g.P(" case invalidNanosSign:") 595 g.P(" return ", protoimplPackage.Ident("X"), ".NewError(\"duration (%v) has seconds and nanos with different signs\", x)") 596 g.P(" default:") 597 g.P(" return nil") 598 g.P(" }") 599 g.P("}") 600 g.P() 601 602 g.P("const (") 603 g.P(" _ = iota") 604 g.P(" invalidNil") 605 g.P(" invalidUnderflow") 606 g.P(" invalidOverflow") 607 g.P(" invalidNanosRange") 608 g.P(" invalidNanosSign") 609 g.P(")") 610 g.P() 611 612 g.P("func (x *Duration) check() uint {") 613 g.P(" const absDuration = 315576000000 // 10000yr * 365.25day/yr * 24hr/day * 60min/hr * 60sec/min") 614 g.P(" secs := x.GetSeconds()") 615 g.P(" nanos := x.GetNanos()") 616 g.P(" switch {") 617 g.P(" case x == nil:") 618 g.P(" return invalidNil") 619 g.P(" case secs < -absDuration:") 620 g.P(" return invalidUnderflow") 621 g.P(" case secs > +absDuration:") 622 g.P(" return invalidOverflow") 623 g.P(" case nanos <= -1e9 || nanos >= +1e9:") 624 g.P(" return invalidNanosRange") 625 g.P(" case (secs > 0 && nanos < 0) || (secs < 0 && nanos > 0):") 626 g.P(" return invalidNanosSign") 627 g.P(" default:") 628 g.P(" return 0") 629 g.P(" }") 630 g.P("}") 631 g.P() 632 633 case genid.Struct_message_fullname: 634 g.P("// NewStruct constructs a Struct from a general-purpose Go map.") 635 g.P("// The map keys must be valid UTF-8.") 636 g.P("// The map values are converted using NewValue.") 637 g.P("func NewStruct(v map[string]interface{}) (*Struct, error) {") 638 g.P(" x := &Struct{Fields: make(map[string]*Value, len(v))}") 639 g.P(" for k, v := range v {") 640 g.P(" if !", utf8Package.Ident("ValidString"), "(k) {") 641 g.P(" return nil, ", protoimplPackage.Ident("X"), ".NewError(\"invalid UTF-8 in string: %q\", k)") 642 g.P(" }") 643 g.P(" var err error") 644 g.P(" x.Fields[k], err = NewValue(v)") 645 g.P(" if err != nil {") 646 g.P(" return nil, err") 647 g.P(" }") 648 g.P(" }") 649 g.P(" return x, nil") 650 g.P("}") 651 g.P() 652 653 g.P("// AsMap converts x to a general-purpose Go map.") 654 g.P("// The map values are converted by calling Value.AsInterface.") 655 g.P("func (x *Struct) AsMap() map[string]interface{} {") 656 g.P(" f := x.GetFields()") 657 g.P(" vs := make(map[string]interface{}, len(f))") 658 g.P(" for k, v := range f {") 659 g.P(" vs[k] = v.AsInterface()") 660 g.P(" }") 661 g.P(" return vs") 662 g.P("}") 663 g.P() 664 665 g.P("func (x *Struct) MarshalJSON() ([]byte, error) {") 666 g.P(" return ", protojsonPackage.Ident("Marshal"), "(x)") 667 g.P("}") 668 g.P() 669 670 g.P("func (x *Struct) UnmarshalJSON(b []byte) error {") 671 g.P(" return ", protojsonPackage.Ident("Unmarshal"), "(b, x)") 672 g.P("}") 673 g.P() 674 675 case genid.ListValue_message_fullname: 676 g.P("// NewList constructs a ListValue from a general-purpose Go slice.") 677 g.P("// The slice elements are converted using NewValue.") 678 g.P("func NewList(v []interface{}) (*ListValue, error) {") 679 g.P(" x := &ListValue{Values: make([]*Value, len(v))}") 680 g.P(" for i, v := range v {") 681 g.P(" var err error") 682 g.P(" x.Values[i], err = NewValue(v)") 683 g.P(" if err != nil {") 684 g.P(" return nil, err") 685 g.P(" }") 686 g.P(" }") 687 g.P(" return x, nil") 688 g.P("}") 689 g.P() 690 691 g.P("// AsSlice converts x to a general-purpose Go slice.") 692 g.P("// The slice elements are converted by calling Value.AsInterface.") 693 g.P("func (x *ListValue) AsSlice() []interface{} {") 694 g.P(" vals := x.GetValues()") 695 g.P(" vs := make([]interface{}, len(vals))") 696 g.P(" for i, v := range vals {") 697 g.P(" vs[i] = v.AsInterface()") 698 g.P(" }") 699 g.P(" return vs") 700 g.P("}") 701 g.P() 702 703 g.P("func (x *ListValue) MarshalJSON() ([]byte, error) {") 704 g.P(" return ", protojsonPackage.Ident("Marshal"), "(x)") 705 g.P("}") 706 g.P() 707 708 g.P("func (x *ListValue) UnmarshalJSON(b []byte) error {") 709 g.P(" return ", protojsonPackage.Ident("Unmarshal"), "(b, x)") 710 g.P("}") 711 g.P() 712 713 case genid.Value_message_fullname: 714 g.P("// NewValue constructs a Value from a general-purpose Go interface.") 715 g.P("//") 716 g.P("// ╔════════════════════════╤════════════════════════════════════════════╗") 717 g.P("// ║ Go type │ Conversion ║") 718 g.P("// ╠════════════════════════╪════════════════════════════════════════════╣") 719 g.P("// ║ nil │ stored as NullValue ║") 720 g.P("// ║ bool │ stored as BoolValue ║") 721 g.P("// ║ int, int32, int64 │ stored as NumberValue ║") 722 g.P("// ║ uint, uint32, uint64 │ stored as NumberValue ║") 723 g.P("// ║ float32, float64 │ stored as NumberValue ║") 724 g.P("// ║ string │ stored as StringValue; must be valid UTF-8 ║") 725 g.P("// ║ []byte │ stored as StringValue; base64-encoded ║") 726 g.P("// ║ map[string]interface{} │ stored as StructValue ║") 727 g.P("// ║ []interface{} │ stored as ListValue ║") 728 g.P("// ╚════════════════════════╧════════════════════════════════════════════╝") 729 g.P("//") 730 g.P("// When converting an int64 or uint64 to a NumberValue, numeric precision loss") 731 g.P("// is possible since they are stored as a float64.") 732 g.P("func NewValue(v interface{}) (*Value, error) {") 733 g.P(" switch v := v.(type) {") 734 g.P(" case nil:") 735 g.P(" return NewNullValue(), nil") 736 g.P(" case bool:") 737 g.P(" return NewBoolValue(v), nil") 738 g.P(" case int:") 739 g.P(" return NewNumberValue(float64(v)), nil") 740 g.P(" case int32:") 741 g.P(" return NewNumberValue(float64(v)), nil") 742 g.P(" case int64:") 743 g.P(" return NewNumberValue(float64(v)), nil") 744 g.P(" case uint:") 745 g.P(" return NewNumberValue(float64(v)), nil") 746 g.P(" case uint32:") 747 g.P(" return NewNumberValue(float64(v)), nil") 748 g.P(" case uint64:") 749 g.P(" return NewNumberValue(float64(v)), nil") 750 g.P(" case float32:") 751 g.P(" return NewNumberValue(float64(v)), nil") 752 g.P(" case float64:") 753 g.P(" return NewNumberValue(float64(v)), nil") 754 g.P(" case string:") 755 g.P(" if !", utf8Package.Ident("ValidString"), "(v) {") 756 g.P(" return nil, ", protoimplPackage.Ident("X"), ".NewError(\"invalid UTF-8 in string: %q\", v)") 757 g.P(" }") 758 g.P(" return NewStringValue(v), nil") 759 g.P(" case []byte:") 760 g.P(" s := ", base64Package.Ident("StdEncoding"), ".EncodeToString(v)") 761 g.P(" return NewStringValue(s), nil") 762 g.P(" case map[string]interface{}:") 763 g.P(" v2, err := NewStruct(v)") 764 g.P(" if err != nil {") 765 g.P(" return nil, err") 766 g.P(" }") 767 g.P(" return NewStructValue(v2), nil") 768 g.P(" case []interface{}:") 769 g.P(" v2, err := NewList(v)") 770 g.P(" if err != nil {") 771 g.P(" return nil, err") 772 g.P(" }") 773 g.P(" return NewListValue(v2), nil") 774 g.P(" default:") 775 g.P(" return nil, ", protoimplPackage.Ident("X"), ".NewError(\"invalid type: %T\", v)") 776 g.P(" }") 777 g.P("}") 778 g.P() 779 780 g.P("// NewNullValue constructs a new null Value.") 781 g.P("func NewNullValue() *Value {") 782 g.P(" return &Value{Kind: &Value_NullValue{NullValue: NullValue_NULL_VALUE}}") 783 g.P("}") 784 g.P() 785 786 g.P("// NewBoolValue constructs a new boolean Value.") 787 g.P("func NewBoolValue(v bool) *Value {") 788 g.P(" return &Value{Kind: &Value_BoolValue{BoolValue: v}}") 789 g.P("}") 790 g.P() 791 792 g.P("// NewNumberValue constructs a new number Value.") 793 g.P("func NewNumberValue(v float64) *Value {") 794 g.P(" return &Value{Kind: &Value_NumberValue{NumberValue: v}}") 795 g.P("}") 796 g.P() 797 798 g.P("// NewStringValue constructs a new string Value.") 799 g.P("func NewStringValue(v string) *Value {") 800 g.P(" return &Value{Kind: &Value_StringValue{StringValue: v}}") 801 g.P("}") 802 g.P() 803 804 g.P("// NewStructValue constructs a new struct Value.") 805 g.P("func NewStructValue(v *Struct) *Value {") 806 g.P(" return &Value{Kind: &Value_StructValue{StructValue: v}}") 807 g.P("}") 808 g.P() 809 810 g.P("// NewListValue constructs a new list Value.") 811 g.P("func NewListValue(v *ListValue) *Value {") 812 g.P(" return &Value{Kind: &Value_ListValue{ListValue: v}}") 813 g.P("}") 814 g.P() 815 816 g.P("// AsInterface converts x to a general-purpose Go interface.") 817 g.P("//") 818 g.P("// Calling Value.MarshalJSON and \"encoding/json\".Marshal on this output produce") 819 g.P("// semantically equivalent JSON (assuming no errors occur).") 820 g.P("//") 821 g.P("// Floating-point values (i.e., \"NaN\", \"Infinity\", and \"-Infinity\") are") 822 g.P("// converted as strings to remain compatible with MarshalJSON.") 823 g.P("func (x *Value) AsInterface() interface{} {") 824 g.P(" switch v := x.GetKind().(type) {") 825 g.P(" case *Value_NumberValue:") 826 g.P(" if v != nil {") 827 g.P(" switch {") 828 g.P(" case ", mathPackage.Ident("IsNaN"), "(v.NumberValue):") 829 g.P(" return \"NaN\"") 830 g.P(" case ", mathPackage.Ident("IsInf"), "(v.NumberValue, +1):") 831 g.P(" return \"Infinity\"") 832 g.P(" case ", mathPackage.Ident("IsInf"), "(v.NumberValue, -1):") 833 g.P(" return \"-Infinity\"") 834 g.P(" default:") 835 g.P(" return v.NumberValue") 836 g.P(" }") 837 g.P(" }") 838 g.P(" case *Value_StringValue:") 839 g.P(" if v != nil {") 840 g.P(" return v.StringValue") 841 g.P(" }") 842 g.P(" case *Value_BoolValue:") 843 g.P(" if v != nil {") 844 g.P(" return v.BoolValue") 845 g.P(" }") 846 g.P(" case *Value_StructValue:") 847 g.P(" if v != nil {") 848 g.P(" return v.StructValue.AsMap()") 849 g.P(" }") 850 g.P(" case *Value_ListValue:") 851 g.P(" if v != nil {") 852 g.P(" return v.ListValue.AsSlice()") 853 g.P(" }") 854 g.P(" }") 855 g.P(" return nil") 856 g.P("}") 857 g.P() 858 859 g.P("func (x *Value) MarshalJSON() ([]byte, error) {") 860 g.P(" return ", protojsonPackage.Ident("Marshal"), "(x)") 861 g.P("}") 862 g.P() 863 864 g.P("func (x *Value) UnmarshalJSON(b []byte) error {") 865 g.P(" return ", protojsonPackage.Ident("Unmarshal"), "(b, x)") 866 g.P("}") 867 g.P() 868 869 case genid.FieldMask_message_fullname: 870 g.P("// New constructs a field mask from a list of paths and verifies that") 871 g.P("// each one is valid according to the specified message type.") 872 g.P("func New(m ", protoPackage.Ident("Message"), ", paths ...string) (*FieldMask, error) {") 873 g.P(" x := new(FieldMask)") 874 g.P(" return x, x.Append(m, paths...)") 875 g.P("}") 876 g.P() 877 878 g.P("// Union returns the union of all the paths in the input field masks.") 879 g.P("func Union(mx *FieldMask, my *FieldMask, ms ...*FieldMask) *FieldMask {") 880 g.P(" var out []string") 881 g.P(" out = append(out, mx.GetPaths()...)") 882 g.P(" out = append(out, my.GetPaths()...)") 883 g.P(" for _, m := range ms {") 884 g.P(" out = append(out, m.GetPaths()...)") 885 g.P(" }") 886 g.P(" return &FieldMask{Paths: normalizePaths(out)}") 887 g.P("}") 888 g.P() 889 890 g.P("// Intersect returns the intersection of all the paths in the input field masks.") 891 g.P("func Intersect(mx *FieldMask, my *FieldMask, ms ...*FieldMask) *FieldMask {") 892 g.P(" var ss1, ss2 []string // reused buffers for performance") 893 g.P(" intersect := func(out, in []string) []string {") 894 g.P(" ss1 = normalizePaths(append(ss1[:0], in...))") 895 g.P(" ss2 = normalizePaths(append(ss2[:0], out...))") 896 g.P(" out = out[:0]") 897 g.P(" for i1, i2 := 0, 0; i1 < len(ss1) && i2 < len(ss2); {") 898 g.P(" switch s1, s2 := ss1[i1], ss2[i2]; {") 899 g.P(" case hasPathPrefix(s1, s2):") 900 g.P(" out = append(out, s1)") 901 g.P(" i1++") 902 g.P(" case hasPathPrefix(s2, s1):") 903 g.P(" out = append(out, s2)") 904 g.P(" i2++") 905 g.P(" case lessPath(s1, s2):") 906 g.P(" i1++") 907 g.P(" case lessPath(s2, s1):") 908 g.P(" i2++") 909 g.P(" }") 910 g.P(" }") 911 g.P(" return out") 912 g.P(" }") 913 g.P() 914 g.P(" out := Union(mx, my, ms...).GetPaths()") 915 g.P(" out = intersect(out, mx.GetPaths())") 916 g.P(" out = intersect(out, my.GetPaths())") 917 g.P(" for _, m := range ms {") 918 g.P(" out = intersect(out, m.GetPaths())") 919 g.P(" }") 920 g.P(" return &FieldMask{Paths: normalizePaths(out)}") 921 g.P("}") 922 g.P() 923 924 g.P("// IsValid reports whether all the paths are syntactically valid and") 925 g.P("// refer to known fields in the specified message type.") 926 g.P("// It reports false for a nil FieldMask.") 927 g.P("func (x *FieldMask) IsValid(m ", protoPackage.Ident("Message"), ") bool {") 928 g.P(" paths := x.GetPaths()") 929 g.P(" return x != nil && numValidPaths(m, paths) == len(paths)") 930 g.P("}") 931 g.P() 932 933 g.P("// Append appends a list of paths to the mask and verifies that each one") 934 g.P("// is valid according to the specified message type.") 935 g.P("// An invalid path is not appended and breaks insertion of subsequent paths.") 936 g.P("func (x *FieldMask) Append(m ", protoPackage.Ident("Message"), ", paths ...string) error {") 937 g.P(" numValid := numValidPaths(m, paths)") 938 g.P(" x.Paths = append(x.Paths, paths[:numValid]...)") 939 g.P(" paths = paths[numValid:]") 940 g.P(" if len(paths) > 0 {") 941 g.P(" name := m.ProtoReflect().Descriptor().FullName()") 942 g.P(" return ", protoimplPackage.Ident("X"), ".NewError(\"invalid path %q for message %q\", paths[0], name)") 943 g.P(" }") 944 g.P(" return nil") 945 g.P("}") 946 g.P() 947 948 g.P("func numValidPaths(m ", protoPackage.Ident("Message"), ", paths []string) int {") 949 g.P(" md0 := m.ProtoReflect().Descriptor()") 950 g.P(" for i, path := range paths {") 951 g.P(" md := md0") 952 g.P(" if !rangeFields(path, func(field string) bool {") 953 g.P(" // Search the field within the message.") 954 g.P(" if md == nil {") 955 g.P(" return false // not within a message") 956 g.P(" }") 957 g.P(" fd := md.Fields().ByName(", protoreflectPackage.Ident("Name"), "(field))") 958 g.P(" // The real field name of a group is the message name.") 959 g.P(" if fd == nil {") 960 g.P(" gd := md.Fields().ByName(", protoreflectPackage.Ident("Name"), "(", stringsPackage.Ident("ToLower"), "(field)))") 961 g.P(" if gd != nil && gd.Kind() == ", protoreflectPackage.Ident("GroupKind"), " && string(gd.Message().Name()) == field {") 962 g.P(" fd = gd") 963 g.P(" }") 964 g.P(" } else if fd.Kind() == ", protoreflectPackage.Ident("GroupKind"), " && string(fd.Message().Name()) != field {") 965 g.P(" fd = nil") 966 g.P(" }") 967 g.P(" if fd == nil {") 968 g.P(" return false // message has does not have this field") 969 g.P(" }") 970 g.P() 971 g.P(" // Identify the next message to search within.") 972 g.P(" md = fd.Message() // may be nil") 973 g.P() 974 g.P(" // Repeated fields are only allowed at the last position.") 975 g.P(" if fd.IsList() || fd.IsMap() {") 976 g.P(" md = nil") 977 g.P(" }") 978 g.P() 979 g.P(" return true") 980 g.P(" }) {") 981 g.P(" return i") 982 g.P(" }") 983 g.P(" }") 984 g.P(" return len(paths)") 985 g.P("}") 986 g.P() 987 988 g.P("// Normalize converts the mask to its canonical form where all paths are sorted") 989 g.P("// and redundant paths are removed.") 990 g.P("func (x *FieldMask) Normalize() {") 991 g.P(" x.Paths = normalizePaths(x.Paths)") 992 g.P("}") 993 g.P() 994 g.P("func normalizePaths(paths []string) []string {") 995 g.P(" ", sortPackage.Ident("Slice"), "(paths, func(i, j int) bool {") 996 g.P(" return lessPath(paths[i], paths[j])") 997 g.P(" })") 998 g.P() 999 g.P(" // Elide any path that is a prefix match on the previous.") 1000 g.P(" out := paths[:0]") 1001 g.P(" for _, path := range paths {") 1002 g.P(" if len(out) > 0 && hasPathPrefix(path, out[len(out)-1]) {") 1003 g.P(" continue") 1004 g.P(" }") 1005 g.P(" out = append(out, path)") 1006 g.P(" }") 1007 g.P(" return out") 1008 g.P("}") 1009 g.P() 1010 1011 g.P("// hasPathPrefix is like strings.HasPrefix, but further checks for either") 1012 g.P("// an exact matche or that the prefix is delimited by a dot.") 1013 g.P("func hasPathPrefix(path, prefix string) bool {") 1014 g.P(" return ", stringsPackage.Ident("HasPrefix"), "(path, prefix) && (len(path) == len(prefix) || path[len(prefix)] == '.')") 1015 g.P("}") 1016 g.P() 1017 1018 g.P("// lessPath is a lexicographical comparison where dot is specially treated") 1019 g.P("// as the smallest symbol.") 1020 g.P("func lessPath(x, y string) bool {") 1021 g.P(" for i := 0; i < len(x) && i < len(y); i++ {") 1022 g.P(" if x[i] != y[i] {") 1023 g.P(" return (x[i] - '.') < (y[i] - '.')") 1024 g.P(" }") 1025 g.P(" }") 1026 g.P(" return len(x) < len(y)") 1027 g.P("}") 1028 g.P() 1029 1030 g.P("// rangeFields is like strings.Split(path, \".\"), but avoids allocations by") 1031 g.P("// iterating over each field in place and calling a iterator function.") 1032 g.P("func rangeFields(path string, f func(field string) bool) bool {") 1033 g.P(" for {") 1034 g.P(" var field string") 1035 g.P(" if i := ", stringsPackage.Ident("IndexByte"), "(path, '.'); i >= 0 {") 1036 g.P(" field, path = path[:i], path[i:]") 1037 g.P(" } else {") 1038 g.P(" field, path = path, \"\"") 1039 g.P(" }") 1040 g.P() 1041 g.P(" if !f(field) {") 1042 g.P(" return false") 1043 g.P(" }") 1044 g.P() 1045 g.P(" if len(path) == 0 {") 1046 g.P(" return true") 1047 g.P(" }") 1048 g.P(" path = ", stringsPackage.Ident("TrimPrefix"), "(path, \".\")") 1049 g.P(" }") 1050 g.P("}") 1051 g.P() 1052 1053 case genid.BoolValue_message_fullname, 1054 genid.Int32Value_message_fullname, 1055 genid.Int64Value_message_fullname, 1056 genid.UInt32Value_message_fullname, 1057 genid.UInt64Value_message_fullname, 1058 genid.FloatValue_message_fullname, 1059 genid.DoubleValue_message_fullname, 1060 genid.StringValue_message_fullname, 1061 genid.BytesValue_message_fullname: 1062 funcName := strings.TrimSuffix(m.GoIdent.GoName, "Value") 1063 typeName := strings.ToLower(funcName) 1064 switch typeName { 1065 case "float": 1066 typeName = "float32" 1067 case "double": 1068 typeName = "float64" 1069 case "bytes": 1070 typeName = "[]byte" 1071 } 1072 1073 g.P("// ", funcName, " stores v in a new ", m.GoIdent, " and returns a pointer to it.") 1074 g.P("func ", funcName, "(v ", typeName, ") *", m.GoIdent, " {") 1075 g.P(" return &", m.GoIdent, "{Value: v}") 1076 g.P("}") 1077 g.P() 1078 } 1079} 1080