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