blob: fcf6a4fe6e996c69193f4f7b3c73d4bf225580b3 [file] [log] [blame]
Rob Pikeaf82b4e2010-04-30 15:19:25 -07001// Go support for Protocol Buffers - Google's data interchange format
2//
3// Copyright 2010 Google Inc. All rights reserved.
4// http://code.google.com/p/goprotobuf/
5//
6// Redistribution and use in source and binary forms, with or without
7// modification, are permitted provided that the following conditions are
8// met:
9//
10// * Redistributions of source code must retain the above copyright
11// notice, this list of conditions and the following disclaimer.
12// * Redistributions in binary form must reproduce the above
13// copyright notice, this list of conditions and the following disclaimer
14// in the documentation and/or other materials provided with the
15// distribution.
16// * Neither the name of Google Inc. nor the names of its
17// contributors may be used to endorse or promote products derived from
18// this software without specific prior written permission.
19//
20// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
32/*
33 The code generator for the plugin for the Google protocol buffer compiler.
34 It generates Go code from the protocol buffer description files read by the
35 main routine.
Rob Pikeaf82b4e2010-04-30 15:19:25 -070036*/
37package generator
38
39import (
40 "bytes"
41 "fmt"
42 "log"
43 "os"
Rob Pike87af39e2010-07-19 10:48:02 -070044 "path"
David Symonds79eae332010-10-16 11:33:20 +110045 "strconv"
Rob Pikeaf82b4e2010-04-30 15:19:25 -070046 "strings"
Rob Pikeaf82b4e2010-04-30 15:19:25 -070047
48 "goprotobuf.googlecode.com/hg/proto"
49 plugin "goprotobuf.googlecode.com/hg/compiler/plugin"
50 descriptor "goprotobuf.googlecode.com/hg/compiler/descriptor"
51)
52
53// A Plugin provides functionality to add to the output during Go code generation,
54// such as to produce RPC stubs.
55type Plugin interface {
56 // Name identifies the plugin.
Rob Pikec9e7d972010-06-10 10:30:22 -070057 Name() string
58 // Init is called once after data structures are built but before
59 // code generation begins.
60 Init(g *Generator)
61 // Generate produces the code generated by the plugin for this file,
62 // except for the imports, by calling the generator's methods P, In, and Out.
63 Generate(file *FileDescriptor)
Rob Pikeaf82b4e2010-04-30 15:19:25 -070064 // GenerateImports produces the import declarations for this file.
Rob Pikec9e7d972010-06-10 10:30:22 -070065 // It is called after Generate.
66 GenerateImports(file *FileDescriptor)
Rob Pikeaf82b4e2010-04-30 15:19:25 -070067}
68
69var plugins []Plugin
70
71// RegisterPlugin installs a (second-order) plugin to be run when the Go output is generated.
72// It is typically called during initialization.
73func RegisterPlugin(p Plugin) {
David Symondscc7142e2010-11-06 14:37:15 +110074 plugins = append(plugins, p)
Rob Pikeaf82b4e2010-04-30 15:19:25 -070075}
76
77// Each type we import as a protocol buffer (other than FileDescriptorProto) needs
78// a pointer to the FileDescriptorProto that represents it. These types achieve that
79// wrapping by placing each Proto inside a struct with the pointer to its File. The
80// structs have the same names as their contents, with "Proto" removed.
81// FileDescriptor is used to store the things that it points to.
82
83// The file and package name method are common to messages and enums.
84type common struct {
85 File *descriptor.FileDescriptorProto // File this object comes from.
86}
87
88// PackageName is name in the package clause in the generated file.
89func (c *common) PackageName() string { return uniquePackageOf(c.File) }
90
91// Descriptor represents a protocol buffer message.
92type Descriptor struct {
93 common
94 *descriptor.DescriptorProto
95 parent *Descriptor // The containing message, if any.
96 nested []*Descriptor // Inner messages, if any.
97 ext []*ExtensionDescriptor // Extensions, if any.
98 typename []string // Cached typename vector.
99}
100
101// TypeName returns the elements of the dotted type name.
102// The package name is not part of this name.
103func (d *Descriptor) TypeName() []string {
104 if d.typename != nil {
105 return d.typename
106 }
107 n := 0
108 for parent := d; parent != nil; parent = parent.parent {
109 n++
110 }
111 s := make([]string, n, n)
112 for parent := d; parent != nil; parent = parent.parent {
113 n--
114 s[n] = proto.GetString(parent.Name)
115 }
116 d.typename = s
117 return s
118}
119
120// EnumDescriptor describes an enum. If it's at top level, its parent will be nil.
121// Otherwise it will be the descriptor of the message in which it is defined.
122type EnumDescriptor struct {
123 common
124 *descriptor.EnumDescriptorProto
125 parent *Descriptor // The containing message, if any.
126 typename []string // Cached typename vector.
127}
128
129// TypeName returns the elements of the dotted type name.
130// The package name is not part of this name.
131func (e *EnumDescriptor) TypeName() (s []string) {
132 if e.typename != nil {
133 return e.typename
134 }
135 name := proto.GetString(e.Name)
136 if e.parent == nil {
137 s = make([]string, 1)
138 } else {
139 pname := e.parent.TypeName()
140 s = make([]string, len(pname)+1)
141 copy(s, pname)
142 }
143 s[len(s)-1] = name
144 e.typename = s
145 return s
146}
147
148// Everything but the last element of the full type name, CamelCased.
149// The values of type Foo.Bar are call Foo_value1... not Foo_Bar_value1... .
150func (e *EnumDescriptor) prefix() string {
151 typeName := e.TypeName()
152 ccPrefix := CamelCaseSlice(typeName[0:len(typeName)-1]) + "_"
153 if e.parent == nil {
154 // If the enum is not part of a message, the prefix is just the type name.
155 ccPrefix = CamelCase(*e.Name) + "_"
156 }
157 return ccPrefix
158}
159
160// The integer value of the named constant in this enumerated type.
161func (e *EnumDescriptor) integerValueAsString(name string) string {
162 for _, c := range e.Value {
163 if proto.GetString(c.Name) == name {
164 return fmt.Sprint(proto.GetInt32(c.Number))
165 }
166 }
167 log.Exit("cannot find value for enum constant")
168 return ""
169}
170
171// ExtensionDescriptor desribes an extension. If it's at top level, its parent will be nil.
172// Otherwise it will be the descriptor of the message in which it is defined.
173type ExtensionDescriptor struct {
174 common
175 *descriptor.FieldDescriptorProto
Rob Pikec9e7d972010-06-10 10:30:22 -0700176 parent *Descriptor // The containing message, if any.
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700177}
178
179// TypeName returns the elements of the dotted type name.
180// The package name is not part of this name.
181func (e *ExtensionDescriptor) TypeName() (s []string) {
182 name := proto.GetString(e.Name)
183 if e.parent == nil {
184 // top-level extension
185 s = make([]string, 1)
186 } else {
187 pname := e.parent.TypeName()
188 s = make([]string, len(pname)+1)
189 copy(s, pname)
190 }
191 s[len(s)-1] = name
192 return s
193}
194
195// FileDescriptor describes an protocol buffer descriptor file (.proto).
196// It includes slices of all the messages and enums defined within it.
197// Those slices are constructed by WrapTypes.
198type FileDescriptor struct {
199 *descriptor.FileDescriptorProto
Rob Pikec9e7d972010-06-10 10:30:22 -0700200 desc []*Descriptor // All the messages defined in this file.
201 enum []*EnumDescriptor // All the enums defined in this file.
202 ext []*ExtensionDescriptor // All the top-level extensions defined in this file.
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700203}
204
205// PackageName is the package name we'll use in the generated code to refer to this file.
206func (d *FileDescriptor) PackageName() string { return uniquePackageOf(d.FileDescriptorProto) }
207
208// The package named defined in the input for this file, possibly dotted.
Rob Pikec9e7d972010-06-10 10:30:22 -0700209// If the file does not define a package, use the base of the file name.
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700210func (d *FileDescriptor) originalPackageName() string {
Rob Pikec9e7d972010-06-10 10:30:22 -0700211 // Does the file have a package clause?
212 pkg := proto.GetString(d.Package)
213 if pkg != "" {
214 return pkg
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700215 }
Rob Pikec9e7d972010-06-10 10:30:22 -0700216 // Use the file base name.
217 return BaseName(proto.GetString(d.Name))
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700218}
219
220// Object is an interface abstracting the abilities shared by enums and messages.
221type Object interface {
222 PackageName() string // The name we use in our output (a_b_c), possibly renamed for uniqueness.
223 TypeName() []string
224}
225
226// Each package name we generate must be unique. The package we're generating
227// gets its own name but every other package must have a unqiue name that does
228// not conflict in the code we generate. These names are chosen globally (although
229// they don't have to be, it simplifies things to do them globally).
230func uniquePackageOf(fd *descriptor.FileDescriptorProto) string {
231 s, ok := uniquePackageName[fd]
232 if !ok {
233 log.Exit("internal error: no package name defined for", proto.GetString(fd.Name))
234 }
235 return s
236}
237
238// Generator is the type whose methods generate the output, stored in the associated response structure.
239type Generator struct {
David Symondsf90e3382010-05-05 10:53:44 +1000240 *bytes.Buffer
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700241
242 Request *plugin.CodeGeneratorRequest // The input.
243 Response *plugin.CodeGeneratorResponse // The output.
244
Rob Pikec9e7d972010-06-10 10:30:22 -0700245 Param map[string]string // Command-line parameters.
246 ImportPrefix string // String to prefix to imported package file names.
247 ImportMap map[string]string // Mapping from import name to generated name
248
249 ProtoPkg string // The name under which we import the library's package proto.
250
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700251 packageName string // What we're calling ourselves.
252 allFiles []*FileDescriptor // All files in the tree
253 genFiles []*FileDescriptor // Those files we will generate output for.
254 file *FileDescriptor // The file we are compiling now.
David Symondsf90e3382010-05-05 10:53:44 +1000255 usedPackages map[string]bool // Names of packages used in current file.
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700256 typeNameToObject map[string]Object // Key is a fully-qualified name in input syntax.
257 indent string
258}
259
260// New creates a new generator and allocates the request and response protobufs.
261func New() *Generator {
262 g := new(Generator)
David Symondsf90e3382010-05-05 10:53:44 +1000263 g.Buffer = new(bytes.Buffer)
David Symondsb0127532010-11-09 11:10:46 +1100264 g.Request = new(plugin.CodeGeneratorRequest)
265 g.Response = new(plugin.CodeGeneratorResponse)
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700266 return g
267}
268
269// Error reports a problem, including an os.Error, and exits the program.
270func (g *Generator) Error(err os.Error, msgs ...string) {
271 s := strings.Join(msgs, " ") + ":" + err.String()
Rob Pike5194c512010-10-14 13:02:16 -0700272 log.Println("protoc-gen-go: error:", s)
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700273 g.Response.Error = proto.String(s)
274 os.Exit(1)
275}
276
277// Fail reports a problem and exits the program.
278func (g *Generator) Fail(msgs ...string) {
279 s := strings.Join(msgs, " ")
Rob Pike5194c512010-10-14 13:02:16 -0700280 log.Println("protoc-gen-go: error:", s)
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700281 g.Response.Error = proto.String(s)
282 os.Exit(1)
283}
284
Rob Pikec9e7d972010-06-10 10:30:22 -0700285// CommandLineParameters breaks the comma-separated list of key=value pairs
286// in the parameter (a member of the request protobuf) into a key/value map.
287// It then sets file name mappings defined by those entries.
288func (g *Generator) CommandLineParameters(parameter string) {
289 g.Param = make(map[string]string)
Rob Pike53385442010-06-30 22:22:43 -0700290 for _, p := range strings.Split(parameter, ",", -1) {
Rob Pikec9e7d972010-06-10 10:30:22 -0700291 if i := strings.Index(p, "="); i < 0 {
292 g.Param[p] = ""
293 } else {
294 g.Param[p[0:i]] = p[i+1:]
295 }
296 }
297
298 g.ImportMap = make(map[string]string)
299 for k, v := range g.Param {
300 if k == "import_prefix" {
301 g.ImportPrefix = v
302 } else if len(k) > 0 && k[0] == 'M' {
303 g.ImportMap[k[1:]] = v
304 }
305 }
306}
307
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700308// DefaultPackageName returns the package name printed for the object.
309// If its file is in a different package, it returns the package name we're using for this file, plus ".".
310// Otherwise it returns the empty string.
311func (g *Generator) DefaultPackageName(obj Object) string {
312 pkg := obj.PackageName()
313 if pkg == g.packageName {
314 return ""
315 }
316 return pkg + "."
317}
318
319// For each input file, the unique package name to use, underscored.
320var uniquePackageName = make(map[*descriptor.FileDescriptorProto]string)
Rob Pikec9e7d972010-06-10 10:30:22 -0700321// Package names already registered. Key is the name from the .proto file;
322// value is the name that appears in the generated code.
323var pkgNamesInUse = make(map[string]bool)
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700324
Rob Pikec9e7d972010-06-10 10:30:22 -0700325// Create and remember a guaranteed unique package name for this file descriptor.
326// Pkg is the candidate name. If f is nil, it's a builtin package like "proto" and
327// has no file descriptor.
328func RegisterUniquePackageName(pkg string, f *FileDescriptor) string {
David Symonds79eae332010-10-16 11:33:20 +1100329 for i, orig := 1, pkg; pkgNamesInUse[pkg]; i++ {
Rob Pikec9e7d972010-06-10 10:30:22 -0700330 // It's a duplicate; must rename.
David Symonds79eae332010-10-16 11:33:20 +1100331 pkg = orig + strconv.Itoa(i)
Rob Pikec9e7d972010-06-10 10:30:22 -0700332 }
333 // Install it.
334 pkgNamesInUse[pkg] = true
335 pkg = strings.Map(DotToUnderscore, pkg)
336 if f != nil {
337 uniquePackageName[f.FileDescriptorProto] = pkg
338 }
339 return pkg
340}
341
342// SetPackageNames sets the package name for this run.
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700343// The package name must agree across all files being generated.
344// It also defines unique package names for all imported files.
345func (g *Generator) SetPackageNames() {
Rob Pikec9e7d972010-06-10 10:30:22 -0700346 // Register the name for this package. It will be the first name
347 // registered so is guaranteed to be unmodified.
348 pkg := g.genFiles[0].originalPackageName()
349 g.packageName = RegisterUniquePackageName(pkg, g.genFiles[0])
350 // Register the proto package name. It might collide with the
351 // name of a package we import.
352 g.ProtoPkg = RegisterUniquePackageName("proto", nil)
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700353 for _, f := range g.genFiles {
Rob Pikec9e7d972010-06-10 10:30:22 -0700354 thisPkg := f.originalPackageName()
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700355 if thisPkg != pkg {
356 g.Fail("inconsistent package names:", thisPkg, pkg)
357 }
358 }
359AllFiles:
360 for _, f := range g.allFiles {
361 for _, genf := range g.genFiles {
362 if f == genf {
363 // In this package already.
364 uniquePackageName[f.FileDescriptorProto] = g.packageName
365 continue AllFiles
366 }
367 }
Rob Pikec9e7d972010-06-10 10:30:22 -0700368 RegisterUniquePackageName(f.originalPackageName(), f)
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700369 }
370}
371
372// WrapTypes walks the incoming data, wrapping DescriptorProtos, EnumDescriptorProtos
373// and FileDescriptorProtos into file-referenced objects within the Generator.
374// It also creates the list of files to generate and so should be called before GenerateAllFiles.
375func (g *Generator) WrapTypes() {
376 g.allFiles = make([]*FileDescriptor, len(g.Request.ProtoFile))
377 for i, f := range g.Request.ProtoFile {
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700378 // We must wrap the descriptors before we wrap the enums
379 descs := wrapDescriptors(f)
380 g.buildNestedDescriptors(descs)
381 enums := wrapEnumDescriptors(f, descs)
382 exts := wrapExtensions(f)
383 g.allFiles[i] = &FileDescriptor{
384 FileDescriptorProto: f,
385 desc: descs,
386 enum: enums,
387 ext: exts,
388 }
389 }
390
391 g.genFiles = make([]*FileDescriptor, len(g.Request.FileToGenerate))
392FindFiles:
393 for i, fileName := range g.Request.FileToGenerate {
394 // Search the list. This algorithm is n^2 but n is tiny.
395 for _, file := range g.allFiles {
396 if fileName == proto.GetString(file.Name) {
397 g.genFiles[i] = file
398 continue FindFiles
399 }
400 }
401 g.Fail("could not find file named", fileName)
402 }
403 g.Response.File = make([]*plugin.CodeGeneratorResponse_File, len(g.genFiles))
404}
405
406// Scan the descriptors in this file. For each one, build the slice of nested descriptors
407func (g *Generator) buildNestedDescriptors(descs []*Descriptor) {
408 for _, desc := range descs {
409 if len(desc.NestedType) != 0 {
410 desc.nested = make([]*Descriptor, len(desc.NestedType))
411 n := 0
412 for _, nest := range descs {
413 if nest.parent == desc {
414 desc.nested[n] = nest
415 n++
416 }
417 }
418 if n != len(desc.NestedType) {
419 g.Fail("internal error: nesting failure for", proto.GetString(desc.Name))
420 }
421 }
422 }
423}
424
425// Construct the Descriptor and add it to the slice
426func addDescriptor(sl []*Descriptor, desc *descriptor.DescriptorProto, parent *Descriptor, file *descriptor.FileDescriptorProto) []*Descriptor {
427 d := &Descriptor{common{File: file}, desc, parent, nil, nil, nil}
428
429 d.ext = make([]*ExtensionDescriptor, len(desc.Extension))
430 for i, field := range desc.Extension {
431 d.ext[i] = &ExtensionDescriptor{common{File: file}, field, d}
432 }
433
David Symondscc7142e2010-11-06 14:37:15 +1100434 return append(sl, d)
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700435}
436
437// Return a slice of all the Descriptors defined within this file
438func wrapDescriptors(file *descriptor.FileDescriptorProto) []*Descriptor {
439 sl := make([]*Descriptor, 0, len(file.MessageType)+10)
440 for _, desc := range file.MessageType {
441 sl = wrapThisDescriptor(sl, desc, nil, file)
442 }
443 return sl
444}
445
446// Wrap this Descriptor, recursively
447func wrapThisDescriptor(sl []*Descriptor, desc *descriptor.DescriptorProto, parent *Descriptor, file *descriptor.FileDescriptorProto) []*Descriptor {
448 sl = addDescriptor(sl, desc, parent, file)
449 me := sl[len(sl)-1]
450 for _, nested := range desc.NestedType {
451 sl = wrapThisDescriptor(sl, nested, me, file)
452 }
453 return sl
454}
455
456// Construct the EnumDescriptor and add it to the slice
457func addEnumDescriptor(sl []*EnumDescriptor, desc *descriptor.EnumDescriptorProto, parent *Descriptor, file *descriptor.FileDescriptorProto) []*EnumDescriptor {
David Symondscc7142e2010-11-06 14:37:15 +1100458 return append(sl, &EnumDescriptor{common{File: file}, desc, parent, nil})
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700459}
460
461// Return a slice of all the EnumDescriptors defined within this file
462func wrapEnumDescriptors(file *descriptor.FileDescriptorProto, descs []*Descriptor) []*EnumDescriptor {
463 sl := make([]*EnumDescriptor, 0, len(file.EnumType)+10)
David Symonds5256cf62010-06-27 10:33:42 +1000464 // Top-level enums.
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700465 for _, enum := range file.EnumType {
466 sl = addEnumDescriptor(sl, enum, nil, file)
467 }
David Symonds5256cf62010-06-27 10:33:42 +1000468 // Enums within messages. Enums within embedded messages appear in the outer-most message.
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700469 for _, nested := range descs {
David Symonds5256cf62010-06-27 10:33:42 +1000470 for _, enum := range nested.EnumType {
471 sl = addEnumDescriptor(sl, enum, nested, file)
472 }
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700473 }
474 return sl
475}
476
477// Return a slice of all the top-level ExtensionDescriptors defined within this file.
478func wrapExtensions(file *descriptor.FileDescriptorProto) []*ExtensionDescriptor {
479 sl := make([]*ExtensionDescriptor, len(file.Extension))
480 for i, field := range file.Extension {
481 sl[i] = &ExtensionDescriptor{common{File: file}, field, nil}
482 }
483 return sl
484}
485
Rob Pikec9e7d972010-06-10 10:30:22 -0700486// BuildTypeNameMap builds the map from fully qualified type names to objects.
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700487// The key names for the map come from the input data, which puts a period at the beginning.
488// It should be called after SetPackageNames and before GenerateAllFiles.
489func (g *Generator) BuildTypeNameMap() {
490 g.typeNameToObject = make(map[string]Object)
491 for _, f := range g.allFiles {
Rob Pikec9e7d972010-06-10 10:30:22 -0700492 // The names in this loop are defined by the proto world, not us, so the
493 // package name may be empty. If so, the dotted package name of X will
494 // be ".X"; otherwise it will be ".pkg.X".
495 dottedPkg := "." + proto.GetString(f.Package)
496 if dottedPkg != "." {
497 dottedPkg += "."
498 }
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700499 for _, enum := range f.enum {
500 name := dottedPkg + dottedSlice(enum.TypeName())
501 g.typeNameToObject[name] = enum
502 }
503 for _, desc := range f.desc {
504 name := dottedPkg + dottedSlice(desc.TypeName())
505 g.typeNameToObject[name] = desc
506 }
507 }
508}
509
510// ObjectNamed, given a fully-qualified input type name as it appears in the input data,
511// returns the descriptor for the message or enum with that name.
512func (g *Generator) ObjectNamed(typeName string) Object {
513 f, ok := g.typeNameToObject[typeName]
514 if !ok {
515 g.Fail("can't find object with type", typeName)
516 }
517 return f
518}
519
520// P prints the arguments to the generated output. It handles strings and int32s, plus
521// handling indirections because they may be *string, etc.
522func (g *Generator) P(str ...interface{}) {
523 g.WriteString(g.indent)
524 for _, v := range str {
525 switch s := v.(type) {
526 case string:
527 g.WriteString(s)
528 case *string:
529 g.WriteString(*s)
Rob Pikec9e7d972010-06-10 10:30:22 -0700530 case bool:
531 g.WriteString(fmt.Sprintf("%t", s))
532 case *bool:
533 g.WriteString(fmt.Sprintf("%t", *s))
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700534 case *int32:
535 g.WriteString(fmt.Sprintf("%d", *s))
Rob Pikec9e7d972010-06-10 10:30:22 -0700536 case float64:
537 g.WriteString(fmt.Sprintf("%g", s))
538 case *float64:
539 g.WriteString(fmt.Sprintf("%g", *s))
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700540 default:
541 g.Fail(fmt.Sprintf("unknown type in printer: %T", v))
542 }
543 }
544 g.WriteByte('\n')
545}
546
547// In Indents the output one tab stop.
548func (g *Generator) In() { g.indent += "\t" }
549
550// Out unindents the output one tab stop.
551func (g *Generator) Out() {
552 if len(g.indent) > 0 {
553 g.indent = g.indent[1:]
554 }
555}
556
557// GenerateAllFiles generates the output for all the files we're outputting.
558func (g *Generator) GenerateAllFiles() {
Rob Pikec9e7d972010-06-10 10:30:22 -0700559 // Initialize the plugins
560 for _, p := range plugins {
561 p.Init(g)
562 }
563 // Generate the output.
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700564 for i, file := range g.genFiles {
565 g.Reset()
566 g.generate(file)
David Symondsb0127532010-11-09 11:10:46 +1100567 g.Response.File[i] = new(plugin.CodeGeneratorResponse_File)
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700568 g.Response.File[i].Name = proto.String(goFileName(*file.Name))
569 g.Response.File[i].Content = proto.String(g.String())
570 }
571}
572
573// Run all the plugins associated with the file.
574func (g *Generator) runPlugins(file *FileDescriptor) {
575 for _, p := range plugins {
Rob Pikec9e7d972010-06-10 10:30:22 -0700576 p.Generate(file)
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700577 }
578}
579
580
581// FileOf return the FileDescriptor for this FileDescriptorProto.
582func (g *Generator) FileOf(fd *descriptor.FileDescriptorProto) *FileDescriptor {
583 for _, file := range g.allFiles {
584 if file.FileDescriptorProto == fd {
585 return file
586 }
587 }
588 g.Fail("could not find file in table:", proto.GetString(fd.Name))
589 return nil
590}
591
592// Fill the response protocol buffer with the generated output for all the files we're
593// supposed to generate.
594func (g *Generator) generate(file *FileDescriptor) {
595 g.file = g.FileOf(file.FileDescriptorProto)
David Symondsf90e3382010-05-05 10:53:44 +1000596 g.usedPackages = make(map[string]bool)
597
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700598 for _, enum := range g.file.enum {
599 g.generateEnum(enum)
600 }
601 for _, desc := range g.file.desc {
602 g.generateMessage(desc)
603 }
604 for _, ext := range g.file.ext {
605 g.generateExtension(ext)
606 }
607 g.generateInitFunction()
David Symondsf90e3382010-05-05 10:53:44 +1000608
Rob Pikec9e7d972010-06-10 10:30:22 -0700609 // Run the plugins before the imports so we know which imports are necessary.
610 g.runPlugins(file)
611
David Symondsf90e3382010-05-05 10:53:44 +1000612 // Generate header and imports last, though they appear first in the output.
613 rem := g.Buffer
614 g.Buffer = new(bytes.Buffer)
615 g.generateHeader()
616 g.generateImports()
617 g.Write(rem.Bytes())
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700618}
619
620// Generate the header, including package definition and imports
621func (g *Generator) generateHeader() {
622 g.P("// Code generated by protoc-gen-go from ", Quote(*g.file.Name))
623 g.P("// DO NOT EDIT!")
624 g.P()
625 g.P("package ", g.file.PackageName())
626 g.P()
627}
628
629// Generate the header, including package definition and imports
630func (g *Generator) generateImports() {
Rob Pikec9e7d972010-06-10 10:30:22 -0700631 // We almost always need a proto import. Rather than computing when we
632 // do, which is tricky when there's a plugin, just import it and
David Symonds4fee3b12010-11-11 10:00:13 +1100633 // reference it later. The same argument applies to the os package.
Rob Pike809831a2010-06-16 10:10:58 -0700634 g.P("import " + g.ProtoPkg + " " + Quote(g.ImportPrefix+"goprotobuf.googlecode.com/hg/proto"))
David Symonds4fee3b12010-11-11 10:00:13 +1100635 g.P(`import "os"`)
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700636 for _, s := range g.file.Dependency {
637 // Need to find the descriptor for this file
638 for _, fd := range g.allFiles {
Rob Pikec9e7d972010-06-10 10:30:22 -0700639 // Do not import our own package.
640 if fd.PackageName() == g.packageName {
641 continue
642 }
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700643 if proto.GetString(fd.Name) == s {
644 filename := goFileName(s)
Rob Pikec9e7d972010-06-10 10:30:22 -0700645 if substitution, ok := g.ImportMap[s]; ok {
646 filename = substitution
647 }
648 filename = g.ImportPrefix + filename
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700649 if strings.HasSuffix(filename, ".go") {
Rob Pikec9e7d972010-06-10 10:30:22 -0700650 filename = filename[0 : len(filename)-3]
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700651 }
David Symondsf90e3382010-05-05 10:53:44 +1000652 if _, ok := g.usedPackages[fd.PackageName()]; ok {
653 g.P("import ", fd.PackageName(), " ", Quote(filename))
654 } else {
Rob Pike5194c512010-10-14 13:02:16 -0700655 log.Println("protoc-gen-go: discarding unused import:", filename)
David Symondsf90e3382010-05-05 10:53:44 +1000656 }
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700657 break
658 }
659 }
660 }
661 g.P()
662 // TODO: may need to worry about uniqueness across plugins
663 for _, p := range plugins {
Rob Pikec9e7d972010-06-10 10:30:22 -0700664 p.GenerateImports(g.file)
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700665 g.P()
666 }
David Symonds4fee3b12010-11-11 10:00:13 +1100667 g.P("// Reference proto & os imports to suppress error if it's not otherwise used.")
Rob Pikec9e7d972010-06-10 10:30:22 -0700668 g.P("var _ = ", g.ProtoPkg, ".GetString")
David Symonds4fee3b12010-11-11 10:00:13 +1100669 g.P("var _ os.Error")
Rob Pikec9e7d972010-06-10 10:30:22 -0700670 g.P()
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700671}
672
673// Generate the enum definitions for this EnumDescriptor.
674func (g *Generator) generateEnum(enum *EnumDescriptor) {
675 // The full type name
676 typeName := enum.TypeName()
677 // The full type name, CamelCased.
678 ccTypeName := CamelCaseSlice(typeName)
679 ccPrefix := enum.prefix()
680 g.P("type ", ccTypeName, " int32")
681 g.P("const (")
682 g.In()
683 for _, e := range enum.Value {
684 g.P(ccPrefix+*e.Name, " = ", e.Number)
685 }
686 g.Out()
687 g.P(")")
688 g.P("var ", ccTypeName, "_name = map[int32] string {")
689 g.In()
Rob Pikec9e7d972010-06-10 10:30:22 -0700690 generated := make(map[int32]bool) // avoid duplicate values
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700691 for _, e := range enum.Value {
692 duplicate := ""
693 if _, present := generated[*e.Number]; present {
694 duplicate = "// Duplicate value: "
695 }
696 g.P(duplicate, e.Number, ": ", Quote(*e.Name), ",")
697 generated[*e.Number] = true
698 }
699 g.Out()
700 g.P("}")
701 g.P("var ", ccTypeName, "_value = map[string] int32 {")
702 g.In()
703 for _, e := range enum.Value {
704 g.P(Quote(*e.Name), ": ", e.Number, ",")
705 }
706 g.Out()
707 g.P("}")
708 g.P("func New", ccTypeName, "(x int32) *", ccTypeName, " {")
709 g.In()
710 g.P("e := ", ccTypeName, "(x)")
711 g.P("return &e")
712 g.Out()
713 g.P("}")
714 g.P()
715}
716
717// The tag is a string like "PB(varint,2,opt,name=fieldname,def=7)" that
718// identifies details of the field for the protocol buffer marshaling and unmarshaling
719// code. The fields are:
720// wire encoding
721// protocol tag number
722// opt,req,rep for optional, required, or repeated
723// name= the original declared name
724// enum= the name of the enum type if it is an enum-typed field.
725// def= string representation of the default value, if any.
726// The default value must be in a representation that can be used at run-time
727// to generate the default value. Thus bools become 0 and 1, for instance.
728func (g *Generator) goTag(field *descriptor.FieldDescriptorProto, wiretype string) string {
729 optrepreq := ""
730 switch {
731 case isOptional(field):
732 optrepreq = "opt"
733 case isRequired(field):
734 optrepreq = "req"
735 case isRepeated(field):
736 optrepreq = "rep"
737 }
738 defaultValue := proto.GetString(field.DefaultValue)
739 if defaultValue != "" {
740 switch *field.Type {
741 case descriptor.FieldDescriptorProto_TYPE_BOOL:
742 if defaultValue == "true" {
743 defaultValue = "1"
744 } else {
745 defaultValue = "0"
746 }
747 case descriptor.FieldDescriptorProto_TYPE_STRING,
748 descriptor.FieldDescriptorProto_TYPE_BYTES:
749 // Protect frogs.
750 defaultValue = Quote(defaultValue)
751 // Don't need the quotes
752 defaultValue = defaultValue[1 : len(defaultValue)-1]
753 case descriptor.FieldDescriptorProto_TYPE_ENUM:
754 // For enums we need to provide the integer constant.
755 obj := g.ObjectNamed(proto.GetString(field.TypeName))
756 enum, ok := obj.(*EnumDescriptor)
757 if !ok {
758 g.Fail("enum type inconsistent for", CamelCaseSlice(obj.TypeName()))
759 }
760 defaultValue = enum.integerValueAsString(defaultValue)
761 }
762 defaultValue = ",def=" + defaultValue
763 }
764 enum := ""
765 if *field.Type == descriptor.FieldDescriptorProto_TYPE_ENUM {
766 obj := g.ObjectNamed(proto.GetString(field.TypeName))
767 enum = ",enum=" + obj.PackageName() + "." + CamelCaseSlice(obj.TypeName())
768 }
769 name := proto.GetString(field.Name)
770 if name == CamelCase(name) {
771 name = ""
772 } else {
773 name = ",name=" + name
774 }
775 return Quote(fmt.Sprintf("PB(%s,%d,%s%s%s%s)",
776 wiretype,
777 proto.GetInt32(field.Number),
778 optrepreq,
779 name,
780 enum,
781 defaultValue))
782}
783
784func needsStar(typ descriptor.FieldDescriptorProto_Type) bool {
785 switch typ {
786 case descriptor.FieldDescriptorProto_TYPE_GROUP:
787 return false
788 case descriptor.FieldDescriptorProto_TYPE_MESSAGE:
789 return false
790 case descriptor.FieldDescriptorProto_TYPE_BYTES:
791 return false
792 }
793 return true
794}
795
796// TypeName is the printed name appropriate for an item. If the object is in the current file,
797// TypeName drops the package name and underscores the rest.
798// Otherwise the object is from another package; and the result is the underscored
799// package name followed by the item name.
800// The result always has an initial capital.
801func (g *Generator) TypeName(obj Object) string {
802 return g.DefaultPackageName(obj) + CamelCaseSlice(obj.TypeName())
803}
804
805// TypeNameWithPackage is like TypeName, but always includes the package
806// name even if the object is in our own package.
807func (g *Generator) TypeNameWithPackage(obj Object) string {
808 return obj.PackageName() + CamelCaseSlice(obj.TypeName())
809}
810
811// GoType returns a string representing the type name, and the wire type
812func (g *Generator) GoType(message *Descriptor, field *descriptor.FieldDescriptorProto) (typ string, wire string) {
813 // TODO: Options.
814 switch *field.Type {
815 case descriptor.FieldDescriptorProto_TYPE_DOUBLE:
816 typ, wire = "float64", "fixed64"
817 case descriptor.FieldDescriptorProto_TYPE_FLOAT:
818 typ, wire = "float32", "fixed32"
819 case descriptor.FieldDescriptorProto_TYPE_INT64:
820 typ, wire = "int64", "varint"
821 case descriptor.FieldDescriptorProto_TYPE_UINT64:
822 typ, wire = "uint64", "varint"
823 case descriptor.FieldDescriptorProto_TYPE_INT32:
824 typ, wire = "int32", "varint"
825 case descriptor.FieldDescriptorProto_TYPE_UINT32:
826 typ, wire = "uint32", "varint"
827 case descriptor.FieldDescriptorProto_TYPE_FIXED64:
828 typ, wire = "uint64", "fixed64"
829 case descriptor.FieldDescriptorProto_TYPE_FIXED32:
830 typ, wire = "uint32", "fixed32"
831 case descriptor.FieldDescriptorProto_TYPE_BOOL:
832 typ, wire = "bool", "varint"
833 case descriptor.FieldDescriptorProto_TYPE_STRING:
834 typ, wire = "string", "bytes"
835 case descriptor.FieldDescriptorProto_TYPE_GROUP:
836 desc := g.ObjectNamed(proto.GetString(field.TypeName))
837 typ, wire = "*"+g.TypeName(desc), "group"
838 case descriptor.FieldDescriptorProto_TYPE_MESSAGE:
839 desc := g.ObjectNamed(proto.GetString(field.TypeName))
840 typ, wire = "*"+g.TypeName(desc), "bytes"
841 case descriptor.FieldDescriptorProto_TYPE_BYTES:
842 typ, wire = "[]byte", "bytes"
843 case descriptor.FieldDescriptorProto_TYPE_ENUM:
844 desc := g.ObjectNamed(proto.GetString(field.TypeName))
845 typ, wire = g.TypeName(desc), "varint"
846 case descriptor.FieldDescriptorProto_TYPE_SFIXED32:
847 typ, wire = "int32", "fixed32"
848 case descriptor.FieldDescriptorProto_TYPE_SFIXED64:
849 typ, wire = "int64", "fixed64"
850 case descriptor.FieldDescriptorProto_TYPE_SINT32:
851 typ, wire = "int32", "zigzag32"
852 case descriptor.FieldDescriptorProto_TYPE_SINT64:
853 typ, wire = "int64", "zigzag64"
854 default:
855 g.Fail("unknown type for", proto.GetString(field.Name))
856 }
857 if isRepeated(field) {
858 typ = "[]" + typ
859 } else if needsStar(*field.Type) {
860 typ = "*" + typ
861 }
862 return
863}
864
David Symondsf90e3382010-05-05 10:53:44 +1000865func (g *Generator) RecordTypeUse(t string) {
866 if obj, ok := g.typeNameToObject[t]; ok {
867 g.usedPackages[obj.PackageName()] = true
868 }
869}
870
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700871// Generate the type and default constant definitions for this Descriptor.
872func (g *Generator) generateMessage(message *Descriptor) {
873 // The full type name
874 typeName := message.TypeName()
875 // The full type name, CamelCased.
876 ccTypeName := CamelCaseSlice(typeName)
877
878 g.P("type ", ccTypeName, " struct {")
879 g.In()
880 for _, field := range message.Field {
881 fieldname := CamelCase(*field.Name)
882 typename, wiretype := g.GoType(message, field)
883 tag := g.goTag(field, wiretype)
884 g.P(fieldname, "\t", typename, "\t", tag)
David Symondsf90e3382010-05-05 10:53:44 +1000885 g.RecordTypeUse(proto.GetString(field.TypeName))
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700886 }
887 if len(message.ExtensionRange) > 0 {
888 g.P("XXX_extensions\t\tmap[int32][]byte")
889 }
890 g.P("XXX_unrecognized\t[]byte")
891 g.Out()
892 g.P("}")
893
Rob Pikec6d8e4a2010-07-28 15:34:32 -0700894 // Reset function
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700895 g.P("func (this *", ccTypeName, ") Reset() {")
896 g.In()
897 g.P("*this = ", ccTypeName, "{}")
898 g.Out()
899 g.P("}")
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700900
901 // Extension support methods
902 if len(message.ExtensionRange) > 0 {
David Symonds4fee3b12010-11-11 10:00:13 +1100903 // message_set_wire_format only makes sense when extensions are defined.
904 if opts := message.Options; opts != nil && proto.GetBool(opts.MessageSetWireFormat) {
905 g.P()
906 g.P("func (this *", ccTypeName, ") Marshal() ([]byte, os.Error) {")
907 g.In()
908 g.P("return ", g.ProtoPkg, ".MarshalMessageSet(this.ExtensionMap())")
909 g.Out()
910 g.P("}")
911 g.P("func (this *", ccTypeName, ") Unmarshal(buf []byte) os.Error {")
912 g.In()
913 g.P("return ", g.ProtoPkg, ".UnmarshalMessageSet(buf, this.ExtensionMap())")
914 g.Out()
915 g.P("}")
916 g.P("// ensure ", ccTypeName, " satisfies proto.Marshaler and proto.Unmarshaler")
917 g.P("var _ ", g.ProtoPkg, ".Marshaler = (*", ccTypeName, ")(nil)")
918 g.P("var _ ", g.ProtoPkg, ".Unmarshaler = (*", ccTypeName, ")(nil)")
919 }
920
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700921 g.P()
Rob Pikec9e7d972010-06-10 10:30:22 -0700922 g.P("var extRange_", ccTypeName, " = []", g.ProtoPkg, ".ExtensionRange{")
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700923 g.In()
924 for _, r := range message.ExtensionRange {
Rob Pikec9e7d972010-06-10 10:30:22 -0700925 end := fmt.Sprint(*r.End - 1) // make range inclusive on both ends
926 g.P(g.ProtoPkg+".ExtensionRange{", r.Start, ", ", end, "},")
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700927 }
928 g.Out()
929 g.P("}")
Rob Pikec9e7d972010-06-10 10:30:22 -0700930 g.P("func (*", ccTypeName, ") ExtensionRangeArray() []", g.ProtoPkg, ".ExtensionRange {")
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700931 g.In()
932 g.P("return extRange_", ccTypeName)
933 g.Out()
934 g.P("}")
935 g.P("func (this *", ccTypeName, ") ExtensionMap() map[int32][]byte {")
936 g.In()
937 g.P("if this.XXX_extensions == nil {")
938 g.In()
939 g.P("this.XXX_extensions = make(map[int32][]byte)")
940 g.Out()
941 g.P("}")
942 g.P("return this.XXX_extensions")
943 g.Out()
944 g.P("}")
945 }
946
947 // Default constants
948 for _, field := range message.Field {
949 def := proto.GetString(field.DefaultValue)
950 if def == "" {
951 continue
952 }
953 fieldname := "Default_" + ccTypeName + "_" + CamelCase(*field.Name)
954 typename, _ := g.GoType(message, field)
955 if typename[0] == '*' {
956 typename = typename[1:]
957 }
958 kind := "const "
959 switch {
960 case typename == "bool":
961 case typename == "string":
962 def = Quote(def)
963 case typename == "[]byte":
964 def = "[]byte(" + Quote(def) + ")"
965 kind = "var "
966 case *field.Type == descriptor.FieldDescriptorProto_TYPE_ENUM:
967 // Must be an enum. Need to construct the prefixed name.
968 obj := g.ObjectNamed(proto.GetString(field.TypeName))
969 enum, ok := obj.(*EnumDescriptor)
970 if !ok {
Rob Pike5194c512010-10-14 13:02:16 -0700971 log.Println("don't know how to generate constant for", fieldname)
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700972 continue
973 }
Rob Pike87af39e2010-07-19 10:48:02 -0700974 def = g.DefaultPackageName(enum) + enum.prefix() + def
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700975 }
976 g.P(kind, fieldname, " ", typename, " = ", def)
977 }
978 g.P()
979
980 for _, ext := range message.ext {
981 g.generateExtension(ext)
982 }
983}
984
985func (g *Generator) generateExtension(ext *ExtensionDescriptor) {
986 // The full type name
987 typeName := ext.TypeName()
988 // Each scope of the extension is individually CamelCased, and all are joined with "_" with an "E_" prefix.
989 for i, s := range typeName {
990 typeName[i] = CamelCase(s)
991 }
992 ccTypeName := "E_" + strings.Join(typeName, "_")
993
994 extendedType := "*" + g.TypeName(g.ObjectNamed(*ext.Extendee))
995 field := ext.FieldDescriptorProto
996 fieldType, wireType := g.GoType(ext.parent, field)
997 tag := g.goTag(field, wireType)
David Symondsf90e3382010-05-05 10:53:44 +1000998 g.RecordTypeUse(*ext.Extendee)
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700999
Rob Pikec9e7d972010-06-10 10:30:22 -07001000 g.P("var ", ccTypeName, " = &", g.ProtoPkg, ".ExtensionDesc{")
Rob Pikeaf82b4e2010-04-30 15:19:25 -07001001 g.In()
1002 g.P("ExtendedType: (", extendedType, ")(nil),")
1003 g.P("ExtensionType: (", fieldType, ")(nil),")
1004 g.P("Field: ", field.Number, ",")
1005 g.P("Tag: ", tag, ",")
1006
1007 g.Out()
1008 g.P("}")
1009 g.P()
1010}
1011
1012func (g *Generator) generateInitFunction() {
1013 g.P("func init() {")
1014 g.In()
1015 for _, enum := range g.file.enum {
1016 g.generateEnumRegistration(enum)
1017 }
1018 g.Out()
1019 g.P("}")
1020}
1021
1022func (g *Generator) generateEnumRegistration(enum *EnumDescriptor) {
1023 pkg := g.packageName + "." // We always print the full package name here.
1024 // The full type name
1025 typeName := enum.TypeName()
1026 // The full type name, CamelCased.
1027 ccTypeName := CamelCaseSlice(typeName)
Rob Pikec9e7d972010-06-10 10:30:22 -07001028 g.P(g.ProtoPkg+".RegisterEnum(", Quote(pkg+ccTypeName), ", ", ccTypeName+"_name, ", ccTypeName+"_value)")
Rob Pikeaf82b4e2010-04-30 15:19:25 -07001029}
1030
1031// And now lots of helper functions.
1032
Rob Pike2c7bafc2010-06-10 16:07:14 -07001033// Is c an ASCII lower-case letter?
1034func isASCIILower(c byte) bool {
1035 return 'a' <= c && c <= 'z'
1036}
1037
1038// Is c an ASCII digit?
1039func isASCIIDigit(c byte) bool {
1040 return '0' <= c && c <= '9'
1041}
1042
1043// CamelCase returns the CamelCased name.
1044// If there is an interior underscore followed by a lower case letter,
1045// drop the underscore and convert the letter to upper case.
1046// There is a remote possibility of this rewrite causing a name collision,
1047// but it's so remote we're prepared to pretend it's nonexistent - since the
1048// C++ generator lowercases names, it's extremely unlikely to have two fields
1049// with different capitalizations.
1050// In short, _my_field_name_2 becomes XMyFieldName2.
1051func CamelCase(s string) string {
1052 if s == "" {
1053 return ""
1054 }
1055 t := make([]byte, 0, 32)
1056 oneC := make([]byte, 1)
1057 i := 0
1058 if s[0] == '_' {
1059 // Need a capital letter; drop the '_'.
1060 oneC[0] = 'X'
1061 t = bytes.Add(t, oneC)
1062 i++
1063 }
1064 // Invariant: if the next letter is lower case, it must be converted
1065 // to upper case.
1066 // That is, we process a word at a time, where words are marked by _ or
1067 // upper case letter. Digits are treated as words.
1068 for ; i < len(s); i++ {
1069 c := s[i]
1070 oneC[0] = c
1071 if c == '_' && i+1 < len(s) && isASCIILower(s[i+1]) {
1072 continue // Skip the underscore in s.
1073 }
1074 if isASCIIDigit(c) {
1075 t = bytes.Add(t, oneC)
Rob Pikeaf82b4e2010-04-30 15:19:25 -07001076 continue
1077 }
Rob Pike2c7bafc2010-06-10 16:07:14 -07001078 // Assume we have a letter now - if not, it's a bogus identifier.
1079 // The next word is a sequence of characters that must start upper case.
1080 if isASCIILower(c) {
1081 oneC[0] ^= ' ' // Make it a capital letter.
1082 }
1083 t = bytes.Add(t, oneC) // Guaranteed not lower case.
1084 // Accept lower case sequence that follows.
1085 for i+1 < len(s) && isASCIILower(s[i+1]) {
1086 i++
1087 oneC[0] = s[i]
1088 t = bytes.Add(t, oneC)
Rob Pikeaf82b4e2010-04-30 15:19:25 -07001089 }
1090 }
Rob Pike2c7bafc2010-06-10 16:07:14 -07001091 return string(t)
Rob Pikeaf82b4e2010-04-30 15:19:25 -07001092}
1093
1094// CamelCaseSlice is like CamelCase, but the argument is a slice of strings to
1095// be joined with "_".
1096func CamelCaseSlice(elem []string) string { return CamelCase(strings.Join(elem, "_")) }
1097
1098// dottedSlice turns a sliced name into a dotted name.
1099func dottedSlice(elem []string) string { return strings.Join(elem, ".") }
1100
1101// Quote returns a Go-source quoted string representation of s.
1102func Quote(s string) string { return fmt.Sprintf("%q", s) }
1103
1104// Given a .proto file name, return the output name for the generated Go program.
1105func goFileName(name string) string {
Rob Pike87af39e2010-07-19 10:48:02 -07001106 ext := path.Ext(name)
1107 if ext == ".proto" || ext == ".protodevel" {
1108 name = name[0 : len(name)-len(ext)]
Rob Pikeaf82b4e2010-04-30 15:19:25 -07001109 }
1110 return name + ".pb.go"
1111}
1112
1113// Is this field optional?
1114func isOptional(field *descriptor.FieldDescriptorProto) bool {
1115 return field.Label != nil && *field.Label == descriptor.FieldDescriptorProto_LABEL_OPTIONAL
1116}
1117
1118// Is this field required?
1119func isRequired(field *descriptor.FieldDescriptorProto) bool {
1120 return field.Label != nil && *field.Label == descriptor.FieldDescriptorProto_LABEL_REQUIRED
1121}
1122
1123// Is this field repeated?
1124func isRepeated(field *descriptor.FieldDescriptorProto) bool {
1125 return field.Label != nil && *field.Label == descriptor.FieldDescriptorProto_LABEL_REPEATED
1126}
1127
1128// DotToUnderscore is the mapping function used to generate Go names from package names,
Rob Pikec9e7d972010-06-10 10:30:22 -07001129// which can be dotted in the input .proto file. It maps dots to underscores.
1130// Because we also get here from package names generated from file names, it also maps
1131// minus signs to underscores.
Rob Pikeaf82b4e2010-04-30 15:19:25 -07001132func DotToUnderscore(rune int) int {
Rob Pikec9e7d972010-06-10 10:30:22 -07001133 switch rune {
1134 case '.', '-':
Rob Pikeaf82b4e2010-04-30 15:19:25 -07001135 return '_'
1136 }
1137 return rune
1138}
Rob Pikec9e7d972010-06-10 10:30:22 -07001139
1140// BaseName returns the last path element of the name, with the last dotted suffix removed.
1141func BaseName(name string) string {
1142 // First, find the last element
1143 if i := strings.LastIndex(name, "/"); i >= 0 {
1144 name = name[i+1:]
1145 }
1146 // Now drop the suffix
1147 if i := strings.LastIndex(name, "."); i >= 0 {
1148 name = name[0:i]
1149 }
1150 return name
1151}