blob: 1a7ba8f2ce325a630ea75f787d5e2e360c66c67f [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"
David Symonds832b2432010-11-11 10:55:27 +110049 plugin "goprotobuf.googlecode.com/hg/compiler/plugin"
Rob Pikeaf82b4e2010-04-30 15:19:25 -070050 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
David Symonds5b7775e2010-12-01 10:09:04 +1100723// packed whether the encoding is "packed" (optional; repeated primitives only)
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700724// name= the original declared name
725// enum= the name of the enum type if it is an enum-typed field.
726// def= string representation of the default value, if any.
727// The default value must be in a representation that can be used at run-time
728// to generate the default value. Thus bools become 0 and 1, for instance.
729func (g *Generator) goTag(field *descriptor.FieldDescriptorProto, wiretype string) string {
730 optrepreq := ""
731 switch {
732 case isOptional(field):
733 optrepreq = "opt"
734 case isRequired(field):
735 optrepreq = "req"
736 case isRepeated(field):
737 optrepreq = "rep"
738 }
739 defaultValue := proto.GetString(field.DefaultValue)
740 if defaultValue != "" {
741 switch *field.Type {
742 case descriptor.FieldDescriptorProto_TYPE_BOOL:
743 if defaultValue == "true" {
744 defaultValue = "1"
745 } else {
746 defaultValue = "0"
747 }
748 case descriptor.FieldDescriptorProto_TYPE_STRING,
749 descriptor.FieldDescriptorProto_TYPE_BYTES:
750 // Protect frogs.
751 defaultValue = Quote(defaultValue)
752 // Don't need the quotes
753 defaultValue = defaultValue[1 : len(defaultValue)-1]
754 case descriptor.FieldDescriptorProto_TYPE_ENUM:
755 // For enums we need to provide the integer constant.
756 obj := g.ObjectNamed(proto.GetString(field.TypeName))
757 enum, ok := obj.(*EnumDescriptor)
758 if !ok {
759 g.Fail("enum type inconsistent for", CamelCaseSlice(obj.TypeName()))
760 }
761 defaultValue = enum.integerValueAsString(defaultValue)
762 }
763 defaultValue = ",def=" + defaultValue
764 }
765 enum := ""
766 if *field.Type == descriptor.FieldDescriptorProto_TYPE_ENUM {
767 obj := g.ObjectNamed(proto.GetString(field.TypeName))
768 enum = ",enum=" + obj.PackageName() + "." + CamelCaseSlice(obj.TypeName())
769 }
David Symonds5b7775e2010-12-01 10:09:04 +1100770 packed := ""
771 if field.Options != nil && proto.GetBool(field.Options.Packed) {
772 packed = ",packed"
773 }
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700774 name := proto.GetString(field.Name)
775 if name == CamelCase(name) {
776 name = ""
777 } else {
778 name = ",name=" + name
779 }
David Symonds5b7775e2010-12-01 10:09:04 +1100780 return Quote(fmt.Sprintf("PB(%s,%d,%s%s%s%s%s)",
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700781 wiretype,
782 proto.GetInt32(field.Number),
783 optrepreq,
David Symonds5b7775e2010-12-01 10:09:04 +1100784 packed,
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700785 name,
786 enum,
787 defaultValue))
788}
789
790func needsStar(typ descriptor.FieldDescriptorProto_Type) bool {
791 switch typ {
792 case descriptor.FieldDescriptorProto_TYPE_GROUP:
793 return false
794 case descriptor.FieldDescriptorProto_TYPE_MESSAGE:
795 return false
796 case descriptor.FieldDescriptorProto_TYPE_BYTES:
797 return false
798 }
799 return true
800}
801
802// TypeName is the printed name appropriate for an item. If the object is in the current file,
803// TypeName drops the package name and underscores the rest.
804// Otherwise the object is from another package; and the result is the underscored
805// package name followed by the item name.
806// The result always has an initial capital.
807func (g *Generator) TypeName(obj Object) string {
808 return g.DefaultPackageName(obj) + CamelCaseSlice(obj.TypeName())
809}
810
811// TypeNameWithPackage is like TypeName, but always includes the package
812// name even if the object is in our own package.
813func (g *Generator) TypeNameWithPackage(obj Object) string {
814 return obj.PackageName() + CamelCaseSlice(obj.TypeName())
815}
816
817// GoType returns a string representing the type name, and the wire type
818func (g *Generator) GoType(message *Descriptor, field *descriptor.FieldDescriptorProto) (typ string, wire string) {
819 // TODO: Options.
820 switch *field.Type {
821 case descriptor.FieldDescriptorProto_TYPE_DOUBLE:
822 typ, wire = "float64", "fixed64"
823 case descriptor.FieldDescriptorProto_TYPE_FLOAT:
824 typ, wire = "float32", "fixed32"
825 case descriptor.FieldDescriptorProto_TYPE_INT64:
826 typ, wire = "int64", "varint"
827 case descriptor.FieldDescriptorProto_TYPE_UINT64:
828 typ, wire = "uint64", "varint"
829 case descriptor.FieldDescriptorProto_TYPE_INT32:
830 typ, wire = "int32", "varint"
831 case descriptor.FieldDescriptorProto_TYPE_UINT32:
832 typ, wire = "uint32", "varint"
833 case descriptor.FieldDescriptorProto_TYPE_FIXED64:
834 typ, wire = "uint64", "fixed64"
835 case descriptor.FieldDescriptorProto_TYPE_FIXED32:
836 typ, wire = "uint32", "fixed32"
837 case descriptor.FieldDescriptorProto_TYPE_BOOL:
838 typ, wire = "bool", "varint"
839 case descriptor.FieldDescriptorProto_TYPE_STRING:
840 typ, wire = "string", "bytes"
841 case descriptor.FieldDescriptorProto_TYPE_GROUP:
842 desc := g.ObjectNamed(proto.GetString(field.TypeName))
843 typ, wire = "*"+g.TypeName(desc), "group"
844 case descriptor.FieldDescriptorProto_TYPE_MESSAGE:
845 desc := g.ObjectNamed(proto.GetString(field.TypeName))
846 typ, wire = "*"+g.TypeName(desc), "bytes"
847 case descriptor.FieldDescriptorProto_TYPE_BYTES:
848 typ, wire = "[]byte", "bytes"
849 case descriptor.FieldDescriptorProto_TYPE_ENUM:
850 desc := g.ObjectNamed(proto.GetString(field.TypeName))
851 typ, wire = g.TypeName(desc), "varint"
852 case descriptor.FieldDescriptorProto_TYPE_SFIXED32:
853 typ, wire = "int32", "fixed32"
854 case descriptor.FieldDescriptorProto_TYPE_SFIXED64:
855 typ, wire = "int64", "fixed64"
856 case descriptor.FieldDescriptorProto_TYPE_SINT32:
857 typ, wire = "int32", "zigzag32"
858 case descriptor.FieldDescriptorProto_TYPE_SINT64:
859 typ, wire = "int64", "zigzag64"
860 default:
861 g.Fail("unknown type for", proto.GetString(field.Name))
862 }
863 if isRepeated(field) {
864 typ = "[]" + typ
865 } else if needsStar(*field.Type) {
866 typ = "*" + typ
867 }
868 return
869}
870
David Symondsf90e3382010-05-05 10:53:44 +1000871func (g *Generator) RecordTypeUse(t string) {
872 if obj, ok := g.typeNameToObject[t]; ok {
873 g.usedPackages[obj.PackageName()] = true
874 }
875}
876
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700877// Generate the type and default constant definitions for this Descriptor.
878func (g *Generator) generateMessage(message *Descriptor) {
879 // The full type name
880 typeName := message.TypeName()
881 // The full type name, CamelCased.
882 ccTypeName := CamelCaseSlice(typeName)
883
884 g.P("type ", ccTypeName, " struct {")
885 g.In()
886 for _, field := range message.Field {
887 fieldname := CamelCase(*field.Name)
888 typename, wiretype := g.GoType(message, field)
889 tag := g.goTag(field, wiretype)
890 g.P(fieldname, "\t", typename, "\t", tag)
David Symondsf90e3382010-05-05 10:53:44 +1000891 g.RecordTypeUse(proto.GetString(field.TypeName))
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700892 }
893 if len(message.ExtensionRange) > 0 {
894 g.P("XXX_extensions\t\tmap[int32][]byte")
895 }
896 g.P("XXX_unrecognized\t[]byte")
897 g.Out()
898 g.P("}")
899
Rob Pikec6d8e4a2010-07-28 15:34:32 -0700900 // Reset function
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700901 g.P("func (this *", ccTypeName, ") Reset() {")
902 g.In()
903 g.P("*this = ", ccTypeName, "{}")
904 g.Out()
905 g.P("}")
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700906
907 // Extension support methods
908 if len(message.ExtensionRange) > 0 {
David Symonds4fee3b12010-11-11 10:00:13 +1100909 // message_set_wire_format only makes sense when extensions are defined.
910 if opts := message.Options; opts != nil && proto.GetBool(opts.MessageSetWireFormat) {
911 g.P()
912 g.P("func (this *", ccTypeName, ") Marshal() ([]byte, os.Error) {")
913 g.In()
914 g.P("return ", g.ProtoPkg, ".MarshalMessageSet(this.ExtensionMap())")
915 g.Out()
916 g.P("}")
917 g.P("func (this *", ccTypeName, ") Unmarshal(buf []byte) os.Error {")
918 g.In()
919 g.P("return ", g.ProtoPkg, ".UnmarshalMessageSet(buf, this.ExtensionMap())")
920 g.Out()
921 g.P("}")
922 g.P("// ensure ", ccTypeName, " satisfies proto.Marshaler and proto.Unmarshaler")
923 g.P("var _ ", g.ProtoPkg, ".Marshaler = (*", ccTypeName, ")(nil)")
924 g.P("var _ ", g.ProtoPkg, ".Unmarshaler = (*", ccTypeName, ")(nil)")
925 }
926
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700927 g.P()
Rob Pikec9e7d972010-06-10 10:30:22 -0700928 g.P("var extRange_", ccTypeName, " = []", g.ProtoPkg, ".ExtensionRange{")
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700929 g.In()
930 for _, r := range message.ExtensionRange {
Rob Pikec9e7d972010-06-10 10:30:22 -0700931 end := fmt.Sprint(*r.End - 1) // make range inclusive on both ends
932 g.P(g.ProtoPkg+".ExtensionRange{", r.Start, ", ", end, "},")
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700933 }
934 g.Out()
935 g.P("}")
Rob Pikec9e7d972010-06-10 10:30:22 -0700936 g.P("func (*", ccTypeName, ") ExtensionRangeArray() []", g.ProtoPkg, ".ExtensionRange {")
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700937 g.In()
938 g.P("return extRange_", ccTypeName)
939 g.Out()
940 g.P("}")
941 g.P("func (this *", ccTypeName, ") ExtensionMap() map[int32][]byte {")
942 g.In()
943 g.P("if this.XXX_extensions == nil {")
944 g.In()
945 g.P("this.XXX_extensions = make(map[int32][]byte)")
946 g.Out()
947 g.P("}")
948 g.P("return this.XXX_extensions")
949 g.Out()
950 g.P("}")
951 }
952
953 // Default constants
954 for _, field := range message.Field {
955 def := proto.GetString(field.DefaultValue)
956 if def == "" {
957 continue
958 }
959 fieldname := "Default_" + ccTypeName + "_" + CamelCase(*field.Name)
960 typename, _ := g.GoType(message, field)
961 if typename[0] == '*' {
962 typename = typename[1:]
963 }
964 kind := "const "
965 switch {
966 case typename == "bool":
967 case typename == "string":
968 def = Quote(def)
969 case typename == "[]byte":
970 def = "[]byte(" + Quote(def) + ")"
971 kind = "var "
972 case *field.Type == descriptor.FieldDescriptorProto_TYPE_ENUM:
973 // Must be an enum. Need to construct the prefixed name.
974 obj := g.ObjectNamed(proto.GetString(field.TypeName))
975 enum, ok := obj.(*EnumDescriptor)
976 if !ok {
Rob Pike5194c512010-10-14 13:02:16 -0700977 log.Println("don't know how to generate constant for", fieldname)
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700978 continue
979 }
Rob Pike87af39e2010-07-19 10:48:02 -0700980 def = g.DefaultPackageName(enum) + enum.prefix() + def
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700981 }
982 g.P(kind, fieldname, " ", typename, " = ", def)
983 }
984 g.P()
985
986 for _, ext := range message.ext {
987 g.generateExtension(ext)
988 }
989}
990
991func (g *Generator) generateExtension(ext *ExtensionDescriptor) {
992 // The full type name
993 typeName := ext.TypeName()
994 // Each scope of the extension is individually CamelCased, and all are joined with "_" with an "E_" prefix.
995 for i, s := range typeName {
996 typeName[i] = CamelCase(s)
997 }
998 ccTypeName := "E_" + strings.Join(typeName, "_")
999
1000 extendedType := "*" + g.TypeName(g.ObjectNamed(*ext.Extendee))
1001 field := ext.FieldDescriptorProto
1002 fieldType, wireType := g.GoType(ext.parent, field)
1003 tag := g.goTag(field, wireType)
David Symondsf90e3382010-05-05 10:53:44 +10001004 g.RecordTypeUse(*ext.Extendee)
Rob Pikeaf82b4e2010-04-30 15:19:25 -07001005
Rob Pikec9e7d972010-06-10 10:30:22 -07001006 g.P("var ", ccTypeName, " = &", g.ProtoPkg, ".ExtensionDesc{")
Rob Pikeaf82b4e2010-04-30 15:19:25 -07001007 g.In()
1008 g.P("ExtendedType: (", extendedType, ")(nil),")
1009 g.P("ExtensionType: (", fieldType, ")(nil),")
1010 g.P("Field: ", field.Number, ",")
1011 g.P("Tag: ", tag, ",")
1012
1013 g.Out()
1014 g.P("}")
1015 g.P()
1016}
1017
1018func (g *Generator) generateInitFunction() {
1019 g.P("func init() {")
1020 g.In()
1021 for _, enum := range g.file.enum {
1022 g.generateEnumRegistration(enum)
1023 }
1024 g.Out()
1025 g.P("}")
1026}
1027
1028func (g *Generator) generateEnumRegistration(enum *EnumDescriptor) {
1029 pkg := g.packageName + "." // We always print the full package name here.
1030 // The full type name
1031 typeName := enum.TypeName()
1032 // The full type name, CamelCased.
1033 ccTypeName := CamelCaseSlice(typeName)
Rob Pikec9e7d972010-06-10 10:30:22 -07001034 g.P(g.ProtoPkg+".RegisterEnum(", Quote(pkg+ccTypeName), ", ", ccTypeName+"_name, ", ccTypeName+"_value)")
Rob Pikeaf82b4e2010-04-30 15:19:25 -07001035}
1036
1037// And now lots of helper functions.
1038
Rob Pike2c7bafc2010-06-10 16:07:14 -07001039// Is c an ASCII lower-case letter?
1040func isASCIILower(c byte) bool {
1041 return 'a' <= c && c <= 'z'
1042}
1043
1044// Is c an ASCII digit?
1045func isASCIIDigit(c byte) bool {
1046 return '0' <= c && c <= '9'
1047}
1048
1049// CamelCase returns the CamelCased name.
1050// If there is an interior underscore followed by a lower case letter,
1051// drop the underscore and convert the letter to upper case.
1052// There is a remote possibility of this rewrite causing a name collision,
1053// but it's so remote we're prepared to pretend it's nonexistent - since the
1054// C++ generator lowercases names, it's extremely unlikely to have two fields
1055// with different capitalizations.
1056// In short, _my_field_name_2 becomes XMyFieldName2.
1057func CamelCase(s string) string {
1058 if s == "" {
1059 return ""
1060 }
1061 t := make([]byte, 0, 32)
1062 oneC := make([]byte, 1)
1063 i := 0
1064 if s[0] == '_' {
1065 // Need a capital letter; drop the '_'.
1066 oneC[0] = 'X'
1067 t = bytes.Add(t, oneC)
1068 i++
1069 }
1070 // Invariant: if the next letter is lower case, it must be converted
1071 // to upper case.
1072 // That is, we process a word at a time, where words are marked by _ or
1073 // upper case letter. Digits are treated as words.
1074 for ; i < len(s); i++ {
1075 c := s[i]
1076 oneC[0] = c
1077 if c == '_' && i+1 < len(s) && isASCIILower(s[i+1]) {
1078 continue // Skip the underscore in s.
1079 }
1080 if isASCIIDigit(c) {
1081 t = bytes.Add(t, oneC)
Rob Pikeaf82b4e2010-04-30 15:19:25 -07001082 continue
1083 }
Rob Pike2c7bafc2010-06-10 16:07:14 -07001084 // Assume we have a letter now - if not, it's a bogus identifier.
1085 // The next word is a sequence of characters that must start upper case.
1086 if isASCIILower(c) {
1087 oneC[0] ^= ' ' // Make it a capital letter.
1088 }
1089 t = bytes.Add(t, oneC) // Guaranteed not lower case.
1090 // Accept lower case sequence that follows.
1091 for i+1 < len(s) && isASCIILower(s[i+1]) {
1092 i++
1093 oneC[0] = s[i]
1094 t = bytes.Add(t, oneC)
Rob Pikeaf82b4e2010-04-30 15:19:25 -07001095 }
1096 }
Rob Pike2c7bafc2010-06-10 16:07:14 -07001097 return string(t)
Rob Pikeaf82b4e2010-04-30 15:19:25 -07001098}
1099
1100// CamelCaseSlice is like CamelCase, but the argument is a slice of strings to
1101// be joined with "_".
1102func CamelCaseSlice(elem []string) string { return CamelCase(strings.Join(elem, "_")) }
1103
1104// dottedSlice turns a sliced name into a dotted name.
1105func dottedSlice(elem []string) string { return strings.Join(elem, ".") }
1106
1107// Quote returns a Go-source quoted string representation of s.
1108func Quote(s string) string { return fmt.Sprintf("%q", s) }
1109
1110// Given a .proto file name, return the output name for the generated Go program.
1111func goFileName(name string) string {
Rob Pike87af39e2010-07-19 10:48:02 -07001112 ext := path.Ext(name)
1113 if ext == ".proto" || ext == ".protodevel" {
1114 name = name[0 : len(name)-len(ext)]
Rob Pikeaf82b4e2010-04-30 15:19:25 -07001115 }
1116 return name + ".pb.go"
1117}
1118
1119// Is this field optional?
1120func isOptional(field *descriptor.FieldDescriptorProto) bool {
1121 return field.Label != nil && *field.Label == descriptor.FieldDescriptorProto_LABEL_OPTIONAL
1122}
1123
1124// Is this field required?
1125func isRequired(field *descriptor.FieldDescriptorProto) bool {
1126 return field.Label != nil && *field.Label == descriptor.FieldDescriptorProto_LABEL_REQUIRED
1127}
1128
1129// Is this field repeated?
1130func isRepeated(field *descriptor.FieldDescriptorProto) bool {
1131 return field.Label != nil && *field.Label == descriptor.FieldDescriptorProto_LABEL_REPEATED
1132}
1133
1134// DotToUnderscore is the mapping function used to generate Go names from package names,
Rob Pikec9e7d972010-06-10 10:30:22 -07001135// which can be dotted in the input .proto file. It maps dots to underscores.
1136// Because we also get here from package names generated from file names, it also maps
1137// minus signs to underscores.
Rob Pikeaf82b4e2010-04-30 15:19:25 -07001138func DotToUnderscore(rune int) int {
Rob Pikec9e7d972010-06-10 10:30:22 -07001139 switch rune {
1140 case '.', '-':
Rob Pikeaf82b4e2010-04-30 15:19:25 -07001141 return '_'
1142 }
1143 return rune
1144}
Rob Pikec9e7d972010-06-10 10:30:22 -07001145
1146// BaseName returns the last path element of the name, with the last dotted suffix removed.
1147func BaseName(name string) string {
1148 // First, find the last element
1149 if i := strings.LastIndex(name, "/"); i >= 0 {
1150 name = name[i+1:]
1151 }
1152 // Now drop the suffix
1153 if i := strings.LastIndex(name, "."); i >= 0 {
1154 name = name[0:i]
1155 }
1156 return name
1157}