blob: 1b89bedabd92cc413ebaeba402f389473225df42 [file] [log] [blame]
Scott Baker105df152020-04-13 15:55:14 -07001// Copyright 2018 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
5// Package protoreflect provides interfaces to dynamically manipulate messages.
6//
7// This package includes type descriptors which describe the structure of types
8// defined in proto source files and value interfaces which provide the
9// ability to examine and manipulate the contents of messages.
10//
11//
12// Protocol Buffer Descriptors
13//
14// Protobuf descriptors (e.g., EnumDescriptor or MessageDescriptor)
15// are immutable objects that represent protobuf type information.
16// They are wrappers around the messages declared in descriptor.proto.
17// Protobuf descriptors alone lack any information regarding Go types.
18//
19// Enums and messages generated by this module implement Enum and ProtoMessage,
20// where the Descriptor and ProtoReflect.Descriptor accessors respectively
21// return the protobuf descriptor for the values.
22//
23// The protobuf descriptor interfaces are not meant to be implemented by
24// user code since they might need to be extended in the future to support
25// additions to the protobuf language. Protobuf descriptors can be constructed
26// using the "google.golang.org/protobuf/reflect/protodesc" package.
27//
28//
29// Go Type Descriptors
30//
31// A type descriptor (e.g., EnumType or MessageType) is a constructor for
32// a concrete Go type that represents the associated protobuf descriptor.
33// There is commonly a one-to-one relationship between protobuf descriptors and
34// Go type descriptors, but it can potentially be a one-to-many relationship.
35//
36// Enums and messages generated by this module implement Enum and ProtoMessage,
37// where the Type and ProtoReflect.Type accessors respectively
38// return the protobuf descriptor for the values.
39//
40// The "google.golang.org/protobuf/types/dynamicpb" package can be used to
41// create Go type descriptors from protobuf descriptors.
42//
43//
44// Value Interfaces
45//
46// The Enum and Message interfaces provide a reflective view over an
47// enum or message instance. For enums, it provides the ability to retrieve
48// the enum value number for any concrete enum type. For messages, it provides
49// the ability to access or manipulate fields of the message.
50//
51// To convert a proto.Message to a protoreflect.Message, use the
52// former's ProtoReflect method. Since the ProtoReflect method is new to the
53// v2 message interface, it may not be present on older message implementations.
54// The "github.com/golang/protobuf/proto".MessageReflect function can be used
55// to obtain a reflective view on older messages.
56//
57//
58// Relationships
59//
60// The following diagrams demonstrate the relationships between
61// various types declared in this package.
62//
63//
64// ┌───────────────────────────────────┐
65// V │
66// ┌────────────── New(n) ─────────────┐ │
67// │ │ │
68// │ ┌──── Descriptor() ──┐ │ ┌── Number() ──┐ │
69// │ │ V V │ V │
70// ╔════════════╗ ╔════════════════╗ ╔════════╗ ╔════════════╗
71// ║ EnumType ║ ║ EnumDescriptor ║ ║ Enum ║ ║ EnumNumber ║
72// ╚════════════╝ ╚════════════════╝ ╚════════╝ ╚════════════╝
73// Λ Λ │ │
74// │ └─── Descriptor() ──┘ │
75// │ │
76// └────────────────── Type() ───────┘
77//
78// • An EnumType describes a concrete Go enum type.
79// It has an EnumDescriptor and can construct an Enum instance.
80//
81// • An EnumDescriptor describes an abstract protobuf enum type.
82//
83// • An Enum is a concrete enum instance. Generated enums implement Enum.
84//
85//
86// ┌──────────────── New() ─────────────────┐
87// │ │
88// │ ┌─── Descriptor() ─────┐ │ ┌── Interface() ───┐
89// │ │ V V │ V
90// ╔═════════════╗ ╔═══════════════════╗ ╔═════════╗ ╔══════════════╗
91// ║ MessageType ║ ║ MessageDescriptor ║ ║ Message ║ ║ ProtoMessage ║
92// ╚═════════════╝ ╚═══════════════════╝ ╚═════════╝ ╚══════════════╝
93// Λ Λ │ │ Λ │
94// │ └──── Descriptor() ────┘ │ └─ ProtoReflect() ─┘
95// │ │
96// └─────────────────── Type() ─────────┘
97//
98// • A MessageType describes a concrete Go message type.
99// It has a MessageDescriptor and can construct a Message instance.
100//
101// • A MessageDescriptor describes an abstract protobuf message type.
102//
103// • A Message is a concrete message instance. Generated messages implement
104// ProtoMessage, which can convert to/from a Message.
105//
106//
107// ┌── TypeDescriptor() ──┐ ┌───── Descriptor() ─────┐
108// │ V │ V
109// ╔═══════════════╗ ╔═════════════════════════╗ ╔═════════════════════╗
110// ║ ExtensionType ║ ║ ExtensionTypeDescriptor ║ ║ ExtensionDescriptor ║
111// ╚═══════════════╝ ╚═════════════════════════╝ ╚═════════════════════╝
112// Λ │ │ Λ │ Λ
113// └─────── Type() ───────┘ │ └─── may implement ────┘ │
114// │ │
115// └────── implements ────────┘
116//
117// • An ExtensionType describes a concrete Go implementation of an extension.
118// It has an ExtensionTypeDescriptor and can convert to/from
119// abstract Values and Go values.
120//
121// • An ExtensionTypeDescriptor is an ExtensionDescriptor
122// which also has an ExtensionType.
123//
124// • An ExtensionDescriptor describes an abstract protobuf extension field and
125// may not always be an ExtensionTypeDescriptor.
126package protoreflect
127
128import (
129 "fmt"
130 "regexp"
131 "strings"
132
133 "google.golang.org/protobuf/encoding/protowire"
134 "google.golang.org/protobuf/internal/pragma"
135)
136
137type doNotImplement pragma.DoNotImplement
138
139// ProtoMessage is the top-level interface that all proto messages implement.
140// This is declared in the protoreflect package to avoid a cyclic dependency;
141// use the proto.Message type instead, which aliases this type.
142type ProtoMessage interface{ ProtoReflect() Message }
143
144// Syntax is the language version of the proto file.
145type Syntax syntax
146
147type syntax int8 // keep exact type opaque as the int type may change
148
149const (
150 Proto2 Syntax = 2
151 Proto3 Syntax = 3
152)
153
154// IsValid reports whether the syntax is valid.
155func (s Syntax) IsValid() bool {
156 switch s {
157 case Proto2, Proto3:
158 return true
159 default:
160 return false
161 }
162}
163
164// String returns s as a proto source identifier (e.g., "proto2").
165func (s Syntax) String() string {
166 switch s {
167 case Proto2:
168 return "proto2"
169 case Proto3:
170 return "proto3"
171 default:
172 return fmt.Sprintf("<unknown:%d>", s)
173 }
174}
175
176// GoString returns s as a Go source identifier (e.g., "Proto2").
177func (s Syntax) GoString() string {
178 switch s {
179 case Proto2:
180 return "Proto2"
181 case Proto3:
182 return "Proto3"
183 default:
184 return fmt.Sprintf("Syntax(%d)", s)
185 }
186}
187
188// Cardinality determines whether a field is optional, required, or repeated.
189type Cardinality cardinality
190
191type cardinality int8 // keep exact type opaque as the int type may change
192
193// Constants as defined by the google.protobuf.Cardinality enumeration.
194const (
195 Optional Cardinality = 1 // appears zero or one times
196 Required Cardinality = 2 // appears exactly one time; invalid with Proto3
197 Repeated Cardinality = 3 // appears zero or more times
198)
199
200// IsValid reports whether the cardinality is valid.
201func (c Cardinality) IsValid() bool {
202 switch c {
203 case Optional, Required, Repeated:
204 return true
205 default:
206 return false
207 }
208}
209
210// String returns c as a proto source identifier (e.g., "optional").
211func (c Cardinality) String() string {
212 switch c {
213 case Optional:
214 return "optional"
215 case Required:
216 return "required"
217 case Repeated:
218 return "repeated"
219 default:
220 return fmt.Sprintf("<unknown:%d>", c)
221 }
222}
223
224// GoString returns c as a Go source identifier (e.g., "Optional").
225func (c Cardinality) GoString() string {
226 switch c {
227 case Optional:
228 return "Optional"
229 case Required:
230 return "Required"
231 case Repeated:
232 return "Repeated"
233 default:
234 return fmt.Sprintf("Cardinality(%d)", c)
235 }
236}
237
238// Kind indicates the basic proto kind of a field.
239type Kind kind
240
241type kind int8 // keep exact type opaque as the int type may change
242
243// Constants as defined by the google.protobuf.Field.Kind enumeration.
244const (
245 BoolKind Kind = 8
246 EnumKind Kind = 14
247 Int32Kind Kind = 5
248 Sint32Kind Kind = 17
249 Uint32Kind Kind = 13
250 Int64Kind Kind = 3
251 Sint64Kind Kind = 18
252 Uint64Kind Kind = 4
253 Sfixed32Kind Kind = 15
254 Fixed32Kind Kind = 7
255 FloatKind Kind = 2
256 Sfixed64Kind Kind = 16
257 Fixed64Kind Kind = 6
258 DoubleKind Kind = 1
259 StringKind Kind = 9
260 BytesKind Kind = 12
261 MessageKind Kind = 11
262 GroupKind Kind = 10
263)
264
265// IsValid reports whether the kind is valid.
266func (k Kind) IsValid() bool {
267 switch k {
268 case BoolKind, EnumKind,
269 Int32Kind, Sint32Kind, Uint32Kind,
270 Int64Kind, Sint64Kind, Uint64Kind,
271 Sfixed32Kind, Fixed32Kind, FloatKind,
272 Sfixed64Kind, Fixed64Kind, DoubleKind,
273 StringKind, BytesKind, MessageKind, GroupKind:
274 return true
275 default:
276 return false
277 }
278}
279
280// String returns k as a proto source identifier (e.g., "bool").
281func (k Kind) String() string {
282 switch k {
283 case BoolKind:
284 return "bool"
285 case EnumKind:
286 return "enum"
287 case Int32Kind:
288 return "int32"
289 case Sint32Kind:
290 return "sint32"
291 case Uint32Kind:
292 return "uint32"
293 case Int64Kind:
294 return "int64"
295 case Sint64Kind:
296 return "sint64"
297 case Uint64Kind:
298 return "uint64"
299 case Sfixed32Kind:
300 return "sfixed32"
301 case Fixed32Kind:
302 return "fixed32"
303 case FloatKind:
304 return "float"
305 case Sfixed64Kind:
306 return "sfixed64"
307 case Fixed64Kind:
308 return "fixed64"
309 case DoubleKind:
310 return "double"
311 case StringKind:
312 return "string"
313 case BytesKind:
314 return "bytes"
315 case MessageKind:
316 return "message"
317 case GroupKind:
318 return "group"
319 default:
320 return fmt.Sprintf("<unknown:%d>", k)
321 }
322}
323
324// GoString returns k as a Go source identifier (e.g., "BoolKind").
325func (k Kind) GoString() string {
326 switch k {
327 case BoolKind:
328 return "BoolKind"
329 case EnumKind:
330 return "EnumKind"
331 case Int32Kind:
332 return "Int32Kind"
333 case Sint32Kind:
334 return "Sint32Kind"
335 case Uint32Kind:
336 return "Uint32Kind"
337 case Int64Kind:
338 return "Int64Kind"
339 case Sint64Kind:
340 return "Sint64Kind"
341 case Uint64Kind:
342 return "Uint64Kind"
343 case Sfixed32Kind:
344 return "Sfixed32Kind"
345 case Fixed32Kind:
346 return "Fixed32Kind"
347 case FloatKind:
348 return "FloatKind"
349 case Sfixed64Kind:
350 return "Sfixed64Kind"
351 case Fixed64Kind:
352 return "Fixed64Kind"
353 case DoubleKind:
354 return "DoubleKind"
355 case StringKind:
356 return "StringKind"
357 case BytesKind:
358 return "BytesKind"
359 case MessageKind:
360 return "MessageKind"
361 case GroupKind:
362 return "GroupKind"
363 default:
364 return fmt.Sprintf("Kind(%d)", k)
365 }
366}
367
368// FieldNumber is the field number in a message.
369type FieldNumber = protowire.Number
370
371// FieldNumbers represent a list of field numbers.
372type FieldNumbers interface {
373 // Len reports the number of fields in the list.
374 Len() int
375 // Get returns the ith field number. It panics if out of bounds.
376 Get(i int) FieldNumber
377 // Has reports whether n is within the list of fields.
378 Has(n FieldNumber) bool
379
380 doNotImplement
381}
382
383// FieldRanges represent a list of field number ranges.
384type FieldRanges interface {
385 // Len reports the number of ranges in the list.
386 Len() int
387 // Get returns the ith range. It panics if out of bounds.
388 Get(i int) [2]FieldNumber // start inclusive; end exclusive
389 // Has reports whether n is within any of the ranges.
390 Has(n FieldNumber) bool
391
392 doNotImplement
393}
394
395// EnumNumber is the numeric value for an enum.
396type EnumNumber int32
397
398// EnumRanges represent a list of enum number ranges.
399type EnumRanges interface {
400 // Len reports the number of ranges in the list.
401 Len() int
402 // Get returns the ith range. It panics if out of bounds.
403 Get(i int) [2]EnumNumber // start inclusive; end inclusive
404 // Has reports whether n is within any of the ranges.
405 Has(n EnumNumber) bool
406
407 doNotImplement
408}
409
410var (
411 regexName = regexp.MustCompile(`^[_a-zA-Z][_a-zA-Z0-9]*$`)
412 regexFullName = regexp.MustCompile(`^[_a-zA-Z][_a-zA-Z0-9]*(\.[_a-zA-Z][_a-zA-Z0-9]*)*$`)
413)
414
415// Name is the short name for a proto declaration. This is not the name
416// as used in Go source code, which might not be identical to the proto name.
417type Name string // e.g., "Kind"
418
419// IsValid reports whether n is a syntactically valid name.
420// An empty name is invalid.
421func (n Name) IsValid() bool {
422 return regexName.MatchString(string(n))
423}
424
425// Names represent a list of names.
426type Names interface {
427 // Len reports the number of names in the list.
428 Len() int
429 // Get returns the ith name. It panics if out of bounds.
430 Get(i int) Name
431 // Has reports whether s matches any names in the list.
432 Has(s Name) bool
433
434 doNotImplement
435}
436
437// FullName is a qualified name that uniquely identifies a proto declaration.
438// A qualified name is the concatenation of the proto package along with the
439// fully-declared name (i.e., name of parent preceding the name of the child),
440// with a '.' delimiter placed between each Name.
441//
442// This should not have any leading or trailing dots.
443type FullName string // e.g., "google.protobuf.Field.Kind"
444
445// IsValid reports whether n is a syntactically valid full name.
446// An empty full name is invalid.
447func (n FullName) IsValid() bool {
448 return regexFullName.MatchString(string(n))
449}
450
451// Name returns the short name, which is the last identifier segment.
452// A single segment FullName is the Name itself.
453func (n FullName) Name() Name {
454 if i := strings.LastIndexByte(string(n), '.'); i >= 0 {
455 return Name(n[i+1:])
456 }
457 return Name(n)
458}
459
460// Parent returns the full name with the trailing identifier removed.
461// A single segment FullName has no parent.
462func (n FullName) Parent() FullName {
463 if i := strings.LastIndexByte(string(n), '.'); i >= 0 {
464 return n[:i]
465 }
466 return ""
467}
468
469// Append returns the qualified name appended with the provided short name.
470//
471// Invariant: n == n.Parent().Append(n.Name()) // assuming n is valid
472func (n FullName) Append(s Name) FullName {
473 if n == "" {
474 return FullName(s)
475 }
476 return n + "." + FullName(s)
477}