| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 1 | // 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 Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 36 | */ |
| 37 | package generator |
| 38 | |
| 39 | import ( |
| 40 | "bytes" |
| 41 | "fmt" |
| 42 | "log" |
| 43 | "os" |
| Rob Pike | 87af39e | 2010-07-19 10:48:02 -0700 | [diff] [blame] | 44 | "path" |
| David Symonds | 79eae33 | 2010-10-16 11:33:20 +1100 | [diff] [blame] | 45 | "strconv" |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 46 | "strings" |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 47 | |
| 48 | "goprotobuf.googlecode.com/hg/proto" |
| David Symonds | 832b243 | 2010-11-11 10:55:27 +1100 | [diff] [blame] | 49 | plugin "goprotobuf.googlecode.com/hg/compiler/plugin" |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 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. |
| 55 | type Plugin interface { |
| 56 | // Name identifies the plugin. |
| Rob Pike | c9e7d97 | 2010-06-10 10:30:22 -0700 | [diff] [blame] | 57 | 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 Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 64 | // GenerateImports produces the import declarations for this file. |
| Rob Pike | c9e7d97 | 2010-06-10 10:30:22 -0700 | [diff] [blame] | 65 | // It is called after Generate. |
| 66 | GenerateImports(file *FileDescriptor) |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 67 | } |
| 68 | |
| 69 | var 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. |
| 73 | func RegisterPlugin(p Plugin) { |
| David Symonds | cc7142e | 2010-11-06 14:37:15 +1100 | [diff] [blame] | 74 | plugins = append(plugins, p) |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 75 | } |
| 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. |
| 84 | type 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. |
| 89 | func (c *common) PackageName() string { return uniquePackageOf(c.File) } |
| 90 | |
| 91 | // Descriptor represents a protocol buffer message. |
| 92 | type 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. |
| 103 | func (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. |
| 122 | type 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. |
| 131 | func (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... . |
| 150 | func (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. |
| 161 | func (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 | } |
| David Symonds | 9d0000e | 2011-02-03 10:48:14 +1100 | [diff] [blame] | 167 | log.Fatal("cannot find value for enum constant") |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 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. |
| 173 | type ExtensionDescriptor struct { |
| 174 | common |
| 175 | *descriptor.FieldDescriptorProto |
| Rob Pike | c9e7d97 | 2010-06-10 10:30:22 -0700 | [diff] [blame] | 176 | parent *Descriptor // The containing message, if any. |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 177 | } |
| 178 | |
| 179 | // TypeName returns the elements of the dotted type name. |
| 180 | // The package name is not part of this name. |
| 181 | func (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. |
| 198 | type FileDescriptor struct { |
| 199 | *descriptor.FileDescriptorProto |
| Rob Pike | c9e7d97 | 2010-06-10 10:30:22 -0700 | [diff] [blame] | 200 | 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. |
| David Symonds | 31d58a2 | 2011-01-20 18:33:21 +1100 | [diff] [blame] | 203 | |
| 204 | // The full list of symbols that are exported. |
| 205 | // This is used for supporting public imports. |
| 206 | exported []Symbol |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 207 | } |
| 208 | |
| 209 | // PackageName is the package name we'll use in the generated code to refer to this file. |
| 210 | func (d *FileDescriptor) PackageName() string { return uniquePackageOf(d.FileDescriptorProto) } |
| 211 | |
| 212 | // The package named defined in the input for this file, possibly dotted. |
| Rob Pike | c9e7d97 | 2010-06-10 10:30:22 -0700 | [diff] [blame] | 213 | // If the file does not define a package, use the base of the file name. |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 214 | func (d *FileDescriptor) originalPackageName() string { |
| Rob Pike | c9e7d97 | 2010-06-10 10:30:22 -0700 | [diff] [blame] | 215 | // Does the file have a package clause? |
| David Symonds | 7d5c824 | 2011-03-14 12:03:50 -0700 | [diff] [blame] | 216 | if pkg := proto.GetString(d.Package); pkg != "" { |
| Rob Pike | c9e7d97 | 2010-06-10 10:30:22 -0700 | [diff] [blame] | 217 | return pkg |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 218 | } |
| Rob Pike | c9e7d97 | 2010-06-10 10:30:22 -0700 | [diff] [blame] | 219 | // Use the file base name. |
| 220 | return BaseName(proto.GetString(d.Name)) |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 221 | } |
| 222 | |
| David Symonds | 31d58a2 | 2011-01-20 18:33:21 +1100 | [diff] [blame] | 223 | func (d *FileDescriptor) addExport(symbol Symbol) { |
| 224 | d.exported = append(d.exported, symbol) |
| 225 | } |
| 226 | |
| 227 | // Symbol is an interface representing an exported Go symbol. |
| 228 | type Symbol interface { |
| 229 | // GenerateAlias should generate an appropriate alias |
| 230 | // for the symbol from the named package. |
| 231 | GenerateAlias(g *Generator, pkg string) |
| 232 | } |
| 233 | |
| 234 | type messageSymbol struct { |
| 235 | sym string |
| 236 | hasExtensions, isMessageSet bool |
| 237 | } |
| 238 | |
| 239 | func (ms messageSymbol) GenerateAlias(g *Generator, pkg string) { |
| 240 | remoteSym := pkg + "." + ms.sym |
| 241 | |
| 242 | g.P("type ", ms.sym, " ", remoteSym) |
| 243 | g.P("func (this *", ms.sym, ") Reset() { (*", remoteSym, ")(this).Reset() }") |
| 244 | if ms.hasExtensions { |
| 245 | g.P("func (*", ms.sym, ") ExtensionRangeArray() []", g.ProtoPkg, ".ExtensionRange ", |
| 246 | "{ return (*", remoteSym, ")(nil).ExtensionRangeArray() }") |
| 247 | g.P("func (this *", ms.sym, ") ExtensionMap() map[int32][]byte ", |
| 248 | "{ return (*", remoteSym, ")(this).ExtensionMap() }") |
| 249 | if ms.isMessageSet { |
| 250 | g.P("func (this *", ms.sym, ") Marshal() ([]byte, os.Error) ", |
| 251 | "{ return (*", remoteSym, ")(this).Marshal() }") |
| 252 | g.P("func (this *", ms.sym, ") Unmarshal(buf []byte) os.Error ", |
| 253 | "{ return (*", remoteSym, ")(this).Unmarshal(buf) }") |
| 254 | } |
| 255 | } |
| 256 | } |
| 257 | |
| 258 | type enumSymbol string |
| 259 | |
| 260 | func (es enumSymbol) GenerateAlias(g *Generator, pkg string) { |
| 261 | s := string(es) |
| 262 | g.P("type ", s, " ", pkg, ".", s) |
| 263 | g.P("var ", s, "_name = ", pkg, ".", s, "_name") |
| 264 | g.P("var ", s, "_value = ", pkg, ".", s, "_value") |
| 265 | g.P("func New", s, "(x int32) *", s, " { e := ", s, "(x); return &e }") |
| 266 | } |
| 267 | |
| 268 | type constOrVarSymbol struct { |
| 269 | sym string |
| 270 | typ string // either "const" or "var" |
| 271 | } |
| 272 | |
| 273 | func (cs constOrVarSymbol) GenerateAlias(g *Generator, pkg string) { |
| 274 | g.P(cs.typ, " ", cs.sym, " = ", pkg, ".", cs.sym) |
| 275 | } |
| 276 | |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 277 | // Object is an interface abstracting the abilities shared by enums and messages. |
| 278 | type Object interface { |
| 279 | PackageName() string // The name we use in our output (a_b_c), possibly renamed for uniqueness. |
| 280 | TypeName() []string |
| 281 | } |
| 282 | |
| 283 | // Each package name we generate must be unique. The package we're generating |
| 284 | // gets its own name but every other package must have a unqiue name that does |
| 285 | // not conflict in the code we generate. These names are chosen globally (although |
| 286 | // they don't have to be, it simplifies things to do them globally). |
| 287 | func uniquePackageOf(fd *descriptor.FileDescriptorProto) string { |
| 288 | s, ok := uniquePackageName[fd] |
| 289 | if !ok { |
| David Symonds | 9d0000e | 2011-02-03 10:48:14 +1100 | [diff] [blame] | 290 | log.Fatal("internal error: no package name defined for", proto.GetString(fd.Name)) |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 291 | } |
| 292 | return s |
| 293 | } |
| 294 | |
| 295 | // Generator is the type whose methods generate the output, stored in the associated response structure. |
| 296 | type Generator struct { |
| David Symonds | f90e338 | 2010-05-05 10:53:44 +1000 | [diff] [blame] | 297 | *bytes.Buffer |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 298 | |
| 299 | Request *plugin.CodeGeneratorRequest // The input. |
| 300 | Response *plugin.CodeGeneratorResponse // The output. |
| 301 | |
| Rob Pike | c9e7d97 | 2010-06-10 10:30:22 -0700 | [diff] [blame] | 302 | Param map[string]string // Command-line parameters. |
| 303 | ImportPrefix string // String to prefix to imported package file names. |
| 304 | ImportMap map[string]string // Mapping from import name to generated name |
| 305 | |
| 306 | ProtoPkg string // The name under which we import the library's package proto. |
| 307 | |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 308 | packageName string // What we're calling ourselves. |
| 309 | allFiles []*FileDescriptor // All files in the tree |
| 310 | genFiles []*FileDescriptor // Those files we will generate output for. |
| 311 | file *FileDescriptor // The file we are compiling now. |
| David Symonds | f90e338 | 2010-05-05 10:53:44 +1000 | [diff] [blame] | 312 | usedPackages map[string]bool // Names of packages used in current file. |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 313 | typeNameToObject map[string]Object // Key is a fully-qualified name in input syntax. |
| 314 | indent string |
| 315 | } |
| 316 | |
| 317 | // New creates a new generator and allocates the request and response protobufs. |
| 318 | func New() *Generator { |
| 319 | g := new(Generator) |
| David Symonds | f90e338 | 2010-05-05 10:53:44 +1000 | [diff] [blame] | 320 | g.Buffer = new(bytes.Buffer) |
| David Symonds | b012753 | 2010-11-09 11:10:46 +1100 | [diff] [blame] | 321 | g.Request = new(plugin.CodeGeneratorRequest) |
| 322 | g.Response = new(plugin.CodeGeneratorResponse) |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 323 | return g |
| 324 | } |
| 325 | |
| 326 | // Error reports a problem, including an os.Error, and exits the program. |
| 327 | func (g *Generator) Error(err os.Error, msgs ...string) { |
| 328 | s := strings.Join(msgs, " ") + ":" + err.String() |
| Rob Pike | 5194c51 | 2010-10-14 13:02:16 -0700 | [diff] [blame] | 329 | log.Println("protoc-gen-go: error:", s) |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 330 | g.Response.Error = proto.String(s) |
| 331 | os.Exit(1) |
| 332 | } |
| 333 | |
| 334 | // Fail reports a problem and exits the program. |
| 335 | func (g *Generator) Fail(msgs ...string) { |
| 336 | s := strings.Join(msgs, " ") |
| Rob Pike | 5194c51 | 2010-10-14 13:02:16 -0700 | [diff] [blame] | 337 | log.Println("protoc-gen-go: error:", s) |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 338 | g.Response.Error = proto.String(s) |
| 339 | os.Exit(1) |
| 340 | } |
| 341 | |
| Rob Pike | c9e7d97 | 2010-06-10 10:30:22 -0700 | [diff] [blame] | 342 | // CommandLineParameters breaks the comma-separated list of key=value pairs |
| 343 | // in the parameter (a member of the request protobuf) into a key/value map. |
| 344 | // It then sets file name mappings defined by those entries. |
| 345 | func (g *Generator) CommandLineParameters(parameter string) { |
| 346 | g.Param = make(map[string]string) |
| Rob Pike | 5338544 | 2010-06-30 22:22:43 -0700 | [diff] [blame] | 347 | for _, p := range strings.Split(parameter, ",", -1) { |
| Rob Pike | c9e7d97 | 2010-06-10 10:30:22 -0700 | [diff] [blame] | 348 | if i := strings.Index(p, "="); i < 0 { |
| 349 | g.Param[p] = "" |
| 350 | } else { |
| 351 | g.Param[p[0:i]] = p[i+1:] |
| 352 | } |
| 353 | } |
| 354 | |
| 355 | g.ImportMap = make(map[string]string) |
| 356 | for k, v := range g.Param { |
| 357 | if k == "import_prefix" { |
| 358 | g.ImportPrefix = v |
| 359 | } else if len(k) > 0 && k[0] == 'M' { |
| 360 | g.ImportMap[k[1:]] = v |
| 361 | } |
| 362 | } |
| 363 | } |
| 364 | |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 365 | // DefaultPackageName returns the package name printed for the object. |
| 366 | // If its file is in a different package, it returns the package name we're using for this file, plus ".". |
| 367 | // Otherwise it returns the empty string. |
| 368 | func (g *Generator) DefaultPackageName(obj Object) string { |
| 369 | pkg := obj.PackageName() |
| 370 | if pkg == g.packageName { |
| 371 | return "" |
| 372 | } |
| 373 | return pkg + "." |
| 374 | } |
| 375 | |
| 376 | // For each input file, the unique package name to use, underscored. |
| 377 | var uniquePackageName = make(map[*descriptor.FileDescriptorProto]string) |
| Rob Pike | c9e7d97 | 2010-06-10 10:30:22 -0700 | [diff] [blame] | 378 | // Package names already registered. Key is the name from the .proto file; |
| 379 | // value is the name that appears in the generated code. |
| 380 | var pkgNamesInUse = make(map[string]bool) |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 381 | |
| Rob Pike | c9e7d97 | 2010-06-10 10:30:22 -0700 | [diff] [blame] | 382 | // Create and remember a guaranteed unique package name for this file descriptor. |
| 383 | // Pkg is the candidate name. If f is nil, it's a builtin package like "proto" and |
| 384 | // has no file descriptor. |
| 385 | func RegisterUniquePackageName(pkg string, f *FileDescriptor) string { |
| David Symonds | 79eae33 | 2010-10-16 11:33:20 +1100 | [diff] [blame] | 386 | for i, orig := 1, pkg; pkgNamesInUse[pkg]; i++ { |
| Rob Pike | c9e7d97 | 2010-06-10 10:30:22 -0700 | [diff] [blame] | 387 | // It's a duplicate; must rename. |
| David Symonds | 79eae33 | 2010-10-16 11:33:20 +1100 | [diff] [blame] | 388 | pkg = orig + strconv.Itoa(i) |
| Rob Pike | c9e7d97 | 2010-06-10 10:30:22 -0700 | [diff] [blame] | 389 | } |
| 390 | // Install it. |
| 391 | pkgNamesInUse[pkg] = true |
| 392 | pkg = strings.Map(DotToUnderscore, pkg) |
| 393 | if f != nil { |
| 394 | uniquePackageName[f.FileDescriptorProto] = pkg |
| 395 | } |
| 396 | return pkg |
| 397 | } |
| 398 | |
| 399 | // SetPackageNames sets the package name for this run. |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 400 | // The package name must agree across all files being generated. |
| 401 | // It also defines unique package names for all imported files. |
| 402 | func (g *Generator) SetPackageNames() { |
| Rob Pike | c9e7d97 | 2010-06-10 10:30:22 -0700 | [diff] [blame] | 403 | // Register the name for this package. It will be the first name |
| 404 | // registered so is guaranteed to be unmodified. |
| 405 | pkg := g.genFiles[0].originalPackageName() |
| 406 | g.packageName = RegisterUniquePackageName(pkg, g.genFiles[0]) |
| 407 | // Register the proto package name. It might collide with the |
| 408 | // name of a package we import. |
| 409 | g.ProtoPkg = RegisterUniquePackageName("proto", nil) |
| David Symonds | 7d5c824 | 2011-03-14 12:03:50 -0700 | [diff] [blame] | 410 | // Verify that we are generating output for a single package. |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 411 | for _, f := range g.genFiles { |
| Rob Pike | c9e7d97 | 2010-06-10 10:30:22 -0700 | [diff] [blame] | 412 | thisPkg := f.originalPackageName() |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 413 | if thisPkg != pkg { |
| 414 | g.Fail("inconsistent package names:", thisPkg, pkg) |
| 415 | } |
| 416 | } |
| 417 | AllFiles: |
| 418 | for _, f := range g.allFiles { |
| 419 | for _, genf := range g.genFiles { |
| 420 | if f == genf { |
| 421 | // In this package already. |
| 422 | uniquePackageName[f.FileDescriptorProto] = g.packageName |
| 423 | continue AllFiles |
| 424 | } |
| 425 | } |
| David Symonds | 7d5c824 | 2011-03-14 12:03:50 -0700 | [diff] [blame] | 426 | // The file is a dependency, so we want to ignore its go_package option |
| 427 | // because that is only relevant for its specific generated output. |
| 428 | pkg := proto.GetString(f.Package) |
| 429 | if pkg == "" { |
| 430 | pkg = BaseName(*f.Name) |
| 431 | } |
| 432 | RegisterUniquePackageName(pkg, f) |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 433 | } |
| 434 | } |
| 435 | |
| 436 | // WrapTypes walks the incoming data, wrapping DescriptorProtos, EnumDescriptorProtos |
| 437 | // and FileDescriptorProtos into file-referenced objects within the Generator. |
| 438 | // It also creates the list of files to generate and so should be called before GenerateAllFiles. |
| 439 | func (g *Generator) WrapTypes() { |
| 440 | g.allFiles = make([]*FileDescriptor, len(g.Request.ProtoFile)) |
| 441 | for i, f := range g.Request.ProtoFile { |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 442 | // We must wrap the descriptors before we wrap the enums |
| 443 | descs := wrapDescriptors(f) |
| 444 | g.buildNestedDescriptors(descs) |
| 445 | enums := wrapEnumDescriptors(f, descs) |
| 446 | exts := wrapExtensions(f) |
| 447 | g.allFiles[i] = &FileDescriptor{ |
| 448 | FileDescriptorProto: f, |
| 449 | desc: descs, |
| 450 | enum: enums, |
| 451 | ext: exts, |
| 452 | } |
| 453 | } |
| 454 | |
| 455 | g.genFiles = make([]*FileDescriptor, len(g.Request.FileToGenerate)) |
| 456 | FindFiles: |
| 457 | for i, fileName := range g.Request.FileToGenerate { |
| 458 | // Search the list. This algorithm is n^2 but n is tiny. |
| 459 | for _, file := range g.allFiles { |
| 460 | if fileName == proto.GetString(file.Name) { |
| 461 | g.genFiles[i] = file |
| 462 | continue FindFiles |
| 463 | } |
| 464 | } |
| 465 | g.Fail("could not find file named", fileName) |
| 466 | } |
| 467 | g.Response.File = make([]*plugin.CodeGeneratorResponse_File, len(g.genFiles)) |
| 468 | } |
| 469 | |
| 470 | // Scan the descriptors in this file. For each one, build the slice of nested descriptors |
| 471 | func (g *Generator) buildNestedDescriptors(descs []*Descriptor) { |
| 472 | for _, desc := range descs { |
| 473 | if len(desc.NestedType) != 0 { |
| 474 | desc.nested = make([]*Descriptor, len(desc.NestedType)) |
| 475 | n := 0 |
| 476 | for _, nest := range descs { |
| 477 | if nest.parent == desc { |
| 478 | desc.nested[n] = nest |
| 479 | n++ |
| 480 | } |
| 481 | } |
| 482 | if n != len(desc.NestedType) { |
| 483 | g.Fail("internal error: nesting failure for", proto.GetString(desc.Name)) |
| 484 | } |
| 485 | } |
| 486 | } |
| 487 | } |
| 488 | |
| 489 | // Construct the Descriptor and add it to the slice |
| 490 | func addDescriptor(sl []*Descriptor, desc *descriptor.DescriptorProto, parent *Descriptor, file *descriptor.FileDescriptorProto) []*Descriptor { |
| 491 | d := &Descriptor{common{File: file}, desc, parent, nil, nil, nil} |
| 492 | |
| 493 | d.ext = make([]*ExtensionDescriptor, len(desc.Extension)) |
| 494 | for i, field := range desc.Extension { |
| 495 | d.ext[i] = &ExtensionDescriptor{common{File: file}, field, d} |
| 496 | } |
| 497 | |
| David Symonds | cc7142e | 2010-11-06 14:37:15 +1100 | [diff] [blame] | 498 | return append(sl, d) |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 499 | } |
| 500 | |
| 501 | // Return a slice of all the Descriptors defined within this file |
| 502 | func wrapDescriptors(file *descriptor.FileDescriptorProto) []*Descriptor { |
| 503 | sl := make([]*Descriptor, 0, len(file.MessageType)+10) |
| 504 | for _, desc := range file.MessageType { |
| 505 | sl = wrapThisDescriptor(sl, desc, nil, file) |
| 506 | } |
| 507 | return sl |
| 508 | } |
| 509 | |
| 510 | // Wrap this Descriptor, recursively |
| 511 | func wrapThisDescriptor(sl []*Descriptor, desc *descriptor.DescriptorProto, parent *Descriptor, file *descriptor.FileDescriptorProto) []*Descriptor { |
| 512 | sl = addDescriptor(sl, desc, parent, file) |
| 513 | me := sl[len(sl)-1] |
| 514 | for _, nested := range desc.NestedType { |
| 515 | sl = wrapThisDescriptor(sl, nested, me, file) |
| 516 | } |
| 517 | return sl |
| 518 | } |
| 519 | |
| 520 | // Construct the EnumDescriptor and add it to the slice |
| 521 | func addEnumDescriptor(sl []*EnumDescriptor, desc *descriptor.EnumDescriptorProto, parent *Descriptor, file *descriptor.FileDescriptorProto) []*EnumDescriptor { |
| David Symonds | cc7142e | 2010-11-06 14:37:15 +1100 | [diff] [blame] | 522 | return append(sl, &EnumDescriptor{common{File: file}, desc, parent, nil}) |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 523 | } |
| 524 | |
| 525 | // Return a slice of all the EnumDescriptors defined within this file |
| 526 | func wrapEnumDescriptors(file *descriptor.FileDescriptorProto, descs []*Descriptor) []*EnumDescriptor { |
| 527 | sl := make([]*EnumDescriptor, 0, len(file.EnumType)+10) |
| David Symonds | 5256cf6 | 2010-06-27 10:33:42 +1000 | [diff] [blame] | 528 | // Top-level enums. |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 529 | for _, enum := range file.EnumType { |
| 530 | sl = addEnumDescriptor(sl, enum, nil, file) |
| 531 | } |
| David Symonds | 5256cf6 | 2010-06-27 10:33:42 +1000 | [diff] [blame] | 532 | // Enums within messages. Enums within embedded messages appear in the outer-most message. |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 533 | for _, nested := range descs { |
| David Symonds | 5256cf6 | 2010-06-27 10:33:42 +1000 | [diff] [blame] | 534 | for _, enum := range nested.EnumType { |
| 535 | sl = addEnumDescriptor(sl, enum, nested, file) |
| 536 | } |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 537 | } |
| 538 | return sl |
| 539 | } |
| 540 | |
| 541 | // Return a slice of all the top-level ExtensionDescriptors defined within this file. |
| 542 | func wrapExtensions(file *descriptor.FileDescriptorProto) []*ExtensionDescriptor { |
| 543 | sl := make([]*ExtensionDescriptor, len(file.Extension)) |
| 544 | for i, field := range file.Extension { |
| 545 | sl[i] = &ExtensionDescriptor{common{File: file}, field, nil} |
| 546 | } |
| 547 | return sl |
| 548 | } |
| 549 | |
| Rob Pike | c9e7d97 | 2010-06-10 10:30:22 -0700 | [diff] [blame] | 550 | // BuildTypeNameMap builds the map from fully qualified type names to objects. |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 551 | // The key names for the map come from the input data, which puts a period at the beginning. |
| 552 | // It should be called after SetPackageNames and before GenerateAllFiles. |
| 553 | func (g *Generator) BuildTypeNameMap() { |
| 554 | g.typeNameToObject = make(map[string]Object) |
| 555 | for _, f := range g.allFiles { |
| Rob Pike | c9e7d97 | 2010-06-10 10:30:22 -0700 | [diff] [blame] | 556 | // The names in this loop are defined by the proto world, not us, so the |
| 557 | // package name may be empty. If so, the dotted package name of X will |
| 558 | // be ".X"; otherwise it will be ".pkg.X". |
| 559 | dottedPkg := "." + proto.GetString(f.Package) |
| 560 | if dottedPkg != "." { |
| 561 | dottedPkg += "." |
| 562 | } |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 563 | for _, enum := range f.enum { |
| 564 | name := dottedPkg + dottedSlice(enum.TypeName()) |
| 565 | g.typeNameToObject[name] = enum |
| 566 | } |
| 567 | for _, desc := range f.desc { |
| 568 | name := dottedPkg + dottedSlice(desc.TypeName()) |
| 569 | g.typeNameToObject[name] = desc |
| 570 | } |
| 571 | } |
| 572 | } |
| 573 | |
| 574 | // ObjectNamed, given a fully-qualified input type name as it appears in the input data, |
| 575 | // returns the descriptor for the message or enum with that name. |
| 576 | func (g *Generator) ObjectNamed(typeName string) Object { |
| 577 | f, ok := g.typeNameToObject[typeName] |
| 578 | if !ok { |
| 579 | g.Fail("can't find object with type", typeName) |
| 580 | } |
| 581 | return f |
| 582 | } |
| 583 | |
| 584 | // P prints the arguments to the generated output. It handles strings and int32s, plus |
| 585 | // handling indirections because they may be *string, etc. |
| 586 | func (g *Generator) P(str ...interface{}) { |
| 587 | g.WriteString(g.indent) |
| 588 | for _, v := range str { |
| 589 | switch s := v.(type) { |
| 590 | case string: |
| 591 | g.WriteString(s) |
| 592 | case *string: |
| 593 | g.WriteString(*s) |
| Rob Pike | c9e7d97 | 2010-06-10 10:30:22 -0700 | [diff] [blame] | 594 | case bool: |
| 595 | g.WriteString(fmt.Sprintf("%t", s)) |
| 596 | case *bool: |
| 597 | g.WriteString(fmt.Sprintf("%t", *s)) |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 598 | case *int32: |
| 599 | g.WriteString(fmt.Sprintf("%d", *s)) |
| Rob Pike | c9e7d97 | 2010-06-10 10:30:22 -0700 | [diff] [blame] | 600 | case float64: |
| 601 | g.WriteString(fmt.Sprintf("%g", s)) |
| 602 | case *float64: |
| 603 | g.WriteString(fmt.Sprintf("%g", *s)) |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 604 | default: |
| 605 | g.Fail(fmt.Sprintf("unknown type in printer: %T", v)) |
| 606 | } |
| 607 | } |
| 608 | g.WriteByte('\n') |
| 609 | } |
| 610 | |
| 611 | // In Indents the output one tab stop. |
| 612 | func (g *Generator) In() { g.indent += "\t" } |
| 613 | |
| 614 | // Out unindents the output one tab stop. |
| 615 | func (g *Generator) Out() { |
| 616 | if len(g.indent) > 0 { |
| 617 | g.indent = g.indent[1:] |
| 618 | } |
| 619 | } |
| 620 | |
| 621 | // GenerateAllFiles generates the output for all the files we're outputting. |
| 622 | func (g *Generator) GenerateAllFiles() { |
| Rob Pike | c9e7d97 | 2010-06-10 10:30:22 -0700 | [diff] [blame] | 623 | // Initialize the plugins |
| 624 | for _, p := range plugins { |
| 625 | p.Init(g) |
| 626 | } |
| David Symonds | 31d58a2 | 2011-01-20 18:33:21 +1100 | [diff] [blame] | 627 | // Generate the output. The generator runs for every file, even the files |
| 628 | // that we don't generate output for, so that we can collate the full list |
| 629 | // of exported symbols to support public imports. |
| 630 | genFileMap := make(map[*FileDescriptor]bool, len(g.genFiles)) |
| 631 | for _, file := range g.genFiles { |
| 632 | genFileMap[file] = true |
| 633 | } |
| 634 | i := 0 |
| 635 | for _, file := range g.allFiles { |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 636 | g.Reset() |
| 637 | g.generate(file) |
| David Symonds | 31d58a2 | 2011-01-20 18:33:21 +1100 | [diff] [blame] | 638 | if _, ok := genFileMap[file]; !ok { |
| 639 | continue |
| 640 | } |
| David Symonds | b012753 | 2010-11-09 11:10:46 +1100 | [diff] [blame] | 641 | g.Response.File[i] = new(plugin.CodeGeneratorResponse_File) |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 642 | g.Response.File[i].Name = proto.String(goFileName(*file.Name)) |
| 643 | g.Response.File[i].Content = proto.String(g.String()) |
| David Symonds | 31d58a2 | 2011-01-20 18:33:21 +1100 | [diff] [blame] | 644 | i++ |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 645 | } |
| 646 | } |
| 647 | |
| 648 | // Run all the plugins associated with the file. |
| 649 | func (g *Generator) runPlugins(file *FileDescriptor) { |
| 650 | for _, p := range plugins { |
| Rob Pike | c9e7d97 | 2010-06-10 10:30:22 -0700 | [diff] [blame] | 651 | p.Generate(file) |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 652 | } |
| 653 | } |
| 654 | |
| 655 | |
| 656 | // FileOf return the FileDescriptor for this FileDescriptorProto. |
| 657 | func (g *Generator) FileOf(fd *descriptor.FileDescriptorProto) *FileDescriptor { |
| 658 | for _, file := range g.allFiles { |
| 659 | if file.FileDescriptorProto == fd { |
| 660 | return file |
| 661 | } |
| 662 | } |
| 663 | g.Fail("could not find file in table:", proto.GetString(fd.Name)) |
| 664 | return nil |
| 665 | } |
| 666 | |
| 667 | // Fill the response protocol buffer with the generated output for all the files we're |
| 668 | // supposed to generate. |
| 669 | func (g *Generator) generate(file *FileDescriptor) { |
| 670 | g.file = g.FileOf(file.FileDescriptorProto) |
| David Symonds | f90e338 | 2010-05-05 10:53:44 +1000 | [diff] [blame] | 671 | g.usedPackages = make(map[string]bool) |
| 672 | |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 673 | for _, enum := range g.file.enum { |
| 674 | g.generateEnum(enum) |
| 675 | } |
| 676 | for _, desc := range g.file.desc { |
| 677 | g.generateMessage(desc) |
| 678 | } |
| 679 | for _, ext := range g.file.ext { |
| 680 | g.generateExtension(ext) |
| 681 | } |
| 682 | g.generateInitFunction() |
| David Symonds | f90e338 | 2010-05-05 10:53:44 +1000 | [diff] [blame] | 683 | |
| Rob Pike | c9e7d97 | 2010-06-10 10:30:22 -0700 | [diff] [blame] | 684 | // Run the plugins before the imports so we know which imports are necessary. |
| 685 | g.runPlugins(file) |
| 686 | |
| David Symonds | f90e338 | 2010-05-05 10:53:44 +1000 | [diff] [blame] | 687 | // Generate header and imports last, though they appear first in the output. |
| 688 | rem := g.Buffer |
| 689 | g.Buffer = new(bytes.Buffer) |
| 690 | g.generateHeader() |
| 691 | g.generateImports() |
| 692 | g.Write(rem.Bytes()) |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 693 | } |
| 694 | |
| 695 | // Generate the header, including package definition and imports |
| 696 | func (g *Generator) generateHeader() { |
| 697 | g.P("// Code generated by protoc-gen-go from ", Quote(*g.file.Name)) |
| 698 | g.P("// DO NOT EDIT!") |
| 699 | g.P() |
| 700 | g.P("package ", g.file.PackageName()) |
| 701 | g.P() |
| 702 | } |
| 703 | |
| David Symonds | 31d58a2 | 2011-01-20 18:33:21 +1100 | [diff] [blame] | 704 | func (g *Generator) fileByName(filename string) *FileDescriptor { |
| 705 | for _, fd := range g.allFiles { |
| 706 | if proto.GetString(fd.Name) == filename { |
| 707 | return fd |
| 708 | } |
| 709 | } |
| 710 | return nil |
| 711 | } |
| 712 | |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 713 | // Generate the header, including package definition and imports |
| 714 | func (g *Generator) generateImports() { |
| Rob Pike | c9e7d97 | 2010-06-10 10:30:22 -0700 | [diff] [blame] | 715 | // We almost always need a proto import. Rather than computing when we |
| 716 | // do, which is tricky when there's a plugin, just import it and |
| David Symonds | 4fee3b1 | 2010-11-11 10:00:13 +1100 | [diff] [blame] | 717 | // reference it later. The same argument applies to the os package. |
| Rob Pike | 809831a | 2010-06-16 10:10:58 -0700 | [diff] [blame] | 718 | g.P("import " + g.ProtoPkg + " " + Quote(g.ImportPrefix+"goprotobuf.googlecode.com/hg/proto")) |
| David Symonds | cea785b | 2011-01-07 11:02:30 +1100 | [diff] [blame] | 719 | g.P(`import "math"`) |
| David Symonds | 4fee3b1 | 2010-11-11 10:00:13 +1100 | [diff] [blame] | 720 | g.P(`import "os"`) |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 721 | for _, s := range g.file.Dependency { |
| David Symonds | 31d58a2 | 2011-01-20 18:33:21 +1100 | [diff] [blame] | 722 | fd := g.fileByName(s) |
| 723 | // Do not import our own package. |
| 724 | if fd.PackageName() == g.packageName { |
| 725 | continue |
| 726 | } |
| 727 | filename := goFileName(s) |
| 728 | if substitution, ok := g.ImportMap[s]; ok { |
| 729 | filename = substitution |
| 730 | } |
| 731 | filename = g.ImportPrefix + filename |
| 732 | if strings.HasSuffix(filename, ".go") { |
| 733 | filename = filename[0 : len(filename)-3] |
| 734 | } |
| 735 | if _, ok := g.usedPackages[fd.PackageName()]; ok { |
| 736 | g.P("import ", fd.PackageName(), " ", Quote(filename)) |
| 737 | } else { |
| 738 | log.Println("protoc-gen-go: discarding unused import:", filename) |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 739 | } |
| 740 | } |
| 741 | g.P() |
| 742 | // TODO: may need to worry about uniqueness across plugins |
| 743 | for _, p := range plugins { |
| Rob Pike | c9e7d97 | 2010-06-10 10:30:22 -0700 | [diff] [blame] | 744 | p.GenerateImports(g.file) |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 745 | g.P() |
| 746 | } |
| David Symonds | cea785b | 2011-01-07 11:02:30 +1100 | [diff] [blame] | 747 | g.P("// Reference proto, math & os imports to suppress error if they are not otherwise used.") |
| Rob Pike | c9e7d97 | 2010-06-10 10:30:22 -0700 | [diff] [blame] | 748 | g.P("var _ = ", g.ProtoPkg, ".GetString") |
| David Symonds | cea785b | 2011-01-07 11:02:30 +1100 | [diff] [blame] | 749 | g.P("var _ = math.Inf") |
| David Symonds | 4fee3b1 | 2010-11-11 10:00:13 +1100 | [diff] [blame] | 750 | g.P("var _ os.Error") |
| Rob Pike | c9e7d97 | 2010-06-10 10:30:22 -0700 | [diff] [blame] | 751 | g.P() |
| David Symonds | 31d58a2 | 2011-01-20 18:33:21 +1100 | [diff] [blame] | 752 | |
| 753 | // Symbols from public imports. |
| 754 | for _, index := range g.file.PublicDependency { |
| 755 | fd := g.fileByName(g.file.Dependency[index]) |
| 756 | g.P("// Types from public import ", *fd.Name) |
| 757 | for _, sym := range fd.exported { |
| 758 | sym.GenerateAlias(g, fd.PackageName()) |
| 759 | } |
| 760 | } |
| 761 | g.P() |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 762 | } |
| 763 | |
| 764 | // Generate the enum definitions for this EnumDescriptor. |
| 765 | func (g *Generator) generateEnum(enum *EnumDescriptor) { |
| 766 | // The full type name |
| 767 | typeName := enum.TypeName() |
| 768 | // The full type name, CamelCased. |
| 769 | ccTypeName := CamelCaseSlice(typeName) |
| 770 | ccPrefix := enum.prefix() |
| 771 | g.P("type ", ccTypeName, " int32") |
| David Symonds | 31d58a2 | 2011-01-20 18:33:21 +1100 | [diff] [blame] | 772 | g.file.addExport(enumSymbol(ccTypeName)) |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 773 | g.P("const (") |
| 774 | g.In() |
| 775 | for _, e := range enum.Value { |
| David Symonds | 31d58a2 | 2011-01-20 18:33:21 +1100 | [diff] [blame] | 776 | name := ccPrefix + *e.Name |
| 777 | g.P(name, " = ", e.Number) |
| 778 | g.file.addExport(constOrVarSymbol{name, "const"}) |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 779 | } |
| 780 | g.Out() |
| 781 | g.P(")") |
| David Symonds | 940b961 | 2011-04-01 10:45:23 +1100 | [diff] [blame^] | 782 | g.P("var ", ccTypeName, "_name = map[int32]string{") |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 783 | g.In() |
| Rob Pike | c9e7d97 | 2010-06-10 10:30:22 -0700 | [diff] [blame] | 784 | generated := make(map[int32]bool) // avoid duplicate values |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 785 | for _, e := range enum.Value { |
| 786 | duplicate := "" |
| 787 | if _, present := generated[*e.Number]; present { |
| 788 | duplicate = "// Duplicate value: " |
| 789 | } |
| 790 | g.P(duplicate, e.Number, ": ", Quote(*e.Name), ",") |
| 791 | generated[*e.Number] = true |
| 792 | } |
| 793 | g.Out() |
| 794 | g.P("}") |
| David Symonds | 940b961 | 2011-04-01 10:45:23 +1100 | [diff] [blame^] | 795 | g.P("var ", ccTypeName, "_value = map[string]int32{") |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 796 | g.In() |
| 797 | for _, e := range enum.Value { |
| 798 | g.P(Quote(*e.Name), ": ", e.Number, ",") |
| 799 | } |
| 800 | g.Out() |
| 801 | g.P("}") |
| David Symonds | 940b961 | 2011-04-01 10:45:23 +1100 | [diff] [blame^] | 802 | |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 803 | g.P("func New", ccTypeName, "(x int32) *", ccTypeName, " {") |
| 804 | g.In() |
| 805 | g.P("e := ", ccTypeName, "(x)") |
| 806 | g.P("return &e") |
| 807 | g.Out() |
| 808 | g.P("}") |
| David Symonds | 940b961 | 2011-04-01 10:45:23 +1100 | [diff] [blame^] | 809 | |
| 810 | g.P("func (x ", ccTypeName, ") String() string {") |
| 811 | g.In() |
| 812 | g.P("return ", g.ProtoPkg, ".EnumName(", ccTypeName, "_name, int32(x))") |
| 813 | g.Out() |
| 814 | g.P("}") |
| 815 | |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 816 | g.P() |
| 817 | } |
| 818 | |
| 819 | // The tag is a string like "PB(varint,2,opt,name=fieldname,def=7)" that |
| 820 | // identifies details of the field for the protocol buffer marshaling and unmarshaling |
| 821 | // code. The fields are: |
| 822 | // wire encoding |
| 823 | // protocol tag number |
| 824 | // opt,req,rep for optional, required, or repeated |
| David Symonds | 5b7775e | 2010-12-01 10:09:04 +1100 | [diff] [blame] | 825 | // packed whether the encoding is "packed" (optional; repeated primitives only) |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 826 | // name= the original declared name |
| 827 | // enum= the name of the enum type if it is an enum-typed field. |
| 828 | // def= string representation of the default value, if any. |
| 829 | // The default value must be in a representation that can be used at run-time |
| 830 | // to generate the default value. Thus bools become 0 and 1, for instance. |
| 831 | func (g *Generator) goTag(field *descriptor.FieldDescriptorProto, wiretype string) string { |
| 832 | optrepreq := "" |
| 833 | switch { |
| 834 | case isOptional(field): |
| 835 | optrepreq = "opt" |
| 836 | case isRequired(field): |
| 837 | optrepreq = "req" |
| 838 | case isRepeated(field): |
| 839 | optrepreq = "rep" |
| 840 | } |
| 841 | defaultValue := proto.GetString(field.DefaultValue) |
| 842 | if defaultValue != "" { |
| 843 | switch *field.Type { |
| 844 | case descriptor.FieldDescriptorProto_TYPE_BOOL: |
| 845 | if defaultValue == "true" { |
| 846 | defaultValue = "1" |
| 847 | } else { |
| 848 | defaultValue = "0" |
| 849 | } |
| 850 | case descriptor.FieldDescriptorProto_TYPE_STRING, |
| 851 | descriptor.FieldDescriptorProto_TYPE_BYTES: |
| 852 | // Protect frogs. |
| 853 | defaultValue = Quote(defaultValue) |
| 854 | // Don't need the quotes |
| 855 | defaultValue = defaultValue[1 : len(defaultValue)-1] |
| 856 | case descriptor.FieldDescriptorProto_TYPE_ENUM: |
| 857 | // For enums we need to provide the integer constant. |
| 858 | obj := g.ObjectNamed(proto.GetString(field.TypeName)) |
| 859 | enum, ok := obj.(*EnumDescriptor) |
| 860 | if !ok { |
| 861 | g.Fail("enum type inconsistent for", CamelCaseSlice(obj.TypeName())) |
| 862 | } |
| 863 | defaultValue = enum.integerValueAsString(defaultValue) |
| 864 | } |
| 865 | defaultValue = ",def=" + defaultValue |
| 866 | } |
| 867 | enum := "" |
| 868 | if *field.Type == descriptor.FieldDescriptorProto_TYPE_ENUM { |
| 869 | obj := g.ObjectNamed(proto.GetString(field.TypeName)) |
| 870 | enum = ",enum=" + obj.PackageName() + "." + CamelCaseSlice(obj.TypeName()) |
| 871 | } |
| David Symonds | 5b7775e | 2010-12-01 10:09:04 +1100 | [diff] [blame] | 872 | packed := "" |
| 873 | if field.Options != nil && proto.GetBool(field.Options.Packed) { |
| 874 | packed = ",packed" |
| 875 | } |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 876 | name := proto.GetString(field.Name) |
| 877 | if name == CamelCase(name) { |
| 878 | name = "" |
| 879 | } else { |
| 880 | name = ",name=" + name |
| 881 | } |
| David Symonds | 5b7775e | 2010-12-01 10:09:04 +1100 | [diff] [blame] | 882 | return Quote(fmt.Sprintf("PB(%s,%d,%s%s%s%s%s)", |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 883 | wiretype, |
| 884 | proto.GetInt32(field.Number), |
| 885 | optrepreq, |
| David Symonds | 5b7775e | 2010-12-01 10:09:04 +1100 | [diff] [blame] | 886 | packed, |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 887 | name, |
| 888 | enum, |
| 889 | defaultValue)) |
| 890 | } |
| 891 | |
| 892 | func needsStar(typ descriptor.FieldDescriptorProto_Type) bool { |
| 893 | switch typ { |
| 894 | case descriptor.FieldDescriptorProto_TYPE_GROUP: |
| 895 | return false |
| 896 | case descriptor.FieldDescriptorProto_TYPE_MESSAGE: |
| 897 | return false |
| 898 | case descriptor.FieldDescriptorProto_TYPE_BYTES: |
| 899 | return false |
| 900 | } |
| 901 | return true |
| 902 | } |
| 903 | |
| 904 | // TypeName is the printed name appropriate for an item. If the object is in the current file, |
| 905 | // TypeName drops the package name and underscores the rest. |
| David Symonds | 7d5c824 | 2011-03-14 12:03:50 -0700 | [diff] [blame] | 906 | // Otherwise the object is from another package; and the result is the underscored |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 907 | // package name followed by the item name. |
| 908 | // The result always has an initial capital. |
| 909 | func (g *Generator) TypeName(obj Object) string { |
| 910 | return g.DefaultPackageName(obj) + CamelCaseSlice(obj.TypeName()) |
| 911 | } |
| 912 | |
| 913 | // TypeNameWithPackage is like TypeName, but always includes the package |
| 914 | // name even if the object is in our own package. |
| 915 | func (g *Generator) TypeNameWithPackage(obj Object) string { |
| 916 | return obj.PackageName() + CamelCaseSlice(obj.TypeName()) |
| 917 | } |
| 918 | |
| 919 | // GoType returns a string representing the type name, and the wire type |
| 920 | func (g *Generator) GoType(message *Descriptor, field *descriptor.FieldDescriptorProto) (typ string, wire string) { |
| 921 | // TODO: Options. |
| 922 | switch *field.Type { |
| 923 | case descriptor.FieldDescriptorProto_TYPE_DOUBLE: |
| 924 | typ, wire = "float64", "fixed64" |
| 925 | case descriptor.FieldDescriptorProto_TYPE_FLOAT: |
| 926 | typ, wire = "float32", "fixed32" |
| 927 | case descriptor.FieldDescriptorProto_TYPE_INT64: |
| 928 | typ, wire = "int64", "varint" |
| 929 | case descriptor.FieldDescriptorProto_TYPE_UINT64: |
| 930 | typ, wire = "uint64", "varint" |
| 931 | case descriptor.FieldDescriptorProto_TYPE_INT32: |
| 932 | typ, wire = "int32", "varint" |
| 933 | case descriptor.FieldDescriptorProto_TYPE_UINT32: |
| 934 | typ, wire = "uint32", "varint" |
| 935 | case descriptor.FieldDescriptorProto_TYPE_FIXED64: |
| 936 | typ, wire = "uint64", "fixed64" |
| 937 | case descriptor.FieldDescriptorProto_TYPE_FIXED32: |
| 938 | typ, wire = "uint32", "fixed32" |
| 939 | case descriptor.FieldDescriptorProto_TYPE_BOOL: |
| 940 | typ, wire = "bool", "varint" |
| 941 | case descriptor.FieldDescriptorProto_TYPE_STRING: |
| 942 | typ, wire = "string", "bytes" |
| 943 | case descriptor.FieldDescriptorProto_TYPE_GROUP: |
| 944 | desc := g.ObjectNamed(proto.GetString(field.TypeName)) |
| 945 | typ, wire = "*"+g.TypeName(desc), "group" |
| 946 | case descriptor.FieldDescriptorProto_TYPE_MESSAGE: |
| 947 | desc := g.ObjectNamed(proto.GetString(field.TypeName)) |
| 948 | typ, wire = "*"+g.TypeName(desc), "bytes" |
| 949 | case descriptor.FieldDescriptorProto_TYPE_BYTES: |
| 950 | typ, wire = "[]byte", "bytes" |
| 951 | case descriptor.FieldDescriptorProto_TYPE_ENUM: |
| 952 | desc := g.ObjectNamed(proto.GetString(field.TypeName)) |
| 953 | typ, wire = g.TypeName(desc), "varint" |
| 954 | case descriptor.FieldDescriptorProto_TYPE_SFIXED32: |
| 955 | typ, wire = "int32", "fixed32" |
| 956 | case descriptor.FieldDescriptorProto_TYPE_SFIXED64: |
| 957 | typ, wire = "int64", "fixed64" |
| 958 | case descriptor.FieldDescriptorProto_TYPE_SINT32: |
| 959 | typ, wire = "int32", "zigzag32" |
| 960 | case descriptor.FieldDescriptorProto_TYPE_SINT64: |
| 961 | typ, wire = "int64", "zigzag64" |
| 962 | default: |
| 963 | g.Fail("unknown type for", proto.GetString(field.Name)) |
| 964 | } |
| 965 | if isRepeated(field) { |
| 966 | typ = "[]" + typ |
| 967 | } else if needsStar(*field.Type) { |
| 968 | typ = "*" + typ |
| 969 | } |
| 970 | return |
| 971 | } |
| 972 | |
| David Symonds | f90e338 | 2010-05-05 10:53:44 +1000 | [diff] [blame] | 973 | func (g *Generator) RecordTypeUse(t string) { |
| 974 | if obj, ok := g.typeNameToObject[t]; ok { |
| 975 | g.usedPackages[obj.PackageName()] = true |
| 976 | } |
| 977 | } |
| 978 | |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 979 | // Generate the type and default constant definitions for this Descriptor. |
| 980 | func (g *Generator) generateMessage(message *Descriptor) { |
| 981 | // The full type name |
| 982 | typeName := message.TypeName() |
| 983 | // The full type name, CamelCased. |
| 984 | ccTypeName := CamelCaseSlice(typeName) |
| 985 | |
| 986 | g.P("type ", ccTypeName, " struct {") |
| 987 | g.In() |
| 988 | for _, field := range message.Field { |
| 989 | fieldname := CamelCase(*field.Name) |
| 990 | typename, wiretype := g.GoType(message, field) |
| 991 | tag := g.goTag(field, wiretype) |
| 992 | g.P(fieldname, "\t", typename, "\t", tag) |
| David Symonds | f90e338 | 2010-05-05 10:53:44 +1000 | [diff] [blame] | 993 | g.RecordTypeUse(proto.GetString(field.TypeName)) |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 994 | } |
| 995 | if len(message.ExtensionRange) > 0 { |
| 996 | g.P("XXX_extensions\t\tmap[int32][]byte") |
| 997 | } |
| 998 | g.P("XXX_unrecognized\t[]byte") |
| 999 | g.Out() |
| 1000 | g.P("}") |
| 1001 | |
| Rob Pike | c6d8e4a | 2010-07-28 15:34:32 -0700 | [diff] [blame] | 1002 | // Reset function |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 1003 | g.P("func (this *", ccTypeName, ") Reset() {") |
| 1004 | g.In() |
| 1005 | g.P("*this = ", ccTypeName, "{}") |
| 1006 | g.Out() |
| 1007 | g.P("}") |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 1008 | |
| 1009 | // Extension support methods |
| David Symonds | 31d58a2 | 2011-01-20 18:33:21 +1100 | [diff] [blame] | 1010 | var hasExtensions, isMessageSet bool |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 1011 | if len(message.ExtensionRange) > 0 { |
| David Symonds | 31d58a2 | 2011-01-20 18:33:21 +1100 | [diff] [blame] | 1012 | hasExtensions = true |
| David Symonds | 4fee3b1 | 2010-11-11 10:00:13 +1100 | [diff] [blame] | 1013 | // message_set_wire_format only makes sense when extensions are defined. |
| 1014 | if opts := message.Options; opts != nil && proto.GetBool(opts.MessageSetWireFormat) { |
| David Symonds | 31d58a2 | 2011-01-20 18:33:21 +1100 | [diff] [blame] | 1015 | isMessageSet = true |
| David Symonds | 4fee3b1 | 2010-11-11 10:00:13 +1100 | [diff] [blame] | 1016 | g.P() |
| 1017 | g.P("func (this *", ccTypeName, ") Marshal() ([]byte, os.Error) {") |
| 1018 | g.In() |
| 1019 | g.P("return ", g.ProtoPkg, ".MarshalMessageSet(this.ExtensionMap())") |
| 1020 | g.Out() |
| 1021 | g.P("}") |
| 1022 | g.P("func (this *", ccTypeName, ") Unmarshal(buf []byte) os.Error {") |
| 1023 | g.In() |
| 1024 | g.P("return ", g.ProtoPkg, ".UnmarshalMessageSet(buf, this.ExtensionMap())") |
| 1025 | g.Out() |
| 1026 | g.P("}") |
| 1027 | g.P("// ensure ", ccTypeName, " satisfies proto.Marshaler and proto.Unmarshaler") |
| 1028 | g.P("var _ ", g.ProtoPkg, ".Marshaler = (*", ccTypeName, ")(nil)") |
| 1029 | g.P("var _ ", g.ProtoPkg, ".Unmarshaler = (*", ccTypeName, ")(nil)") |
| 1030 | } |
| 1031 | |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 1032 | g.P() |
| Rob Pike | c9e7d97 | 2010-06-10 10:30:22 -0700 | [diff] [blame] | 1033 | g.P("var extRange_", ccTypeName, " = []", g.ProtoPkg, ".ExtensionRange{") |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 1034 | g.In() |
| 1035 | for _, r := range message.ExtensionRange { |
| Rob Pike | c9e7d97 | 2010-06-10 10:30:22 -0700 | [diff] [blame] | 1036 | end := fmt.Sprint(*r.End - 1) // make range inclusive on both ends |
| 1037 | g.P(g.ProtoPkg+".ExtensionRange{", r.Start, ", ", end, "},") |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 1038 | } |
| 1039 | g.Out() |
| 1040 | g.P("}") |
| Rob Pike | c9e7d97 | 2010-06-10 10:30:22 -0700 | [diff] [blame] | 1041 | g.P("func (*", ccTypeName, ") ExtensionRangeArray() []", g.ProtoPkg, ".ExtensionRange {") |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 1042 | g.In() |
| 1043 | g.P("return extRange_", ccTypeName) |
| 1044 | g.Out() |
| 1045 | g.P("}") |
| 1046 | g.P("func (this *", ccTypeName, ") ExtensionMap() map[int32][]byte {") |
| 1047 | g.In() |
| 1048 | g.P("if this.XXX_extensions == nil {") |
| 1049 | g.In() |
| 1050 | g.P("this.XXX_extensions = make(map[int32][]byte)") |
| 1051 | g.Out() |
| 1052 | g.P("}") |
| 1053 | g.P("return this.XXX_extensions") |
| 1054 | g.Out() |
| 1055 | g.P("}") |
| 1056 | } |
| 1057 | |
| David Symonds | 31d58a2 | 2011-01-20 18:33:21 +1100 | [diff] [blame] | 1058 | g.file.addExport(messageSymbol{ccTypeName, hasExtensions, isMessageSet}) |
| 1059 | |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 1060 | // Default constants |
| 1061 | for _, field := range message.Field { |
| 1062 | def := proto.GetString(field.DefaultValue) |
| 1063 | if def == "" { |
| 1064 | continue |
| 1065 | } |
| 1066 | fieldname := "Default_" + ccTypeName + "_" + CamelCase(*field.Name) |
| 1067 | typename, _ := g.GoType(message, field) |
| 1068 | if typename[0] == '*' { |
| 1069 | typename = typename[1:] |
| 1070 | } |
| 1071 | kind := "const " |
| 1072 | switch { |
| 1073 | case typename == "bool": |
| 1074 | case typename == "string": |
| 1075 | def = Quote(def) |
| 1076 | case typename == "[]byte": |
| 1077 | def = "[]byte(" + Quote(def) + ")" |
| 1078 | kind = "var " |
| David Symonds | cea785b | 2011-01-07 11:02:30 +1100 | [diff] [blame] | 1079 | case def == "inf", def == "-inf", def == "nan": |
| 1080 | // These names are known to, and defined by, the protocol language. |
| 1081 | switch def { |
| 1082 | case "inf": |
| 1083 | def = "math.Inf(1)" |
| 1084 | case "-inf": |
| 1085 | def = "math.Inf(-1)" |
| 1086 | case "nan": |
| 1087 | def = "math.NaN()" |
| 1088 | } |
| 1089 | if *field.Type == descriptor.FieldDescriptorProto_TYPE_FLOAT { |
| 1090 | def = "float32(" + def + ")" |
| 1091 | } |
| 1092 | kind = "var " |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 1093 | case *field.Type == descriptor.FieldDescriptorProto_TYPE_ENUM: |
| 1094 | // Must be an enum. Need to construct the prefixed name. |
| 1095 | obj := g.ObjectNamed(proto.GetString(field.TypeName)) |
| 1096 | enum, ok := obj.(*EnumDescriptor) |
| 1097 | if !ok { |
| Rob Pike | 5194c51 | 2010-10-14 13:02:16 -0700 | [diff] [blame] | 1098 | log.Println("don't know how to generate constant for", fieldname) |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 1099 | continue |
| 1100 | } |
| Rob Pike | 87af39e | 2010-07-19 10:48:02 -0700 | [diff] [blame] | 1101 | def = g.DefaultPackageName(enum) + enum.prefix() + def |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 1102 | } |
| 1103 | g.P(kind, fieldname, " ", typename, " = ", def) |
| David Symonds | 31d58a2 | 2011-01-20 18:33:21 +1100 | [diff] [blame] | 1104 | g.file.addExport(constOrVarSymbol{fieldname, kind}) |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 1105 | } |
| 1106 | g.P() |
| 1107 | |
| 1108 | for _, ext := range message.ext { |
| 1109 | g.generateExtension(ext) |
| 1110 | } |
| 1111 | } |
| 1112 | |
| 1113 | func (g *Generator) generateExtension(ext *ExtensionDescriptor) { |
| 1114 | // The full type name |
| 1115 | typeName := ext.TypeName() |
| 1116 | // Each scope of the extension is individually CamelCased, and all are joined with "_" with an "E_" prefix. |
| 1117 | for i, s := range typeName { |
| 1118 | typeName[i] = CamelCase(s) |
| 1119 | } |
| 1120 | ccTypeName := "E_" + strings.Join(typeName, "_") |
| 1121 | |
| 1122 | extendedType := "*" + g.TypeName(g.ObjectNamed(*ext.Extendee)) |
| 1123 | field := ext.FieldDescriptorProto |
| 1124 | fieldType, wireType := g.GoType(ext.parent, field) |
| 1125 | tag := g.goTag(field, wireType) |
| David Symonds | f90e338 | 2010-05-05 10:53:44 +1000 | [diff] [blame] | 1126 | g.RecordTypeUse(*ext.Extendee) |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 1127 | |
| Rob Pike | c9e7d97 | 2010-06-10 10:30:22 -0700 | [diff] [blame] | 1128 | g.P("var ", ccTypeName, " = &", g.ProtoPkg, ".ExtensionDesc{") |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 1129 | g.In() |
| 1130 | g.P("ExtendedType: (", extendedType, ")(nil),") |
| 1131 | g.P("ExtensionType: (", fieldType, ")(nil),") |
| 1132 | g.P("Field: ", field.Number, ",") |
| 1133 | g.P("Tag: ", tag, ",") |
| 1134 | |
| 1135 | g.Out() |
| 1136 | g.P("}") |
| 1137 | g.P() |
| David Symonds | 31d58a2 | 2011-01-20 18:33:21 +1100 | [diff] [blame] | 1138 | |
| 1139 | g.file.addExport(constOrVarSymbol{ccTypeName, "var"}) |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 1140 | } |
| 1141 | |
| 1142 | func (g *Generator) generateInitFunction() { |
| 1143 | g.P("func init() {") |
| 1144 | g.In() |
| 1145 | for _, enum := range g.file.enum { |
| 1146 | g.generateEnumRegistration(enum) |
| 1147 | } |
| 1148 | g.Out() |
| 1149 | g.P("}") |
| 1150 | } |
| 1151 | |
| 1152 | func (g *Generator) generateEnumRegistration(enum *EnumDescriptor) { |
| 1153 | pkg := g.packageName + "." // We always print the full package name here. |
| 1154 | // The full type name |
| 1155 | typeName := enum.TypeName() |
| 1156 | // The full type name, CamelCased. |
| 1157 | ccTypeName := CamelCaseSlice(typeName) |
| Rob Pike | c9e7d97 | 2010-06-10 10:30:22 -0700 | [diff] [blame] | 1158 | g.P(g.ProtoPkg+".RegisterEnum(", Quote(pkg+ccTypeName), ", ", ccTypeName+"_name, ", ccTypeName+"_value)") |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 1159 | } |
| 1160 | |
| 1161 | // And now lots of helper functions. |
| 1162 | |
| Rob Pike | 2c7bafc | 2010-06-10 16:07:14 -0700 | [diff] [blame] | 1163 | // Is c an ASCII lower-case letter? |
| 1164 | func isASCIILower(c byte) bool { |
| 1165 | return 'a' <= c && c <= 'z' |
| 1166 | } |
| 1167 | |
| 1168 | // Is c an ASCII digit? |
| 1169 | func isASCIIDigit(c byte) bool { |
| 1170 | return '0' <= c && c <= '9' |
| 1171 | } |
| 1172 | |
| 1173 | // CamelCase returns the CamelCased name. |
| 1174 | // If there is an interior underscore followed by a lower case letter, |
| 1175 | // drop the underscore and convert the letter to upper case. |
| 1176 | // There is a remote possibility of this rewrite causing a name collision, |
| 1177 | // but it's so remote we're prepared to pretend it's nonexistent - since the |
| 1178 | // C++ generator lowercases names, it's extremely unlikely to have two fields |
| 1179 | // with different capitalizations. |
| 1180 | // In short, _my_field_name_2 becomes XMyFieldName2. |
| 1181 | func CamelCase(s string) string { |
| 1182 | if s == "" { |
| 1183 | return "" |
| 1184 | } |
| 1185 | t := make([]byte, 0, 32) |
| Rob Pike | 2c7bafc | 2010-06-10 16:07:14 -0700 | [diff] [blame] | 1186 | i := 0 |
| 1187 | if s[0] == '_' { |
| 1188 | // Need a capital letter; drop the '_'. |
| Rob Pike | 99fa2b6 | 2010-12-02 10:39:42 -0800 | [diff] [blame] | 1189 | t = append(t, 'X') |
| Rob Pike | 2c7bafc | 2010-06-10 16:07:14 -0700 | [diff] [blame] | 1190 | i++ |
| 1191 | } |
| 1192 | // Invariant: if the next letter is lower case, it must be converted |
| 1193 | // to upper case. |
| 1194 | // That is, we process a word at a time, where words are marked by _ or |
| 1195 | // upper case letter. Digits are treated as words. |
| 1196 | for ; i < len(s); i++ { |
| 1197 | c := s[i] |
| Rob Pike | 2c7bafc | 2010-06-10 16:07:14 -0700 | [diff] [blame] | 1198 | if c == '_' && i+1 < len(s) && isASCIILower(s[i+1]) { |
| 1199 | continue // Skip the underscore in s. |
| 1200 | } |
| 1201 | if isASCIIDigit(c) { |
| Rob Pike | 99fa2b6 | 2010-12-02 10:39:42 -0800 | [diff] [blame] | 1202 | t = append(t, c) |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 1203 | continue |
| 1204 | } |
| Rob Pike | 2c7bafc | 2010-06-10 16:07:14 -0700 | [diff] [blame] | 1205 | // Assume we have a letter now - if not, it's a bogus identifier. |
| 1206 | // The next word is a sequence of characters that must start upper case. |
| 1207 | if isASCIILower(c) { |
| Rob Pike | 99fa2b6 | 2010-12-02 10:39:42 -0800 | [diff] [blame] | 1208 | c ^= ' ' // Make it a capital letter. |
| Rob Pike | 2c7bafc | 2010-06-10 16:07:14 -0700 | [diff] [blame] | 1209 | } |
| Rob Pike | 99fa2b6 | 2010-12-02 10:39:42 -0800 | [diff] [blame] | 1210 | t = append(t, c) // Guaranteed not lower case. |
| Rob Pike | 2c7bafc | 2010-06-10 16:07:14 -0700 | [diff] [blame] | 1211 | // Accept lower case sequence that follows. |
| 1212 | for i+1 < len(s) && isASCIILower(s[i+1]) { |
| 1213 | i++ |
| Rob Pike | 99fa2b6 | 2010-12-02 10:39:42 -0800 | [diff] [blame] | 1214 | t = append(t, s[i]) |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 1215 | } |
| 1216 | } |
| Rob Pike | 2c7bafc | 2010-06-10 16:07:14 -0700 | [diff] [blame] | 1217 | return string(t) |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 1218 | } |
| 1219 | |
| 1220 | // CamelCaseSlice is like CamelCase, but the argument is a slice of strings to |
| 1221 | // be joined with "_". |
| 1222 | func CamelCaseSlice(elem []string) string { return CamelCase(strings.Join(elem, "_")) } |
| 1223 | |
| 1224 | // dottedSlice turns a sliced name into a dotted name. |
| 1225 | func dottedSlice(elem []string) string { return strings.Join(elem, ".") } |
| 1226 | |
| 1227 | // Quote returns a Go-source quoted string representation of s. |
| 1228 | func Quote(s string) string { return fmt.Sprintf("%q", s) } |
| 1229 | |
| 1230 | // Given a .proto file name, return the output name for the generated Go program. |
| 1231 | func goFileName(name string) string { |
| Rob Pike | 87af39e | 2010-07-19 10:48:02 -0700 | [diff] [blame] | 1232 | ext := path.Ext(name) |
| 1233 | if ext == ".proto" || ext == ".protodevel" { |
| 1234 | name = name[0 : len(name)-len(ext)] |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 1235 | } |
| 1236 | return name + ".pb.go" |
| 1237 | } |
| 1238 | |
| 1239 | // Is this field optional? |
| 1240 | func isOptional(field *descriptor.FieldDescriptorProto) bool { |
| 1241 | return field.Label != nil && *field.Label == descriptor.FieldDescriptorProto_LABEL_OPTIONAL |
| 1242 | } |
| 1243 | |
| 1244 | // Is this field required? |
| 1245 | func isRequired(field *descriptor.FieldDescriptorProto) bool { |
| 1246 | return field.Label != nil && *field.Label == descriptor.FieldDescriptorProto_LABEL_REQUIRED |
| 1247 | } |
| 1248 | |
| 1249 | // Is this field repeated? |
| 1250 | func isRepeated(field *descriptor.FieldDescriptorProto) bool { |
| 1251 | return field.Label != nil && *field.Label == descriptor.FieldDescriptorProto_LABEL_REPEATED |
| 1252 | } |
| 1253 | |
| 1254 | // DotToUnderscore is the mapping function used to generate Go names from package names, |
| Rob Pike | c9e7d97 | 2010-06-10 10:30:22 -0700 | [diff] [blame] | 1255 | // which can be dotted in the input .proto file. It maps dots to underscores. |
| 1256 | // Because we also get here from package names generated from file names, it also maps |
| 1257 | // minus signs to underscores. |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 1258 | func DotToUnderscore(rune int) int { |
| Rob Pike | c9e7d97 | 2010-06-10 10:30:22 -0700 | [diff] [blame] | 1259 | switch rune { |
| 1260 | case '.', '-': |
| Rob Pike | af82b4e | 2010-04-30 15:19:25 -0700 | [diff] [blame] | 1261 | return '_' |
| 1262 | } |
| 1263 | return rune |
| 1264 | } |
| Rob Pike | c9e7d97 | 2010-06-10 10:30:22 -0700 | [diff] [blame] | 1265 | |
| 1266 | // BaseName returns the last path element of the name, with the last dotted suffix removed. |
| 1267 | func BaseName(name string) string { |
| 1268 | // First, find the last element |
| 1269 | if i := strings.LastIndex(name, "/"); i >= 0 { |
| 1270 | name = name[i+1:] |
| 1271 | } |
| 1272 | // Now drop the suffix |
| 1273 | if i := strings.LastIndex(name, "."); i >= 0 { |
| 1274 | name = name[0:i] |
| 1275 | } |
| 1276 | return name |
| 1277 | } |