blob: f6fb238112c5bcccacfcd4dd45b3701bb2651d7b [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"
44 "strings"
45 "unicode"
46
47 "goprotobuf.googlecode.com/hg/proto"
48 plugin "goprotobuf.googlecode.com/hg/compiler/plugin"
49 descriptor "goprotobuf.googlecode.com/hg/compiler/descriptor"
50)
51
52// A Plugin provides functionality to add to the output during Go code generation,
53// such as to produce RPC stubs.
54type Plugin interface {
55 // Name identifies the plugin.
Rob Pikec9e7d972010-06-10 10:30:22 -070056 Name() string
57 // Init is called once after data structures are built but before
58 // code generation begins.
59 Init(g *Generator)
60 // Generate produces the code generated by the plugin for this file,
61 // except for the imports, by calling the generator's methods P, In, and Out.
62 Generate(file *FileDescriptor)
Rob Pikeaf82b4e2010-04-30 15:19:25 -070063 // GenerateImports produces the import declarations for this file.
Rob Pikec9e7d972010-06-10 10:30:22 -070064 // It is called after Generate.
65 GenerateImports(file *FileDescriptor)
Rob Pikeaf82b4e2010-04-30 15:19:25 -070066}
67
68var plugins []Plugin
69
70// RegisterPlugin installs a (second-order) plugin to be run when the Go output is generated.
71// It is typically called during initialization.
72func RegisterPlugin(p Plugin) {
73 n := len(plugins)
74 if cap(plugins) == n {
Rob Pikec9e7d972010-06-10 10:30:22 -070075 nplugins := make([]Plugin, n, n+10) // very unlikely to need more than this
Rob Pikeaf82b4e2010-04-30 15:19:25 -070076 copy(nplugins, plugins)
77 plugins = nplugins
78 }
Rob Pikec9e7d972010-06-10 10:30:22 -070079 plugins = plugins[0 : n+1]
Rob Pikeaf82b4e2010-04-30 15:19:25 -070080 plugins[n] = p
Rob Pikeaf82b4e2010-04-30 15:19:25 -070081}
82
83// Each type we import as a protocol buffer (other than FileDescriptorProto) needs
84// a pointer to the FileDescriptorProto that represents it. These types achieve that
85// wrapping by placing each Proto inside a struct with the pointer to its File. The
86// structs have the same names as their contents, with "Proto" removed.
87// FileDescriptor is used to store the things that it points to.
88
89// The file and package name method are common to messages and enums.
90type common struct {
91 File *descriptor.FileDescriptorProto // File this object comes from.
92}
93
94// PackageName is name in the package clause in the generated file.
95func (c *common) PackageName() string { return uniquePackageOf(c.File) }
96
97// Descriptor represents a protocol buffer message.
98type Descriptor struct {
99 common
100 *descriptor.DescriptorProto
101 parent *Descriptor // The containing message, if any.
102 nested []*Descriptor // Inner messages, if any.
103 ext []*ExtensionDescriptor // Extensions, if any.
104 typename []string // Cached typename vector.
105}
106
107// TypeName returns the elements of the dotted type name.
108// The package name is not part of this name.
109func (d *Descriptor) TypeName() []string {
110 if d.typename != nil {
111 return d.typename
112 }
113 n := 0
114 for parent := d; parent != nil; parent = parent.parent {
115 n++
116 }
117 s := make([]string, n, n)
118 for parent := d; parent != nil; parent = parent.parent {
119 n--
120 s[n] = proto.GetString(parent.Name)
121 }
122 d.typename = s
123 return s
124}
125
126// EnumDescriptor describes an enum. If it's at top level, its parent will be nil.
127// Otherwise it will be the descriptor of the message in which it is defined.
128type EnumDescriptor struct {
129 common
130 *descriptor.EnumDescriptorProto
131 parent *Descriptor // The containing message, if any.
132 typename []string // Cached typename vector.
133}
134
135// TypeName returns the elements of the dotted type name.
136// The package name is not part of this name.
137func (e *EnumDescriptor) TypeName() (s []string) {
138 if e.typename != nil {
139 return e.typename
140 }
141 name := proto.GetString(e.Name)
142 if e.parent == nil {
143 s = make([]string, 1)
144 } else {
145 pname := e.parent.TypeName()
146 s = make([]string, len(pname)+1)
147 copy(s, pname)
148 }
149 s[len(s)-1] = name
150 e.typename = s
151 return s
152}
153
154// Everything but the last element of the full type name, CamelCased.
155// The values of type Foo.Bar are call Foo_value1... not Foo_Bar_value1... .
156func (e *EnumDescriptor) prefix() string {
157 typeName := e.TypeName()
158 ccPrefix := CamelCaseSlice(typeName[0:len(typeName)-1]) + "_"
159 if e.parent == nil {
160 // If the enum is not part of a message, the prefix is just the type name.
161 ccPrefix = CamelCase(*e.Name) + "_"
162 }
163 return ccPrefix
164}
165
166// The integer value of the named constant in this enumerated type.
167func (e *EnumDescriptor) integerValueAsString(name string) string {
168 for _, c := range e.Value {
169 if proto.GetString(c.Name) == name {
170 return fmt.Sprint(proto.GetInt32(c.Number))
171 }
172 }
173 log.Exit("cannot find value for enum constant")
174 return ""
175}
176
177// ExtensionDescriptor desribes an extension. If it's at top level, its parent will be nil.
178// Otherwise it will be the descriptor of the message in which it is defined.
179type ExtensionDescriptor struct {
180 common
181 *descriptor.FieldDescriptorProto
Rob Pikec9e7d972010-06-10 10:30:22 -0700182 parent *Descriptor // The containing message, if any.
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700183}
184
185// TypeName returns the elements of the dotted type name.
186// The package name is not part of this name.
187func (e *ExtensionDescriptor) TypeName() (s []string) {
188 name := proto.GetString(e.Name)
189 if e.parent == nil {
190 // top-level extension
191 s = make([]string, 1)
192 } else {
193 pname := e.parent.TypeName()
194 s = make([]string, len(pname)+1)
195 copy(s, pname)
196 }
197 s[len(s)-1] = name
198 return s
199}
200
201// FileDescriptor describes an protocol buffer descriptor file (.proto).
202// It includes slices of all the messages and enums defined within it.
203// Those slices are constructed by WrapTypes.
204type FileDescriptor struct {
205 *descriptor.FileDescriptorProto
Rob Pikec9e7d972010-06-10 10:30:22 -0700206 desc []*Descriptor // All the messages defined in this file.
207 enum []*EnumDescriptor // All the enums defined in this file.
208 ext []*ExtensionDescriptor // All the top-level extensions defined in this file.
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700209}
210
211// PackageName is the package name we'll use in the generated code to refer to this file.
212func (d *FileDescriptor) PackageName() string { return uniquePackageOf(d.FileDescriptorProto) }
213
214// The package named defined in the input for this file, possibly dotted.
Rob Pikec9e7d972010-06-10 10:30:22 -0700215// If the file does not define a package, use the base of the file name.
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700216func (d *FileDescriptor) originalPackageName() string {
Rob Pikec9e7d972010-06-10 10:30:22 -0700217 // Does the file have a package clause?
218 pkg := proto.GetString(d.Package)
219 if pkg != "" {
220 return pkg
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700221 }
Rob Pikec9e7d972010-06-10 10:30:22 -0700222 // Use the file base name.
223 return BaseName(proto.GetString(d.Name))
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700224}
225
226// Object is an interface abstracting the abilities shared by enums and messages.
227type Object interface {
228 PackageName() string // The name we use in our output (a_b_c), possibly renamed for uniqueness.
229 TypeName() []string
230}
231
232// Each package name we generate must be unique. The package we're generating
233// gets its own name but every other package must have a unqiue name that does
234// not conflict in the code we generate. These names are chosen globally (although
235// they don't have to be, it simplifies things to do them globally).
236func uniquePackageOf(fd *descriptor.FileDescriptorProto) string {
237 s, ok := uniquePackageName[fd]
238 if !ok {
239 log.Exit("internal error: no package name defined for", proto.GetString(fd.Name))
240 }
241 return s
242}
243
244// Generator is the type whose methods generate the output, stored in the associated response structure.
245type Generator struct {
David Symondsf90e3382010-05-05 10:53:44 +1000246 *bytes.Buffer
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700247
248 Request *plugin.CodeGeneratorRequest // The input.
249 Response *plugin.CodeGeneratorResponse // The output.
250
Rob Pikec9e7d972010-06-10 10:30:22 -0700251 Param map[string]string // Command-line parameters.
252 ImportPrefix string // String to prefix to imported package file names.
253 ImportMap map[string]string // Mapping from import name to generated name
254
255 ProtoPkg string // The name under which we import the library's package proto.
256
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700257 packageName string // What we're calling ourselves.
258 allFiles []*FileDescriptor // All files in the tree
259 genFiles []*FileDescriptor // Those files we will generate output for.
260 file *FileDescriptor // The file we are compiling now.
David Symondsf90e3382010-05-05 10:53:44 +1000261 usedPackages map[string]bool // Names of packages used in current file.
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700262 typeNameToObject map[string]Object // Key is a fully-qualified name in input syntax.
263 indent string
264}
265
266// New creates a new generator and allocates the request and response protobufs.
267func New() *Generator {
268 g := new(Generator)
David Symondsf90e3382010-05-05 10:53:44 +1000269 g.Buffer = new(bytes.Buffer)
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700270 g.Request = plugin.NewCodeGeneratorRequest()
271 g.Response = plugin.NewCodeGeneratorResponse()
272 return g
273}
274
275// Error reports a problem, including an os.Error, and exits the program.
276func (g *Generator) Error(err os.Error, msgs ...string) {
277 s := strings.Join(msgs, " ") + ":" + err.String()
278 log.Stderr("protoc-gen-go: error: ", s)
279 g.Response.Error = proto.String(s)
280 os.Exit(1)
281}
282
283// Fail reports a problem and exits the program.
284func (g *Generator) Fail(msgs ...string) {
285 s := strings.Join(msgs, " ")
286 log.Stderr("protoc-gen-go: error: ", s)
287 g.Response.Error = proto.String(s)
288 os.Exit(1)
289}
290
Rob Pikec9e7d972010-06-10 10:30:22 -0700291// CommandLineParameters breaks the comma-separated list of key=value pairs
292// in the parameter (a member of the request protobuf) into a key/value map.
293// It then sets file name mappings defined by those entries.
294func (g *Generator) CommandLineParameters(parameter string) {
295 g.Param = make(map[string]string)
296 for _, p := range strings.Split(parameter, ",", 0) {
297 if i := strings.Index(p, "="); i < 0 {
298 g.Param[p] = ""
299 } else {
300 g.Param[p[0:i]] = p[i+1:]
301 }
302 }
303
304 g.ImportMap = make(map[string]string)
305 for k, v := range g.Param {
306 if k == "import_prefix" {
307 g.ImportPrefix = v
308 } else if len(k) > 0 && k[0] == 'M' {
309 g.ImportMap[k[1:]] = v
310 }
311 }
312}
313
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700314// DefaultPackageName returns the package name printed for the object.
315// If its file is in a different package, it returns the package name we're using for this file, plus ".".
316// Otherwise it returns the empty string.
317func (g *Generator) DefaultPackageName(obj Object) string {
318 pkg := obj.PackageName()
319 if pkg == g.packageName {
320 return ""
321 }
322 return pkg + "."
323}
324
325// For each input file, the unique package name to use, underscored.
326var uniquePackageName = make(map[*descriptor.FileDescriptorProto]string)
Rob Pikec9e7d972010-06-10 10:30:22 -0700327// Package names already registered. Key is the name from the .proto file;
328// value is the name that appears in the generated code.
329var pkgNamesInUse = make(map[string]bool)
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700330
Rob Pikec9e7d972010-06-10 10:30:22 -0700331// Create and remember a guaranteed unique package name for this file descriptor.
332// Pkg is the candidate name. If f is nil, it's a builtin package like "proto" and
333// has no file descriptor.
334func RegisterUniquePackageName(pkg string, f *FileDescriptor) string {
335 for pkgNamesInUse[pkg] {
336 // It's a duplicate; must rename.
337 pkg += "X"
338 }
339 // Install it.
340 pkgNamesInUse[pkg] = true
341 pkg = strings.Map(DotToUnderscore, pkg)
342 if f != nil {
343 uniquePackageName[f.FileDescriptorProto] = pkg
344 }
345 return pkg
346}
347
348// SetPackageNames sets the package name for this run.
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700349// The package name must agree across all files being generated.
350// It also defines unique package names for all imported files.
351func (g *Generator) SetPackageNames() {
Rob Pikec9e7d972010-06-10 10:30:22 -0700352 // Register the name for this package. It will be the first name
353 // registered so is guaranteed to be unmodified.
354 pkg := g.genFiles[0].originalPackageName()
355 g.packageName = RegisterUniquePackageName(pkg, g.genFiles[0])
356 // Register the proto package name. It might collide with the
357 // name of a package we import.
358 g.ProtoPkg = RegisterUniquePackageName("proto", nil)
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700359 for _, f := range g.genFiles {
Rob Pikec9e7d972010-06-10 10:30:22 -0700360 thisPkg := f.originalPackageName()
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700361 if thisPkg != pkg {
362 g.Fail("inconsistent package names:", thisPkg, pkg)
363 }
364 }
365AllFiles:
366 for _, f := range g.allFiles {
367 for _, genf := range g.genFiles {
368 if f == genf {
369 // In this package already.
370 uniquePackageName[f.FileDescriptorProto] = g.packageName
371 continue AllFiles
372 }
373 }
Rob Pikec9e7d972010-06-10 10:30:22 -0700374 RegisterUniquePackageName(f.originalPackageName(), f)
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700375 }
376}
377
378// WrapTypes walks the incoming data, wrapping DescriptorProtos, EnumDescriptorProtos
379// and FileDescriptorProtos into file-referenced objects within the Generator.
380// It also creates the list of files to generate and so should be called before GenerateAllFiles.
381func (g *Generator) WrapTypes() {
382 g.allFiles = make([]*FileDescriptor, len(g.Request.ProtoFile))
383 for i, f := range g.Request.ProtoFile {
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700384 // We must wrap the descriptors before we wrap the enums
385 descs := wrapDescriptors(f)
386 g.buildNestedDescriptors(descs)
387 enums := wrapEnumDescriptors(f, descs)
388 exts := wrapExtensions(f)
389 g.allFiles[i] = &FileDescriptor{
390 FileDescriptorProto: f,
391 desc: descs,
392 enum: enums,
393 ext: exts,
394 }
395 }
396
397 g.genFiles = make([]*FileDescriptor, len(g.Request.FileToGenerate))
398FindFiles:
399 for i, fileName := range g.Request.FileToGenerate {
400 // Search the list. This algorithm is n^2 but n is tiny.
401 for _, file := range g.allFiles {
402 if fileName == proto.GetString(file.Name) {
403 g.genFiles[i] = file
404 continue FindFiles
405 }
406 }
407 g.Fail("could not find file named", fileName)
408 }
409 g.Response.File = make([]*plugin.CodeGeneratorResponse_File, len(g.genFiles))
410}
411
412// Scan the descriptors in this file. For each one, build the slice of nested descriptors
413func (g *Generator) buildNestedDescriptors(descs []*Descriptor) {
414 for _, desc := range descs {
415 if len(desc.NestedType) != 0 {
416 desc.nested = make([]*Descriptor, len(desc.NestedType))
417 n := 0
418 for _, nest := range descs {
419 if nest.parent == desc {
420 desc.nested[n] = nest
421 n++
422 }
423 }
424 if n != len(desc.NestedType) {
425 g.Fail("internal error: nesting failure for", proto.GetString(desc.Name))
426 }
427 }
428 }
429}
430
431// Construct the Descriptor and add it to the slice
432func addDescriptor(sl []*Descriptor, desc *descriptor.DescriptorProto, parent *Descriptor, file *descriptor.FileDescriptorProto) []*Descriptor {
433 d := &Descriptor{common{File: file}, desc, parent, nil, nil, nil}
434
435 d.ext = make([]*ExtensionDescriptor, len(desc.Extension))
436 for i, field := range desc.Extension {
437 d.ext[i] = &ExtensionDescriptor{common{File: file}, field, d}
438 }
439
440 if len(sl) == cap(sl) {
441 nsl := make([]*Descriptor, len(sl), 2*len(sl))
442 copy(nsl, sl)
443 sl = nsl
444 }
445 sl = sl[0 : len(sl)+1]
446 sl[len(sl)-1] = d
447 return sl
448}
449
450// Return a slice of all the Descriptors defined within this file
451func wrapDescriptors(file *descriptor.FileDescriptorProto) []*Descriptor {
452 sl := make([]*Descriptor, 0, len(file.MessageType)+10)
453 for _, desc := range file.MessageType {
454 sl = wrapThisDescriptor(sl, desc, nil, file)
455 }
456 return sl
457}
458
459// Wrap this Descriptor, recursively
460func wrapThisDescriptor(sl []*Descriptor, desc *descriptor.DescriptorProto, parent *Descriptor, file *descriptor.FileDescriptorProto) []*Descriptor {
461 sl = addDescriptor(sl, desc, parent, file)
462 me := sl[len(sl)-1]
463 for _, nested := range desc.NestedType {
464 sl = wrapThisDescriptor(sl, nested, me, file)
465 }
466 return sl
467}
468
469// Construct the EnumDescriptor and add it to the slice
470func addEnumDescriptor(sl []*EnumDescriptor, desc *descriptor.EnumDescriptorProto, parent *Descriptor, file *descriptor.FileDescriptorProto) []*EnumDescriptor {
471 if len(sl) == cap(sl) {
472 nsl := make([]*EnumDescriptor, len(sl), 2*len(sl))
473 copy(nsl, sl)
474 sl = nsl
475 }
476 sl = sl[0 : len(sl)+1]
477 sl[len(sl)-1] = &EnumDescriptor{common{File: file}, desc, parent, nil}
478 return sl
479}
480
481// Return a slice of all the EnumDescriptors defined within this file
482func wrapEnumDescriptors(file *descriptor.FileDescriptorProto, descs []*Descriptor) []*EnumDescriptor {
483 sl := make([]*EnumDescriptor, 0, len(file.EnumType)+10)
484 for _, enum := range file.EnumType {
485 sl = addEnumDescriptor(sl, enum, nil, file)
486 }
487 for _, nested := range descs {
488 sl = wrapEnumDescriptorsInMessage(sl, nested, file)
489 }
490 return sl
491}
492
493// Wrap this EnumDescriptor, recursively
494func wrapEnumDescriptorsInMessage(sl []*EnumDescriptor, desc *Descriptor, file *descriptor.FileDescriptorProto) []*EnumDescriptor {
495 for _, enum := range desc.EnumType {
496 sl = addEnumDescriptor(sl, enum, desc, file)
497 }
498 for _, nested := range desc.nested {
499 sl = wrapEnumDescriptorsInMessage(sl, nested, file)
500 }
501 return sl
502}
503
504// Return a slice of all the top-level ExtensionDescriptors defined within this file.
505func wrapExtensions(file *descriptor.FileDescriptorProto) []*ExtensionDescriptor {
506 sl := make([]*ExtensionDescriptor, len(file.Extension))
507 for i, field := range file.Extension {
508 sl[i] = &ExtensionDescriptor{common{File: file}, field, nil}
509 }
510 return sl
511}
512
Rob Pikec9e7d972010-06-10 10:30:22 -0700513// BuildTypeNameMap builds the map from fully qualified type names to objects.
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700514// The key names for the map come from the input data, which puts a period at the beginning.
515// It should be called after SetPackageNames and before GenerateAllFiles.
516func (g *Generator) BuildTypeNameMap() {
517 g.typeNameToObject = make(map[string]Object)
518 for _, f := range g.allFiles {
Rob Pikec9e7d972010-06-10 10:30:22 -0700519 // The names in this loop are defined by the proto world, not us, so the
520 // package name may be empty. If so, the dotted package name of X will
521 // be ".X"; otherwise it will be ".pkg.X".
522 dottedPkg := "." + proto.GetString(f.Package)
523 if dottedPkg != "." {
524 dottedPkg += "."
525 }
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700526 for _, enum := range f.enum {
527 name := dottedPkg + dottedSlice(enum.TypeName())
528 g.typeNameToObject[name] = enum
529 }
530 for _, desc := range f.desc {
531 name := dottedPkg + dottedSlice(desc.TypeName())
532 g.typeNameToObject[name] = desc
533 }
534 }
535}
536
537// ObjectNamed, given a fully-qualified input type name as it appears in the input data,
538// returns the descriptor for the message or enum with that name.
539func (g *Generator) ObjectNamed(typeName string) Object {
540 f, ok := g.typeNameToObject[typeName]
541 if !ok {
542 g.Fail("can't find object with type", typeName)
543 }
544 return f
545}
546
547// P prints the arguments to the generated output. It handles strings and int32s, plus
548// handling indirections because they may be *string, etc.
549func (g *Generator) P(str ...interface{}) {
550 g.WriteString(g.indent)
551 for _, v := range str {
552 switch s := v.(type) {
553 case string:
554 g.WriteString(s)
555 case *string:
556 g.WriteString(*s)
Rob Pikec9e7d972010-06-10 10:30:22 -0700557 case bool:
558 g.WriteString(fmt.Sprintf("%t", s))
559 case *bool:
560 g.WriteString(fmt.Sprintf("%t", *s))
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700561 case *int32:
562 g.WriteString(fmt.Sprintf("%d", *s))
Rob Pikec9e7d972010-06-10 10:30:22 -0700563 case float64:
564 g.WriteString(fmt.Sprintf("%g", s))
565 case *float64:
566 g.WriteString(fmt.Sprintf("%g", *s))
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700567 default:
568 g.Fail(fmt.Sprintf("unknown type in printer: %T", v))
569 }
570 }
571 g.WriteByte('\n')
572}
573
574// In Indents the output one tab stop.
575func (g *Generator) In() { g.indent += "\t" }
576
577// Out unindents the output one tab stop.
578func (g *Generator) Out() {
579 if len(g.indent) > 0 {
580 g.indent = g.indent[1:]
581 }
582}
583
584// GenerateAllFiles generates the output for all the files we're outputting.
585func (g *Generator) GenerateAllFiles() {
Rob Pikec9e7d972010-06-10 10:30:22 -0700586 // Initialize the plugins
587 for _, p := range plugins {
588 p.Init(g)
589 }
590 // Generate the output.
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700591 for i, file := range g.genFiles {
592 g.Reset()
593 g.generate(file)
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700594 g.Response.File[i] = plugin.NewCodeGeneratorResponse_File()
595 g.Response.File[i].Name = proto.String(goFileName(*file.Name))
596 g.Response.File[i].Content = proto.String(g.String())
597 }
598}
599
600// Run all the plugins associated with the file.
601func (g *Generator) runPlugins(file *FileDescriptor) {
602 for _, p := range plugins {
Rob Pikec9e7d972010-06-10 10:30:22 -0700603 p.Generate(file)
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700604 }
605}
606
607
608// FileOf return the FileDescriptor for this FileDescriptorProto.
609func (g *Generator) FileOf(fd *descriptor.FileDescriptorProto) *FileDescriptor {
610 for _, file := range g.allFiles {
611 if file.FileDescriptorProto == fd {
612 return file
613 }
614 }
615 g.Fail("could not find file in table:", proto.GetString(fd.Name))
616 return nil
617}
618
619// Fill the response protocol buffer with the generated output for all the files we're
620// supposed to generate.
621func (g *Generator) generate(file *FileDescriptor) {
622 g.file = g.FileOf(file.FileDescriptorProto)
David Symondsf90e3382010-05-05 10:53:44 +1000623 g.usedPackages = make(map[string]bool)
624
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700625 for _, enum := range g.file.enum {
626 g.generateEnum(enum)
627 }
628 for _, desc := range g.file.desc {
629 g.generateMessage(desc)
630 }
631 for _, ext := range g.file.ext {
632 g.generateExtension(ext)
633 }
634 g.generateInitFunction()
David Symondsf90e3382010-05-05 10:53:44 +1000635
Rob Pikec9e7d972010-06-10 10:30:22 -0700636 // Run the plugins before the imports so we know which imports are necessary.
637 g.runPlugins(file)
638
David Symondsf90e3382010-05-05 10:53:44 +1000639 // Generate header and imports last, though they appear first in the output.
640 rem := g.Buffer
641 g.Buffer = new(bytes.Buffer)
642 g.generateHeader()
643 g.generateImports()
644 g.Write(rem.Bytes())
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700645}
646
647// Generate the header, including package definition and imports
648func (g *Generator) generateHeader() {
649 g.P("// Code generated by protoc-gen-go from ", Quote(*g.file.Name))
650 g.P("// DO NOT EDIT!")
651 g.P()
652 g.P("package ", g.file.PackageName())
653 g.P()
654}
655
656// Generate the header, including package definition and imports
657func (g *Generator) generateImports() {
Rob Pikec9e7d972010-06-10 10:30:22 -0700658 // We almost always need a proto import. Rather than computing when we
659 // do, which is tricky when there's a plugin, just import it and
660 // reference it later.
661 g.P("import " + g.ProtoPkg + " " + Quote(g.ImportPrefix+"net/proto2/go/proto"))
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700662 for _, s := range g.file.Dependency {
663 // Need to find the descriptor for this file
664 for _, fd := range g.allFiles {
Rob Pikec9e7d972010-06-10 10:30:22 -0700665 // Do not import our own package.
666 if fd.PackageName() == g.packageName {
667 continue
668 }
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700669 if proto.GetString(fd.Name) == s {
670 filename := goFileName(s)
Rob Pikec9e7d972010-06-10 10:30:22 -0700671 if substitution, ok := g.ImportMap[s]; ok {
672 filename = substitution
673 }
674 filename = g.ImportPrefix + filename
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700675 if strings.HasSuffix(filename, ".go") {
Rob Pikec9e7d972010-06-10 10:30:22 -0700676 filename = filename[0 : len(filename)-3]
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700677 }
David Symondsf90e3382010-05-05 10:53:44 +1000678 if _, ok := g.usedPackages[fd.PackageName()]; ok {
679 g.P("import ", fd.PackageName(), " ", Quote(filename))
680 } else {
681 log.Stderr("protoc-gen-go: discarding unused import: ", filename)
682 }
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700683 break
684 }
685 }
686 }
687 g.P()
688 // TODO: may need to worry about uniqueness across plugins
689 for _, p := range plugins {
Rob Pikec9e7d972010-06-10 10:30:22 -0700690 p.GenerateImports(g.file)
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700691 g.P()
692 }
Rob Pikec9e7d972010-06-10 10:30:22 -0700693 g.P("// Reference proto import to suppress error if it's not otherwise used.")
694 g.P("var _ = ", g.ProtoPkg, ".GetString")
695 g.P()
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700696}
697
698// Generate the enum definitions for this EnumDescriptor.
699func (g *Generator) generateEnum(enum *EnumDescriptor) {
700 // The full type name
701 typeName := enum.TypeName()
702 // The full type name, CamelCased.
703 ccTypeName := CamelCaseSlice(typeName)
704 ccPrefix := enum.prefix()
705 g.P("type ", ccTypeName, " int32")
706 g.P("const (")
707 g.In()
708 for _, e := range enum.Value {
709 g.P(ccPrefix+*e.Name, " = ", e.Number)
710 }
711 g.Out()
712 g.P(")")
713 g.P("var ", ccTypeName, "_name = map[int32] string {")
714 g.In()
Rob Pikec9e7d972010-06-10 10:30:22 -0700715 generated := make(map[int32]bool) // avoid duplicate values
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700716 for _, e := range enum.Value {
717 duplicate := ""
718 if _, present := generated[*e.Number]; present {
719 duplicate = "// Duplicate value: "
720 }
721 g.P(duplicate, e.Number, ": ", Quote(*e.Name), ",")
722 generated[*e.Number] = true
723 }
724 g.Out()
725 g.P("}")
726 g.P("var ", ccTypeName, "_value = map[string] int32 {")
727 g.In()
728 for _, e := range enum.Value {
729 g.P(Quote(*e.Name), ": ", e.Number, ",")
730 }
731 g.Out()
732 g.P("}")
733 g.P("func New", ccTypeName, "(x int32) *", ccTypeName, " {")
734 g.In()
735 g.P("e := ", ccTypeName, "(x)")
736 g.P("return &e")
737 g.Out()
738 g.P("}")
739 g.P()
740}
741
742// The tag is a string like "PB(varint,2,opt,name=fieldname,def=7)" that
743// identifies details of the field for the protocol buffer marshaling and unmarshaling
744// code. The fields are:
745// wire encoding
746// protocol tag number
747// opt,req,rep for optional, required, or repeated
748// name= the original declared name
749// enum= the name of the enum type if it is an enum-typed field.
750// def= string representation of the default value, if any.
751// The default value must be in a representation that can be used at run-time
752// to generate the default value. Thus bools become 0 and 1, for instance.
753func (g *Generator) goTag(field *descriptor.FieldDescriptorProto, wiretype string) string {
754 optrepreq := ""
755 switch {
756 case isOptional(field):
757 optrepreq = "opt"
758 case isRequired(field):
759 optrepreq = "req"
760 case isRepeated(field):
761 optrepreq = "rep"
762 }
763 defaultValue := proto.GetString(field.DefaultValue)
764 if defaultValue != "" {
765 switch *field.Type {
766 case descriptor.FieldDescriptorProto_TYPE_BOOL:
767 if defaultValue == "true" {
768 defaultValue = "1"
769 } else {
770 defaultValue = "0"
771 }
772 case descriptor.FieldDescriptorProto_TYPE_STRING,
773 descriptor.FieldDescriptorProto_TYPE_BYTES:
774 // Protect frogs.
775 defaultValue = Quote(defaultValue)
776 // Don't need the quotes
777 defaultValue = defaultValue[1 : len(defaultValue)-1]
778 case descriptor.FieldDescriptorProto_TYPE_ENUM:
779 // For enums we need to provide the integer constant.
780 obj := g.ObjectNamed(proto.GetString(field.TypeName))
781 enum, ok := obj.(*EnumDescriptor)
782 if !ok {
783 g.Fail("enum type inconsistent for", CamelCaseSlice(obj.TypeName()))
784 }
785 defaultValue = enum.integerValueAsString(defaultValue)
786 }
787 defaultValue = ",def=" + defaultValue
788 }
789 enum := ""
790 if *field.Type == descriptor.FieldDescriptorProto_TYPE_ENUM {
791 obj := g.ObjectNamed(proto.GetString(field.TypeName))
792 enum = ",enum=" + obj.PackageName() + "." + CamelCaseSlice(obj.TypeName())
793 }
794 name := proto.GetString(field.Name)
795 if name == CamelCase(name) {
796 name = ""
797 } else {
798 name = ",name=" + name
799 }
800 return Quote(fmt.Sprintf("PB(%s,%d,%s%s%s%s)",
801 wiretype,
802 proto.GetInt32(field.Number),
803 optrepreq,
804 name,
805 enum,
806 defaultValue))
807}
808
809func needsStar(typ descriptor.FieldDescriptorProto_Type) bool {
810 switch typ {
811 case descriptor.FieldDescriptorProto_TYPE_GROUP:
812 return false
813 case descriptor.FieldDescriptorProto_TYPE_MESSAGE:
814 return false
815 case descriptor.FieldDescriptorProto_TYPE_BYTES:
816 return false
817 }
818 return true
819}
820
821// TypeName is the printed name appropriate for an item. If the object is in the current file,
822// TypeName drops the package name and underscores the rest.
823// Otherwise the object is from another package; and the result is the underscored
824// package name followed by the item name.
825// The result always has an initial capital.
826func (g *Generator) TypeName(obj Object) string {
827 return g.DefaultPackageName(obj) + CamelCaseSlice(obj.TypeName())
828}
829
830// TypeNameWithPackage is like TypeName, but always includes the package
831// name even if the object is in our own package.
832func (g *Generator) TypeNameWithPackage(obj Object) string {
833 return obj.PackageName() + CamelCaseSlice(obj.TypeName())
834}
835
836// GoType returns a string representing the type name, and the wire type
837func (g *Generator) GoType(message *Descriptor, field *descriptor.FieldDescriptorProto) (typ string, wire string) {
838 // TODO: Options.
839 switch *field.Type {
840 case descriptor.FieldDescriptorProto_TYPE_DOUBLE:
841 typ, wire = "float64", "fixed64"
842 case descriptor.FieldDescriptorProto_TYPE_FLOAT:
843 typ, wire = "float32", "fixed32"
844 case descriptor.FieldDescriptorProto_TYPE_INT64:
845 typ, wire = "int64", "varint"
846 case descriptor.FieldDescriptorProto_TYPE_UINT64:
847 typ, wire = "uint64", "varint"
848 case descriptor.FieldDescriptorProto_TYPE_INT32:
849 typ, wire = "int32", "varint"
850 case descriptor.FieldDescriptorProto_TYPE_UINT32:
851 typ, wire = "uint32", "varint"
852 case descriptor.FieldDescriptorProto_TYPE_FIXED64:
853 typ, wire = "uint64", "fixed64"
854 case descriptor.FieldDescriptorProto_TYPE_FIXED32:
855 typ, wire = "uint32", "fixed32"
856 case descriptor.FieldDescriptorProto_TYPE_BOOL:
857 typ, wire = "bool", "varint"
858 case descriptor.FieldDescriptorProto_TYPE_STRING:
859 typ, wire = "string", "bytes"
860 case descriptor.FieldDescriptorProto_TYPE_GROUP:
861 desc := g.ObjectNamed(proto.GetString(field.TypeName))
862 typ, wire = "*"+g.TypeName(desc), "group"
863 case descriptor.FieldDescriptorProto_TYPE_MESSAGE:
864 desc := g.ObjectNamed(proto.GetString(field.TypeName))
865 typ, wire = "*"+g.TypeName(desc), "bytes"
866 case descriptor.FieldDescriptorProto_TYPE_BYTES:
867 typ, wire = "[]byte", "bytes"
868 case descriptor.FieldDescriptorProto_TYPE_ENUM:
869 desc := g.ObjectNamed(proto.GetString(field.TypeName))
870 typ, wire = g.TypeName(desc), "varint"
871 case descriptor.FieldDescriptorProto_TYPE_SFIXED32:
872 typ, wire = "int32", "fixed32"
873 case descriptor.FieldDescriptorProto_TYPE_SFIXED64:
874 typ, wire = "int64", "fixed64"
875 case descriptor.FieldDescriptorProto_TYPE_SINT32:
876 typ, wire = "int32", "zigzag32"
877 case descriptor.FieldDescriptorProto_TYPE_SINT64:
878 typ, wire = "int64", "zigzag64"
879 default:
880 g.Fail("unknown type for", proto.GetString(field.Name))
881 }
882 if isRepeated(field) {
883 typ = "[]" + typ
884 } else if needsStar(*field.Type) {
885 typ = "*" + typ
886 }
887 return
888}
889
David Symondsf90e3382010-05-05 10:53:44 +1000890func (g *Generator) RecordTypeUse(t string) {
891 if obj, ok := g.typeNameToObject[t]; ok {
892 g.usedPackages[obj.PackageName()] = true
893 }
894}
895
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700896// Generate the type and default constant definitions for this Descriptor.
897func (g *Generator) generateMessage(message *Descriptor) {
898 // The full type name
899 typeName := message.TypeName()
900 // The full type name, CamelCased.
901 ccTypeName := CamelCaseSlice(typeName)
902
903 g.P("type ", ccTypeName, " struct {")
904 g.In()
905 for _, field := range message.Field {
906 fieldname := CamelCase(*field.Name)
907 typename, wiretype := g.GoType(message, field)
908 tag := g.goTag(field, wiretype)
909 g.P(fieldname, "\t", typename, "\t", tag)
David Symondsf90e3382010-05-05 10:53:44 +1000910 g.RecordTypeUse(proto.GetString(field.TypeName))
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700911 }
912 if len(message.ExtensionRange) > 0 {
913 g.P("XXX_extensions\t\tmap[int32][]byte")
914 }
915 g.P("XXX_unrecognized\t[]byte")
916 g.Out()
917 g.P("}")
918
919 // Reset and New functions
920 g.P("func (this *", ccTypeName, ") Reset() {")
921 g.In()
922 g.P("*this = ", ccTypeName, "{}")
923 g.Out()
924 g.P("}")
925 g.P("func New", ccTypeName, "() *", ccTypeName, " {")
926 g.In()
927 g.P("return new(", ccTypeName, ")")
928 g.Out()
929 g.P("}")
930
931 // Extension support methods
932 if len(message.ExtensionRange) > 0 {
933 g.P()
Rob Pikec9e7d972010-06-10 10:30:22 -0700934 g.P("var extRange_", ccTypeName, " = []", g.ProtoPkg, ".ExtensionRange{")
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700935 g.In()
936 for _, r := range message.ExtensionRange {
Rob Pikec9e7d972010-06-10 10:30:22 -0700937 end := fmt.Sprint(*r.End - 1) // make range inclusive on both ends
938 g.P(g.ProtoPkg+".ExtensionRange{", r.Start, ", ", end, "},")
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700939 }
940 g.Out()
941 g.P("}")
Rob Pikec9e7d972010-06-10 10:30:22 -0700942 g.P("func (*", ccTypeName, ") ExtensionRangeArray() []", g.ProtoPkg, ".ExtensionRange {")
Rob Pikeaf82b4e2010-04-30 15:19:25 -0700943 g.In()
944 g.P("return extRange_", ccTypeName)
945 g.Out()
946 g.P("}")
947 g.P("func (this *", ccTypeName, ") ExtensionMap() map[int32][]byte {")
948 g.In()
949 g.P("if this.XXX_extensions == nil {")
950 g.In()
951 g.P("this.XXX_extensions = make(map[int32][]byte)")
952 g.Out()
953 g.P("}")
954 g.P("return this.XXX_extensions")
955 g.Out()
956 g.P("}")
957 }
958
959 // Default constants
960 for _, field := range message.Field {
961 def := proto.GetString(field.DefaultValue)
962 if def == "" {
963 continue
964 }
965 fieldname := "Default_" + ccTypeName + "_" + CamelCase(*field.Name)
966 typename, _ := g.GoType(message, field)
967 if typename[0] == '*' {
968 typename = typename[1:]
969 }
970 kind := "const "
971 switch {
972 case typename == "bool":
973 case typename == "string":
974 def = Quote(def)
975 case typename == "[]byte":
976 def = "[]byte(" + Quote(def) + ")"
977 kind = "var "
978 case *field.Type == descriptor.FieldDescriptorProto_TYPE_ENUM:
979 // Must be an enum. Need to construct the prefixed name.
980 obj := g.ObjectNamed(proto.GetString(field.TypeName))
981 enum, ok := obj.(*EnumDescriptor)
982 if !ok {
983 log.Stderr("don't know how to generate constant for", fieldname)
984 continue
985 }
986 def = enum.prefix() + def
987 }
988 g.P(kind, fieldname, " ", typename, " = ", def)
989 }
990 g.P()
991
992 for _, ext := range message.ext {
993 g.generateExtension(ext)
994 }
995}
996
997func (g *Generator) generateExtension(ext *ExtensionDescriptor) {
998 // The full type name
999 typeName := ext.TypeName()
1000 // Each scope of the extension is individually CamelCased, and all are joined with "_" with an "E_" prefix.
1001 for i, s := range typeName {
1002 typeName[i] = CamelCase(s)
1003 }
1004 ccTypeName := "E_" + strings.Join(typeName, "_")
1005
1006 extendedType := "*" + g.TypeName(g.ObjectNamed(*ext.Extendee))
1007 field := ext.FieldDescriptorProto
1008 fieldType, wireType := g.GoType(ext.parent, field)
1009 tag := g.goTag(field, wireType)
David Symondsf90e3382010-05-05 10:53:44 +10001010 g.RecordTypeUse(*ext.Extendee)
Rob Pikeaf82b4e2010-04-30 15:19:25 -07001011
Rob Pikec9e7d972010-06-10 10:30:22 -07001012 g.P("var ", ccTypeName, " = &", g.ProtoPkg, ".ExtensionDesc{")
Rob Pikeaf82b4e2010-04-30 15:19:25 -07001013 g.In()
1014 g.P("ExtendedType: (", extendedType, ")(nil),")
1015 g.P("ExtensionType: (", fieldType, ")(nil),")
1016 g.P("Field: ", field.Number, ",")
1017 g.P("Tag: ", tag, ",")
1018
1019 g.Out()
1020 g.P("}")
1021 g.P()
1022}
1023
1024func (g *Generator) generateInitFunction() {
1025 g.P("func init() {")
1026 g.In()
1027 for _, enum := range g.file.enum {
1028 g.generateEnumRegistration(enum)
1029 }
1030 g.Out()
1031 g.P("}")
1032}
1033
1034func (g *Generator) generateEnumRegistration(enum *EnumDescriptor) {
1035 pkg := g.packageName + "." // We always print the full package name here.
1036 // The full type name
1037 typeName := enum.TypeName()
1038 // The full type name, CamelCased.
1039 ccTypeName := CamelCaseSlice(typeName)
Rob Pikec9e7d972010-06-10 10:30:22 -07001040 g.P(g.ProtoPkg+".RegisterEnum(", Quote(pkg+ccTypeName), ", ", ccTypeName+"_name, ", ccTypeName+"_value)")
Rob Pikeaf82b4e2010-04-30 15:19:25 -07001041}
1042
1043// And now lots of helper functions.
1044
1045// CamelCase returns the CamelCased name. Given foo_bar_Baz, the result is FooBar_Baz.
1046func CamelCase(name string) string {
1047 elems := strings.Split(name, "_", 0)
1048 for i, e := range elems {
1049 if e == "" {
1050 elems[i] = "_"
1051 continue
1052 }
1053 runes := []int(e)
1054 if unicode.IsLower(runes[0]) {
1055 runes[0] = unicode.ToUpper(runes[0])
1056 elems[i] = string(runes)
1057 } else {
1058 if i > 0 {
1059 elems[i] = "_" + e
1060 }
1061 }
1062 }
1063 s := strings.Join(elems, "")
1064 // Name must not begin with an underscore.
1065 if len(s) > 0 && s[0] == '_' {
1066 s = "X" + s[1:]
1067 }
1068 return s
1069}
1070
1071// CamelCaseSlice is like CamelCase, but the argument is a slice of strings to
1072// be joined with "_".
1073func CamelCaseSlice(elem []string) string { return CamelCase(strings.Join(elem, "_")) }
1074
1075// dottedSlice turns a sliced name into a dotted name.
1076func dottedSlice(elem []string) string { return strings.Join(elem, ".") }
1077
1078// Quote returns a Go-source quoted string representation of s.
1079func Quote(s string) string { return fmt.Sprintf("%q", s) }
1080
1081// Given a .proto file name, return the output name for the generated Go program.
1082func goFileName(name string) string {
1083 if strings.HasSuffix(name, ".proto") {
1084 name = name[0 : len(name)-6]
1085 }
1086 return name + ".pb.go"
1087}
1088
1089// Is this field optional?
1090func isOptional(field *descriptor.FieldDescriptorProto) bool {
1091 return field.Label != nil && *field.Label == descriptor.FieldDescriptorProto_LABEL_OPTIONAL
1092}
1093
1094// Is this field required?
1095func isRequired(field *descriptor.FieldDescriptorProto) bool {
1096 return field.Label != nil && *field.Label == descriptor.FieldDescriptorProto_LABEL_REQUIRED
1097}
1098
1099// Is this field repeated?
1100func isRepeated(field *descriptor.FieldDescriptorProto) bool {
1101 return field.Label != nil && *field.Label == descriptor.FieldDescriptorProto_LABEL_REPEATED
1102}
1103
1104// DotToUnderscore is the mapping function used to generate Go names from package names,
Rob Pikec9e7d972010-06-10 10:30:22 -07001105// which can be dotted in the input .proto file. It maps dots to underscores.
1106// Because we also get here from package names generated from file names, it also maps
1107// minus signs to underscores.
Rob Pikeaf82b4e2010-04-30 15:19:25 -07001108func DotToUnderscore(rune int) int {
Rob Pikec9e7d972010-06-10 10:30:22 -07001109 switch rune {
1110 case '.', '-':
Rob Pikeaf82b4e2010-04-30 15:19:25 -07001111 return '_'
1112 }
1113 return rune
1114}
Rob Pikec9e7d972010-06-10 10:30:22 -07001115
1116// BaseName returns the last path element of the name, with the last dotted suffix removed.
1117func BaseName(name string) string {
1118 // First, find the last element
1119 if i := strings.LastIndex(name, "/"); i >= 0 {
1120 name = name[i+1:]
1121 }
1122 // Now drop the suffix
1123 if i := strings.LastIndex(name, "."); i >= 0 {
1124 name = name[0:i]
1125 }
1126 return name
1127}