generator.go 90 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806
  1. // Go support for Protocol Buffers - Google's data interchange format
  2. //
  3. // Copyright 2010 The Go Authors. All rights reserved.
  4. // https://github.com/golang/protobuf
  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. The code generator for the plugin for the Google protocol buffer compiler.
  33. It generates Go code from the protocol buffer description files read by the
  34. main routine.
  35. */
  36. package generator
  37. import (
  38. "bufio"
  39. "bytes"
  40. "compress/gzip"
  41. "crypto/sha256"
  42. "encoding/hex"
  43. "fmt"
  44. "go/ast"
  45. "go/build"
  46. "go/parser"
  47. "go/printer"
  48. "go/token"
  49. "log"
  50. "os"
  51. "path"
  52. "sort"
  53. "strconv"
  54. "strings"
  55. "unicode"
  56. "unicode/utf8"
  57. "github.com/golang/protobuf/proto"
  58. "github.com/golang/protobuf/protoc-gen-go/generator/internal/remap"
  59. "github.com/golang/protobuf/protoc-gen-go/descriptor"
  60. plugin "github.com/golang/protobuf/protoc-gen-go/plugin"
  61. )
  62. // generatedCodeVersion indicates a version of the generated code.
  63. // It is incremented whenever an incompatibility between the generated code and
  64. // proto package is introduced; the generated code references
  65. // a constant, proto.ProtoPackageIsVersionN (where N is generatedCodeVersion).
  66. const generatedCodeVersion = 3
  67. // A Plugin provides functionality to add to the output during Go code generation,
  68. // such as to produce RPC stubs.
  69. type Plugin interface {
  70. // Name identifies the plugin.
  71. Name() string
  72. // Init is called once after data structures are built but before
  73. // code generation begins.
  74. Init(g *Generator)
  75. // Generate produces the code generated by the plugin for this file,
  76. // except for the imports, by calling the generator's methods P, In, and Out.
  77. Generate(file *FileDescriptor)
  78. // GenerateImports produces the import declarations for this file.
  79. // It is called after Generate.
  80. GenerateImports(file *FileDescriptor)
  81. }
  82. var plugins []Plugin
  83. // RegisterPlugin installs a (second-order) plugin to be run when the Go output is generated.
  84. // It is typically called during initialization.
  85. func RegisterPlugin(p Plugin) {
  86. plugins = append(plugins, p)
  87. }
  88. // A GoImportPath is the import path of a Go package. e.g., "google.golang.org/genproto/protobuf".
  89. type GoImportPath string
  90. func (p GoImportPath) String() string { return strconv.Quote(string(p)) }
  91. // A GoPackageName is the name of a Go package. e.g., "protobuf".
  92. type GoPackageName string
  93. // Each type we import as a protocol buffer (other than FileDescriptorProto) needs
  94. // a pointer to the FileDescriptorProto that represents it. These types achieve that
  95. // wrapping by placing each Proto inside a struct with the pointer to its File. The
  96. // structs have the same names as their contents, with "Proto" removed.
  97. // FileDescriptor is used to store the things that it points to.
  98. // The file and package name method are common to messages and enums.
  99. type common struct {
  100. file *FileDescriptor // File this object comes from.
  101. }
  102. // GoImportPath is the import path of the Go package containing the type.
  103. func (c *common) GoImportPath() GoImportPath {
  104. return c.file.importPath
  105. }
  106. func (c *common) File() *FileDescriptor { return c.file }
  107. func fileIsProto3(file *descriptor.FileDescriptorProto) bool {
  108. return file.GetSyntax() == "proto3"
  109. }
  110. func (c *common) proto3() bool { return fileIsProto3(c.file.FileDescriptorProto) }
  111. // Descriptor represents a protocol buffer message.
  112. type Descriptor struct {
  113. common
  114. *descriptor.DescriptorProto
  115. parent *Descriptor // The containing message, if any.
  116. nested []*Descriptor // Inner messages, if any.
  117. enums []*EnumDescriptor // Inner enums, if any.
  118. ext []*ExtensionDescriptor // Extensions, if any.
  119. typename []string // Cached typename vector.
  120. index int // The index into the container, whether the file or another message.
  121. path string // The SourceCodeInfo path as comma-separated integers.
  122. group bool
  123. }
  124. // TypeName returns the elements of the dotted type name.
  125. // The package name is not part of this name.
  126. func (d *Descriptor) TypeName() []string {
  127. if d.typename != nil {
  128. return d.typename
  129. }
  130. n := 0
  131. for parent := d; parent != nil; parent = parent.parent {
  132. n++
  133. }
  134. s := make([]string, n)
  135. for parent := d; parent != nil; parent = parent.parent {
  136. n--
  137. s[n] = parent.GetName()
  138. }
  139. d.typename = s
  140. return s
  141. }
  142. // EnumDescriptor describes an enum. If it's at top level, its parent will be nil.
  143. // Otherwise it will be the descriptor of the message in which it is defined.
  144. type EnumDescriptor struct {
  145. common
  146. *descriptor.EnumDescriptorProto
  147. parent *Descriptor // The containing message, if any.
  148. typename []string // Cached typename vector.
  149. index int // The index into the container, whether the file or a message.
  150. path string // The SourceCodeInfo path as comma-separated integers.
  151. }
  152. // TypeName returns the elements of the dotted type name.
  153. // The package name is not part of this name.
  154. func (e *EnumDescriptor) TypeName() (s []string) {
  155. if e.typename != nil {
  156. return e.typename
  157. }
  158. name := e.GetName()
  159. if e.parent == nil {
  160. s = make([]string, 1)
  161. } else {
  162. pname := e.parent.TypeName()
  163. s = make([]string, len(pname)+1)
  164. copy(s, pname)
  165. }
  166. s[len(s)-1] = name
  167. e.typename = s
  168. return s
  169. }
  170. // Everything but the last element of the full type name, CamelCased.
  171. // The values of type Foo.Bar are call Foo_value1... not Foo_Bar_value1... .
  172. func (e *EnumDescriptor) prefix() string {
  173. if e.parent == nil {
  174. // If the enum is not part of a message, the prefix is just the type name.
  175. return CamelCase(*e.Name) + "_"
  176. }
  177. typeName := e.TypeName()
  178. return CamelCaseSlice(typeName[0:len(typeName)-1]) + "_"
  179. }
  180. // The integer value of the named constant in this enumerated type.
  181. func (e *EnumDescriptor) integerValueAsString(name string) string {
  182. for _, c := range e.Value {
  183. if c.GetName() == name {
  184. return fmt.Sprint(c.GetNumber())
  185. }
  186. }
  187. log.Fatal("cannot find value for enum constant")
  188. return ""
  189. }
  190. // ExtensionDescriptor describes an extension. If it's at top level, its parent will be nil.
  191. // Otherwise it will be the descriptor of the message in which it is defined.
  192. type ExtensionDescriptor struct {
  193. common
  194. *descriptor.FieldDescriptorProto
  195. parent *Descriptor // The containing message, if any.
  196. }
  197. // TypeName returns the elements of the dotted type name.
  198. // The package name is not part of this name.
  199. func (e *ExtensionDescriptor) TypeName() (s []string) {
  200. name := e.GetName()
  201. if e.parent == nil {
  202. // top-level extension
  203. s = make([]string, 1)
  204. } else {
  205. pname := e.parent.TypeName()
  206. s = make([]string, len(pname)+1)
  207. copy(s, pname)
  208. }
  209. s[len(s)-1] = name
  210. return s
  211. }
  212. // DescName returns the variable name used for the generated descriptor.
  213. func (e *ExtensionDescriptor) DescName() string {
  214. // The full type name.
  215. typeName := e.TypeName()
  216. // Each scope of the extension is individually CamelCased, and all are joined with "_" with an "E_" prefix.
  217. for i, s := range typeName {
  218. typeName[i] = CamelCase(s)
  219. }
  220. return "E_" + strings.Join(typeName, "_")
  221. }
  222. // ImportedDescriptor describes a type that has been publicly imported from another file.
  223. type ImportedDescriptor struct {
  224. common
  225. o Object
  226. }
  227. func (id *ImportedDescriptor) TypeName() []string { return id.o.TypeName() }
  228. // FileDescriptor describes an protocol buffer descriptor file (.proto).
  229. // It includes slices of all the messages and enums defined within it.
  230. // Those slices are constructed by WrapTypes.
  231. type FileDescriptor struct {
  232. *descriptor.FileDescriptorProto
  233. desc []*Descriptor // All the messages defined in this file.
  234. enum []*EnumDescriptor // All the enums defined in this file.
  235. ext []*ExtensionDescriptor // All the top-level extensions defined in this file.
  236. imp []*ImportedDescriptor // All types defined in files publicly imported by this file.
  237. // Comments, stored as a map of path (comma-separated integers) to the comment.
  238. comments map[string]*descriptor.SourceCodeInfo_Location
  239. // The full list of symbols that are exported,
  240. // as a map from the exported object to its symbols.
  241. // This is used for supporting public imports.
  242. exported map[Object][]symbol
  243. importPath GoImportPath // Import path of this file's package.
  244. packageName GoPackageName // Name of this file's Go package.
  245. proto3 bool // whether to generate proto3 code for this file
  246. }
  247. // VarName is the variable name we'll use in the generated code to refer
  248. // to the compressed bytes of this descriptor. It is not exported, so
  249. // it is only valid inside the generated package.
  250. func (d *FileDescriptor) VarName() string {
  251. h := sha256.Sum256([]byte(d.GetName()))
  252. return fmt.Sprintf("fileDescriptor_%s", hex.EncodeToString(h[:8]))
  253. }
  254. // goPackageOption interprets the file's go_package option.
  255. // If there is no go_package, it returns ("", "", false).
  256. // If there's a simple name, it returns ("", pkg, true).
  257. // If the option implies an import path, it returns (impPath, pkg, true).
  258. func (d *FileDescriptor) goPackageOption() (impPath GoImportPath, pkg GoPackageName, ok bool) {
  259. opt := d.GetOptions().GetGoPackage()
  260. if opt == "" {
  261. return "", "", false
  262. }
  263. // A semicolon-delimited suffix delimits the import path and package name.
  264. sc := strings.Index(opt, ";")
  265. if sc >= 0 {
  266. return GoImportPath(opt[:sc]), cleanPackageName(opt[sc+1:]), true
  267. }
  268. // The presence of a slash implies there's an import path.
  269. slash := strings.LastIndex(opt, "/")
  270. if slash >= 0 {
  271. return GoImportPath(opt), cleanPackageName(opt[slash+1:]), true
  272. }
  273. return "", cleanPackageName(opt), true
  274. }
  275. // goFileName returns the output name for the generated Go file.
  276. func (d *FileDescriptor) goFileName(pathType pathType) string {
  277. name := *d.Name
  278. if ext := path.Ext(name); ext == ".proto" || ext == ".protodevel" {
  279. name = name[:len(name)-len(ext)]
  280. }
  281. name += ".pb.go"
  282. if pathType == pathTypeSourceRelative {
  283. return name
  284. }
  285. // Does the file have a "go_package" option?
  286. // If it does, it may override the filename.
  287. if impPath, _, ok := d.goPackageOption(); ok && impPath != "" {
  288. // Replace the existing dirname with the declared import path.
  289. _, name = path.Split(name)
  290. name = path.Join(string(impPath), name)
  291. return name
  292. }
  293. return name
  294. }
  295. func (d *FileDescriptor) addExport(obj Object, sym symbol) {
  296. d.exported[obj] = append(d.exported[obj], sym)
  297. }
  298. // symbol is an interface representing an exported Go symbol.
  299. type symbol interface {
  300. // GenerateAlias should generate an appropriate alias
  301. // for the symbol from the named package.
  302. GenerateAlias(g *Generator, filename string, pkg GoPackageName)
  303. }
  304. type messageSymbol struct {
  305. sym string
  306. hasExtensions, isMessageSet bool
  307. oneofTypes []string
  308. }
  309. type getterSymbol struct {
  310. name string
  311. typ string
  312. typeName string // canonical name in proto world; empty for proto.Message and similar
  313. genType bool // whether typ contains a generated type (message/group/enum)
  314. }
  315. func (ms *messageSymbol) GenerateAlias(g *Generator, filename string, pkg GoPackageName) {
  316. g.P("// ", ms.sym, " from public import ", filename)
  317. g.P("type ", ms.sym, " = ", pkg, ".", ms.sym)
  318. for _, name := range ms.oneofTypes {
  319. g.P("type ", name, " = ", pkg, ".", name)
  320. }
  321. }
  322. type enumSymbol struct {
  323. name string
  324. proto3 bool // Whether this came from a proto3 file.
  325. }
  326. func (es enumSymbol) GenerateAlias(g *Generator, filename string, pkg GoPackageName) {
  327. s := es.name
  328. g.P("// ", s, " from public import ", filename)
  329. g.P("type ", s, " = ", pkg, ".", s)
  330. g.P("var ", s, "_name = ", pkg, ".", s, "_name")
  331. g.P("var ", s, "_value = ", pkg, ".", s, "_value")
  332. }
  333. type constOrVarSymbol struct {
  334. sym string
  335. typ string // either "const" or "var"
  336. cast string // if non-empty, a type cast is required (used for enums)
  337. }
  338. func (cs constOrVarSymbol) GenerateAlias(g *Generator, filename string, pkg GoPackageName) {
  339. v := string(pkg) + "." + cs.sym
  340. if cs.cast != "" {
  341. v = cs.cast + "(" + v + ")"
  342. }
  343. g.P(cs.typ, " ", cs.sym, " = ", v)
  344. }
  345. // Object is an interface abstracting the abilities shared by enums, messages, extensions and imported objects.
  346. type Object interface {
  347. GoImportPath() GoImportPath
  348. TypeName() []string
  349. File() *FileDescriptor
  350. }
  351. // Generator is the type whose methods generate the output, stored in the associated response structure.
  352. type Generator struct {
  353. *bytes.Buffer
  354. Request *plugin.CodeGeneratorRequest // The input.
  355. Response *plugin.CodeGeneratorResponse // The output.
  356. Param map[string]string // Command-line parameters.
  357. PackageImportPath string // Go import path of the package we're generating code for
  358. ImportPrefix string // String to prefix to imported package file names.
  359. ImportMap map[string]string // Mapping from .proto file name to import path
  360. Pkg map[string]string // The names under which we import support packages
  361. outputImportPath GoImportPath // Package we're generating code for.
  362. allFiles []*FileDescriptor // All files in the tree
  363. allFilesByName map[string]*FileDescriptor // All files by filename.
  364. genFiles []*FileDescriptor // Those files we will generate output for.
  365. file *FileDescriptor // The file we are compiling now.
  366. packageNames map[GoImportPath]GoPackageName // Imported package names in the current file.
  367. usedPackages map[GoImportPath]bool // Packages used in current file.
  368. usedPackageNames map[GoPackageName]bool // Package names used in the current file.
  369. addedImports map[GoImportPath]bool // Additional imports to emit.
  370. typeNameToObject map[string]Object // Key is a fully-qualified name in input syntax.
  371. init []string // Lines to emit in the init function.
  372. indent string
  373. pathType pathType // How to generate output filenames.
  374. writeOutput bool
  375. annotateCode bool // whether to store annotations
  376. annotations []*descriptor.GeneratedCodeInfo_Annotation // annotations to store
  377. }
  378. type pathType int
  379. const (
  380. pathTypeImport pathType = iota
  381. pathTypeSourceRelative
  382. )
  383. // New creates a new generator and allocates the request and response protobufs.
  384. func New() *Generator {
  385. g := new(Generator)
  386. g.Buffer = new(bytes.Buffer)
  387. g.Request = new(plugin.CodeGeneratorRequest)
  388. g.Response = new(plugin.CodeGeneratorResponse)
  389. return g
  390. }
  391. // Error reports a problem, including an error, and exits the program.
  392. func (g *Generator) Error(err error, msgs ...string) {
  393. s := strings.Join(msgs, " ") + ":" + err.Error()
  394. log.Print("protoc-gen-go: error:", s)
  395. os.Exit(1)
  396. }
  397. // Fail reports a problem and exits the program.
  398. func (g *Generator) Fail(msgs ...string) {
  399. s := strings.Join(msgs, " ")
  400. log.Print("protoc-gen-go: error:", s)
  401. os.Exit(1)
  402. }
  403. // CommandLineParameters breaks the comma-separated list of key=value pairs
  404. // in the parameter (a member of the request protobuf) into a key/value map.
  405. // It then sets file name mappings defined by those entries.
  406. func (g *Generator) CommandLineParameters(parameter string) {
  407. g.Param = make(map[string]string)
  408. for _, p := range strings.Split(parameter, ",") {
  409. if i := strings.Index(p, "="); i < 0 {
  410. g.Param[p] = ""
  411. } else {
  412. g.Param[p[0:i]] = p[i+1:]
  413. }
  414. }
  415. g.ImportMap = make(map[string]string)
  416. pluginList := "none" // Default list of plugin names to enable (empty means all).
  417. for k, v := range g.Param {
  418. switch k {
  419. case "import_prefix":
  420. g.ImportPrefix = v
  421. case "import_path":
  422. g.PackageImportPath = v
  423. case "paths":
  424. switch v {
  425. case "import":
  426. g.pathType = pathTypeImport
  427. case "source_relative":
  428. g.pathType = pathTypeSourceRelative
  429. default:
  430. g.Fail(fmt.Sprintf(`Unknown path type %q: want "import" or "source_relative".`, v))
  431. }
  432. case "plugins":
  433. pluginList = v
  434. case "annotate_code":
  435. if v == "true" {
  436. g.annotateCode = true
  437. }
  438. default:
  439. if len(k) > 0 && k[0] == 'M' {
  440. g.ImportMap[k[1:]] = v
  441. }
  442. }
  443. }
  444. if pluginList != "" {
  445. // Amend the set of plugins.
  446. enabled := make(map[string]bool)
  447. for _, name := range strings.Split(pluginList, "+") {
  448. enabled[name] = true
  449. }
  450. var nplugins []Plugin
  451. for _, p := range plugins {
  452. if enabled[p.Name()] {
  453. nplugins = append(nplugins, p)
  454. }
  455. }
  456. plugins = nplugins
  457. }
  458. }
  459. // DefaultPackageName returns the package name printed for the object.
  460. // If its file is in a different package, it returns the package name we're using for this file, plus ".".
  461. // Otherwise it returns the empty string.
  462. func (g *Generator) DefaultPackageName(obj Object) string {
  463. importPath := obj.GoImportPath()
  464. if importPath == g.outputImportPath {
  465. return ""
  466. }
  467. return string(g.GoPackageName(importPath)) + "."
  468. }
  469. // GoPackageName returns the name used for a package.
  470. func (g *Generator) GoPackageName(importPath GoImportPath) GoPackageName {
  471. if name, ok := g.packageNames[importPath]; ok {
  472. return name
  473. }
  474. name := cleanPackageName(baseName(string(importPath)))
  475. for i, orig := 1, name; g.usedPackageNames[name] || isGoPredeclaredIdentifier[string(name)]; i++ {
  476. name = orig + GoPackageName(strconv.Itoa(i))
  477. }
  478. g.packageNames[importPath] = name
  479. g.usedPackageNames[name] = true
  480. return name
  481. }
  482. // AddImport adds a package to the generated file's import section.
  483. // It returns the name used for the package.
  484. func (g *Generator) AddImport(importPath GoImportPath) GoPackageName {
  485. g.addedImports[importPath] = true
  486. return g.GoPackageName(importPath)
  487. }
  488. var globalPackageNames = map[GoPackageName]bool{
  489. "fmt": true,
  490. "math": true,
  491. "proto": true,
  492. }
  493. // Create and remember a guaranteed unique package name. Pkg is the candidate name.
  494. // The FileDescriptor parameter is unused.
  495. func RegisterUniquePackageName(pkg string, f *FileDescriptor) string {
  496. name := cleanPackageName(pkg)
  497. for i, orig := 1, name; globalPackageNames[name]; i++ {
  498. name = orig + GoPackageName(strconv.Itoa(i))
  499. }
  500. globalPackageNames[name] = true
  501. return string(name)
  502. }
  503. var isGoKeyword = map[string]bool{
  504. "break": true,
  505. "case": true,
  506. "chan": true,
  507. "const": true,
  508. "continue": true,
  509. "default": true,
  510. "else": true,
  511. "defer": true,
  512. "fallthrough": true,
  513. "for": true,
  514. "func": true,
  515. "go": true,
  516. "goto": true,
  517. "if": true,
  518. "import": true,
  519. "interface": true,
  520. "map": true,
  521. "package": true,
  522. "range": true,
  523. "return": true,
  524. "select": true,
  525. "struct": true,
  526. "switch": true,
  527. "type": true,
  528. "var": true,
  529. }
  530. var isGoPredeclaredIdentifier = map[string]bool{
  531. "append": true,
  532. "bool": true,
  533. "byte": true,
  534. "cap": true,
  535. "close": true,
  536. "complex": true,
  537. "complex128": true,
  538. "complex64": true,
  539. "copy": true,
  540. "delete": true,
  541. "error": true,
  542. "false": true,
  543. "float32": true,
  544. "float64": true,
  545. "imag": true,
  546. "int": true,
  547. "int16": true,
  548. "int32": true,
  549. "int64": true,
  550. "int8": true,
  551. "iota": true,
  552. "len": true,
  553. "make": true,
  554. "new": true,
  555. "nil": true,
  556. "panic": true,
  557. "print": true,
  558. "println": true,
  559. "real": true,
  560. "recover": true,
  561. "rune": true,
  562. "string": true,
  563. "true": true,
  564. "uint": true,
  565. "uint16": true,
  566. "uint32": true,
  567. "uint64": true,
  568. "uint8": true,
  569. "uintptr": true,
  570. }
  571. func cleanPackageName(name string) GoPackageName {
  572. name = strings.Map(badToUnderscore, name)
  573. // Identifier must not be keyword or predeclared identifier: insert _.
  574. if isGoKeyword[name] {
  575. name = "_" + name
  576. }
  577. // Identifier must not begin with digit: insert _.
  578. if r, _ := utf8.DecodeRuneInString(name); unicode.IsDigit(r) {
  579. name = "_" + name
  580. }
  581. return GoPackageName(name)
  582. }
  583. // defaultGoPackage returns the package name to use,
  584. // derived from the import path of the package we're building code for.
  585. func (g *Generator) defaultGoPackage() GoPackageName {
  586. p := g.PackageImportPath
  587. if i := strings.LastIndex(p, "/"); i >= 0 {
  588. p = p[i+1:]
  589. }
  590. return cleanPackageName(p)
  591. }
  592. // SetPackageNames sets the package name for this run.
  593. // The package name must agree across all files being generated.
  594. // It also defines unique package names for all imported files.
  595. func (g *Generator) SetPackageNames() {
  596. g.outputImportPath = g.genFiles[0].importPath
  597. defaultPackageNames := make(map[GoImportPath]GoPackageName)
  598. for _, f := range g.genFiles {
  599. if _, p, ok := f.goPackageOption(); ok {
  600. defaultPackageNames[f.importPath] = p
  601. }
  602. }
  603. for _, f := range g.genFiles {
  604. if _, p, ok := f.goPackageOption(); ok {
  605. // Source file: option go_package = "quux/bar";
  606. f.packageName = p
  607. } else if p, ok := defaultPackageNames[f.importPath]; ok {
  608. // A go_package option in another file in the same package.
  609. //
  610. // This is a poor choice in general, since every source file should
  611. // contain a go_package option. Supported mainly for historical
  612. // compatibility.
  613. f.packageName = p
  614. } else if p := g.defaultGoPackage(); p != "" {
  615. // Command-line: import_path=quux/bar.
  616. //
  617. // The import_path flag sets a package name for files which don't
  618. // contain a go_package option.
  619. f.packageName = p
  620. } else if p := f.GetPackage(); p != "" {
  621. // Source file: package quux.bar;
  622. f.packageName = cleanPackageName(p)
  623. } else {
  624. // Source filename.
  625. f.packageName = cleanPackageName(baseName(f.GetName()))
  626. }
  627. }
  628. // Check that all files have a consistent package name and import path.
  629. for _, f := range g.genFiles[1:] {
  630. if a, b := g.genFiles[0].importPath, f.importPath; a != b {
  631. g.Fail(fmt.Sprintf("inconsistent package import paths: %v, %v", a, b))
  632. }
  633. if a, b := g.genFiles[0].packageName, f.packageName; a != b {
  634. g.Fail(fmt.Sprintf("inconsistent package names: %v, %v", a, b))
  635. }
  636. }
  637. // Names of support packages. These never vary (if there are conflicts,
  638. // we rename the conflicting package), so this could be removed someday.
  639. g.Pkg = map[string]string{
  640. "fmt": "fmt",
  641. "math": "math",
  642. "proto": "proto",
  643. }
  644. }
  645. // WrapTypes walks the incoming data, wrapping DescriptorProtos, EnumDescriptorProtos
  646. // and FileDescriptorProtos into file-referenced objects within the Generator.
  647. // It also creates the list of files to generate and so should be called before GenerateAllFiles.
  648. func (g *Generator) WrapTypes() {
  649. g.allFiles = make([]*FileDescriptor, 0, len(g.Request.ProtoFile))
  650. g.allFilesByName = make(map[string]*FileDescriptor, len(g.allFiles))
  651. genFileNames := make(map[string]bool)
  652. for _, n := range g.Request.FileToGenerate {
  653. genFileNames[n] = true
  654. }
  655. for _, f := range g.Request.ProtoFile {
  656. fd := &FileDescriptor{
  657. FileDescriptorProto: f,
  658. exported: make(map[Object][]symbol),
  659. proto3: fileIsProto3(f),
  660. }
  661. // The import path may be set in a number of ways.
  662. if substitution, ok := g.ImportMap[f.GetName()]; ok {
  663. // Command-line: M=foo.proto=quux/bar.
  664. //
  665. // Explicit mapping of source file to import path.
  666. fd.importPath = GoImportPath(substitution)
  667. } else if genFileNames[f.GetName()] && g.PackageImportPath != "" {
  668. // Command-line: import_path=quux/bar.
  669. //
  670. // The import_path flag sets the import path for every file that
  671. // we generate code for.
  672. fd.importPath = GoImportPath(g.PackageImportPath)
  673. } else if p, _, _ := fd.goPackageOption(); p != "" {
  674. // Source file: option go_package = "quux/bar";
  675. //
  676. // The go_package option sets the import path. Most users should use this.
  677. fd.importPath = p
  678. } else {
  679. // Source filename.
  680. //
  681. // Last resort when nothing else is available.
  682. fd.importPath = GoImportPath(path.Dir(f.GetName()))
  683. }
  684. // We must wrap the descriptors before we wrap the enums
  685. fd.desc = wrapDescriptors(fd)
  686. g.buildNestedDescriptors(fd.desc)
  687. fd.enum = wrapEnumDescriptors(fd, fd.desc)
  688. g.buildNestedEnums(fd.desc, fd.enum)
  689. fd.ext = wrapExtensions(fd)
  690. extractComments(fd)
  691. g.allFiles = append(g.allFiles, fd)
  692. g.allFilesByName[f.GetName()] = fd
  693. }
  694. for _, fd := range g.allFiles {
  695. fd.imp = wrapImported(fd, g)
  696. }
  697. g.genFiles = make([]*FileDescriptor, 0, len(g.Request.FileToGenerate))
  698. for _, fileName := range g.Request.FileToGenerate {
  699. fd := g.allFilesByName[fileName]
  700. if fd == nil {
  701. g.Fail("could not find file named", fileName)
  702. }
  703. g.genFiles = append(g.genFiles, fd)
  704. }
  705. }
  706. // Scan the descriptors in this file. For each one, build the slice of nested descriptors
  707. func (g *Generator) buildNestedDescriptors(descs []*Descriptor) {
  708. for _, desc := range descs {
  709. if len(desc.NestedType) != 0 {
  710. for _, nest := range descs {
  711. if nest.parent == desc {
  712. desc.nested = append(desc.nested, nest)
  713. }
  714. }
  715. if len(desc.nested) != len(desc.NestedType) {
  716. g.Fail("internal error: nesting failure for", desc.GetName())
  717. }
  718. }
  719. }
  720. }
  721. func (g *Generator) buildNestedEnums(descs []*Descriptor, enums []*EnumDescriptor) {
  722. for _, desc := range descs {
  723. if len(desc.EnumType) != 0 {
  724. for _, enum := range enums {
  725. if enum.parent == desc {
  726. desc.enums = append(desc.enums, enum)
  727. }
  728. }
  729. if len(desc.enums) != len(desc.EnumType) {
  730. g.Fail("internal error: enum nesting failure for", desc.GetName())
  731. }
  732. }
  733. }
  734. }
  735. // Construct the Descriptor
  736. func newDescriptor(desc *descriptor.DescriptorProto, parent *Descriptor, file *FileDescriptor, index int) *Descriptor {
  737. d := &Descriptor{
  738. common: common{file},
  739. DescriptorProto: desc,
  740. parent: parent,
  741. index: index,
  742. }
  743. if parent == nil {
  744. d.path = fmt.Sprintf("%d,%d", messagePath, index)
  745. } else {
  746. d.path = fmt.Sprintf("%s,%d,%d", parent.path, messageMessagePath, index)
  747. }
  748. // The only way to distinguish a group from a message is whether
  749. // the containing message has a TYPE_GROUP field that matches.
  750. if parent != nil {
  751. parts := d.TypeName()
  752. if file.Package != nil {
  753. parts = append([]string{*file.Package}, parts...)
  754. }
  755. exp := "." + strings.Join(parts, ".")
  756. for _, field := range parent.Field {
  757. if field.GetType() == descriptor.FieldDescriptorProto_TYPE_GROUP && field.GetTypeName() == exp {
  758. d.group = true
  759. break
  760. }
  761. }
  762. }
  763. for _, field := range desc.Extension {
  764. d.ext = append(d.ext, &ExtensionDescriptor{common{file}, field, d})
  765. }
  766. return d
  767. }
  768. // Return a slice of all the Descriptors defined within this file
  769. func wrapDescriptors(file *FileDescriptor) []*Descriptor {
  770. sl := make([]*Descriptor, 0, len(file.MessageType)+10)
  771. for i, desc := range file.MessageType {
  772. sl = wrapThisDescriptor(sl, desc, nil, file, i)
  773. }
  774. return sl
  775. }
  776. // Wrap this Descriptor, recursively
  777. func wrapThisDescriptor(sl []*Descriptor, desc *descriptor.DescriptorProto, parent *Descriptor, file *FileDescriptor, index int) []*Descriptor {
  778. sl = append(sl, newDescriptor(desc, parent, file, index))
  779. me := sl[len(sl)-1]
  780. for i, nested := range desc.NestedType {
  781. sl = wrapThisDescriptor(sl, nested, me, file, i)
  782. }
  783. return sl
  784. }
  785. // Construct the EnumDescriptor
  786. func newEnumDescriptor(desc *descriptor.EnumDescriptorProto, parent *Descriptor, file *FileDescriptor, index int) *EnumDescriptor {
  787. ed := &EnumDescriptor{
  788. common: common{file},
  789. EnumDescriptorProto: desc,
  790. parent: parent,
  791. index: index,
  792. }
  793. if parent == nil {
  794. ed.path = fmt.Sprintf("%d,%d", enumPath, index)
  795. } else {
  796. ed.path = fmt.Sprintf("%s,%d,%d", parent.path, messageEnumPath, index)
  797. }
  798. return ed
  799. }
  800. // Return a slice of all the EnumDescriptors defined within this file
  801. func wrapEnumDescriptors(file *FileDescriptor, descs []*Descriptor) []*EnumDescriptor {
  802. sl := make([]*EnumDescriptor, 0, len(file.EnumType)+10)
  803. // Top-level enums.
  804. for i, enum := range file.EnumType {
  805. sl = append(sl, newEnumDescriptor(enum, nil, file, i))
  806. }
  807. // Enums within messages. Enums within embedded messages appear in the outer-most message.
  808. for _, nested := range descs {
  809. for i, enum := range nested.EnumType {
  810. sl = append(sl, newEnumDescriptor(enum, nested, file, i))
  811. }
  812. }
  813. return sl
  814. }
  815. // Return a slice of all the top-level ExtensionDescriptors defined within this file.
  816. func wrapExtensions(file *FileDescriptor) []*ExtensionDescriptor {
  817. var sl []*ExtensionDescriptor
  818. for _, field := range file.Extension {
  819. sl = append(sl, &ExtensionDescriptor{common{file}, field, nil})
  820. }
  821. return sl
  822. }
  823. // Return a slice of all the types that are publicly imported into this file.
  824. func wrapImported(file *FileDescriptor, g *Generator) (sl []*ImportedDescriptor) {
  825. for _, index := range file.PublicDependency {
  826. df := g.fileByName(file.Dependency[index])
  827. for _, d := range df.desc {
  828. if d.GetOptions().GetMapEntry() {
  829. continue
  830. }
  831. sl = append(sl, &ImportedDescriptor{common{file}, d})
  832. }
  833. for _, e := range df.enum {
  834. sl = append(sl, &ImportedDescriptor{common{file}, e})
  835. }
  836. for _, ext := range df.ext {
  837. sl = append(sl, &ImportedDescriptor{common{file}, ext})
  838. }
  839. }
  840. return
  841. }
  842. func extractComments(file *FileDescriptor) {
  843. file.comments = make(map[string]*descriptor.SourceCodeInfo_Location)
  844. for _, loc := range file.GetSourceCodeInfo().GetLocation() {
  845. if loc.LeadingComments == nil {
  846. continue
  847. }
  848. var p []string
  849. for _, n := range loc.Path {
  850. p = append(p, strconv.Itoa(int(n)))
  851. }
  852. file.comments[strings.Join(p, ",")] = loc
  853. }
  854. }
  855. // BuildTypeNameMap builds the map from fully qualified type names to objects.
  856. // The key names for the map come from the input data, which puts a period at the beginning.
  857. // It should be called after SetPackageNames and before GenerateAllFiles.
  858. func (g *Generator) BuildTypeNameMap() {
  859. g.typeNameToObject = make(map[string]Object)
  860. for _, f := range g.allFiles {
  861. // The names in this loop are defined by the proto world, not us, so the
  862. // package name may be empty. If so, the dotted package name of X will
  863. // be ".X"; otherwise it will be ".pkg.X".
  864. dottedPkg := "." + f.GetPackage()
  865. if dottedPkg != "." {
  866. dottedPkg += "."
  867. }
  868. for _, enum := range f.enum {
  869. name := dottedPkg + dottedSlice(enum.TypeName())
  870. g.typeNameToObject[name] = enum
  871. }
  872. for _, desc := range f.desc {
  873. name := dottedPkg + dottedSlice(desc.TypeName())
  874. g.typeNameToObject[name] = desc
  875. }
  876. }
  877. }
  878. // ObjectNamed, given a fully-qualified input type name as it appears in the input data,
  879. // returns the descriptor for the message or enum with that name.
  880. func (g *Generator) ObjectNamed(typeName string) Object {
  881. o, ok := g.typeNameToObject[typeName]
  882. if !ok {
  883. g.Fail("can't find object with type", typeName)
  884. }
  885. return o
  886. }
  887. // AnnotatedAtoms is a list of atoms (as consumed by P) that records the file name and proto AST path from which they originated.
  888. type AnnotatedAtoms struct {
  889. source string
  890. path string
  891. atoms []interface{}
  892. }
  893. // Annotate records the file name and proto AST path of a list of atoms
  894. // so that a later call to P can emit a link from each atom to its origin.
  895. func Annotate(file *FileDescriptor, path string, atoms ...interface{}) *AnnotatedAtoms {
  896. return &AnnotatedAtoms{source: *file.Name, path: path, atoms: atoms}
  897. }
  898. // printAtom prints the (atomic, non-annotation) argument to the generated output.
  899. func (g *Generator) printAtom(v interface{}) {
  900. switch v := v.(type) {
  901. case string:
  902. g.WriteString(v)
  903. case *string:
  904. g.WriteString(*v)
  905. case bool:
  906. fmt.Fprint(g, v)
  907. case *bool:
  908. fmt.Fprint(g, *v)
  909. case int:
  910. fmt.Fprint(g, v)
  911. case *int32:
  912. fmt.Fprint(g, *v)
  913. case *int64:
  914. fmt.Fprint(g, *v)
  915. case float64:
  916. fmt.Fprint(g, v)
  917. case *float64:
  918. fmt.Fprint(g, *v)
  919. case GoPackageName:
  920. g.WriteString(string(v))
  921. case GoImportPath:
  922. g.WriteString(strconv.Quote(string(v)))
  923. default:
  924. g.Fail(fmt.Sprintf("unknown type in printer: %T", v))
  925. }
  926. }
  927. // P prints the arguments to the generated output. It handles strings and int32s, plus
  928. // handling indirections because they may be *string, etc. Any inputs of type AnnotatedAtoms may emit
  929. // annotations in a .meta file in addition to outputting the atoms themselves (if g.annotateCode
  930. // is true).
  931. func (g *Generator) P(str ...interface{}) {
  932. if !g.writeOutput {
  933. return
  934. }
  935. g.WriteString(g.indent)
  936. for _, v := range str {
  937. switch v := v.(type) {
  938. case *AnnotatedAtoms:
  939. begin := int32(g.Len())
  940. for _, v := range v.atoms {
  941. g.printAtom(v)
  942. }
  943. if g.annotateCode {
  944. end := int32(g.Len())
  945. var path []int32
  946. for _, token := range strings.Split(v.path, ",") {
  947. val, err := strconv.ParseInt(token, 10, 32)
  948. if err != nil {
  949. g.Fail("could not parse proto AST path: ", err.Error())
  950. }
  951. path = append(path, int32(val))
  952. }
  953. g.annotations = append(g.annotations, &descriptor.GeneratedCodeInfo_Annotation{
  954. Path: path,
  955. SourceFile: &v.source,
  956. Begin: &begin,
  957. End: &end,
  958. })
  959. }
  960. default:
  961. g.printAtom(v)
  962. }
  963. }
  964. g.WriteByte('\n')
  965. }
  966. // addInitf stores the given statement to be printed inside the file's init function.
  967. // The statement is given as a format specifier and arguments.
  968. func (g *Generator) addInitf(stmt string, a ...interface{}) {
  969. g.init = append(g.init, fmt.Sprintf(stmt, a...))
  970. }
  971. // In Indents the output one tab stop.
  972. func (g *Generator) In() { g.indent += "\t" }
  973. // Out unindents the output one tab stop.
  974. func (g *Generator) Out() {
  975. if len(g.indent) > 0 {
  976. g.indent = g.indent[1:]
  977. }
  978. }
  979. // GenerateAllFiles generates the output for all the files we're outputting.
  980. func (g *Generator) GenerateAllFiles() {
  981. // Initialize the plugins
  982. for _, p := range plugins {
  983. p.Init(g)
  984. }
  985. // Generate the output. The generator runs for every file, even the files
  986. // that we don't generate output for, so that we can collate the full list
  987. // of exported symbols to support public imports.
  988. genFileMap := make(map[*FileDescriptor]bool, len(g.genFiles))
  989. for _, file := range g.genFiles {
  990. genFileMap[file] = true
  991. }
  992. for _, file := range g.allFiles {
  993. g.Reset()
  994. g.annotations = nil
  995. g.writeOutput = genFileMap[file]
  996. g.generate(file)
  997. if !g.writeOutput {
  998. continue
  999. }
  1000. fname := file.goFileName(g.pathType)
  1001. g.Response.File = append(g.Response.File, &plugin.CodeGeneratorResponse_File{
  1002. Name: proto.String(fname),
  1003. Content: proto.String(g.String()),
  1004. })
  1005. if g.annotateCode {
  1006. // Store the generated code annotations in text, as the protoc plugin protocol requires that
  1007. // strings contain valid UTF-8.
  1008. g.Response.File = append(g.Response.File, &plugin.CodeGeneratorResponse_File{
  1009. Name: proto.String(file.goFileName(g.pathType) + ".meta"),
  1010. Content: proto.String(proto.CompactTextString(&descriptor.GeneratedCodeInfo{Annotation: g.annotations})),
  1011. })
  1012. }
  1013. }
  1014. }
  1015. // Run all the plugins associated with the file.
  1016. func (g *Generator) runPlugins(file *FileDescriptor) {
  1017. for _, p := range plugins {
  1018. p.Generate(file)
  1019. }
  1020. }
  1021. // Fill the response protocol buffer with the generated output for all the files we're
  1022. // supposed to generate.
  1023. func (g *Generator) generate(file *FileDescriptor) {
  1024. g.file = file
  1025. g.usedPackages = make(map[GoImportPath]bool)
  1026. g.packageNames = make(map[GoImportPath]GoPackageName)
  1027. g.usedPackageNames = make(map[GoPackageName]bool)
  1028. g.addedImports = make(map[GoImportPath]bool)
  1029. for name := range globalPackageNames {
  1030. g.usedPackageNames[name] = true
  1031. }
  1032. g.P("// This is a compile-time assertion to ensure that this generated file")
  1033. g.P("// is compatible with the proto package it is being compiled against.")
  1034. g.P("// A compilation error at this line likely means your copy of the")
  1035. g.P("// proto package needs to be updated.")
  1036. g.P("const _ = ", g.Pkg["proto"], ".ProtoPackageIsVersion", generatedCodeVersion, " // please upgrade the proto package")
  1037. g.P()
  1038. for _, td := range g.file.imp {
  1039. g.generateImported(td)
  1040. }
  1041. for _, enum := range g.file.enum {
  1042. g.generateEnum(enum)
  1043. }
  1044. for _, desc := range g.file.desc {
  1045. // Don't generate virtual messages for maps.
  1046. if desc.GetOptions().GetMapEntry() {
  1047. continue
  1048. }
  1049. g.generateMessage(desc)
  1050. }
  1051. for _, ext := range g.file.ext {
  1052. g.generateExtension(ext)
  1053. }
  1054. g.generateInitFunction()
  1055. g.generateFileDescriptor(file)
  1056. // Run the plugins before the imports so we know which imports are necessary.
  1057. g.runPlugins(file)
  1058. // Generate header and imports last, though they appear first in the output.
  1059. rem := g.Buffer
  1060. remAnno := g.annotations
  1061. g.Buffer = new(bytes.Buffer)
  1062. g.annotations = nil
  1063. g.generateHeader()
  1064. g.generateImports()
  1065. if !g.writeOutput {
  1066. return
  1067. }
  1068. // Adjust the offsets for annotations displaced by the header and imports.
  1069. for _, anno := range remAnno {
  1070. *anno.Begin += int32(g.Len())
  1071. *anno.End += int32(g.Len())
  1072. g.annotations = append(g.annotations, anno)
  1073. }
  1074. g.Write(rem.Bytes())
  1075. // Reformat generated code and patch annotation locations.
  1076. fset := token.NewFileSet()
  1077. original := g.Bytes()
  1078. if g.annotateCode {
  1079. // make a copy independent of g; we'll need it after Reset.
  1080. original = append([]byte(nil), original...)
  1081. }
  1082. fileAST, err := parser.ParseFile(fset, "", original, parser.ParseComments)
  1083. if err != nil {
  1084. // Print out the bad code with line numbers.
  1085. // This should never happen in practice, but it can while changing generated code,
  1086. // so consider this a debugging aid.
  1087. var src bytes.Buffer
  1088. s := bufio.NewScanner(bytes.NewReader(original))
  1089. for line := 1; s.Scan(); line++ {
  1090. fmt.Fprintf(&src, "%5d\t%s\n", line, s.Bytes())
  1091. }
  1092. g.Fail("bad Go source code was generated:", err.Error(), "\n"+src.String())
  1093. }
  1094. ast.SortImports(fset, fileAST)
  1095. g.Reset()
  1096. err = (&printer.Config{Mode: printer.TabIndent | printer.UseSpaces, Tabwidth: 8}).Fprint(g, fset, fileAST)
  1097. if err != nil {
  1098. g.Fail("generated Go source code could not be reformatted:", err.Error())
  1099. }
  1100. if g.annotateCode {
  1101. m, err := remap.Compute(original, g.Bytes())
  1102. if err != nil {
  1103. g.Fail("formatted generated Go source code could not be mapped back to the original code:", err.Error())
  1104. }
  1105. for _, anno := range g.annotations {
  1106. new, ok := m.Find(int(*anno.Begin), int(*anno.End))
  1107. if !ok {
  1108. g.Fail("span in formatted generated Go source code could not be mapped back to the original code")
  1109. }
  1110. *anno.Begin = int32(new.Pos)
  1111. *anno.End = int32(new.End)
  1112. }
  1113. }
  1114. }
  1115. // Generate the header, including package definition
  1116. func (g *Generator) generateHeader() {
  1117. g.P("// Code generated by protoc-gen-go. DO NOT EDIT.")
  1118. if g.file.GetOptions().GetDeprecated() {
  1119. g.P("// ", g.file.Name, " is a deprecated file.")
  1120. } else {
  1121. g.P("// source: ", g.file.Name)
  1122. }
  1123. g.P()
  1124. g.PrintComments(strconv.Itoa(packagePath))
  1125. g.P()
  1126. g.P("package ", g.file.packageName)
  1127. g.P()
  1128. }
  1129. // deprecationComment is the standard comment added to deprecated
  1130. // messages, fields, enums, and enum values.
  1131. var deprecationComment = "// Deprecated: Do not use."
  1132. // PrintComments prints any comments from the source .proto file.
  1133. // The path is a comma-separated list of integers.
  1134. // It returns an indication of whether any comments were printed.
  1135. // See descriptor.proto for its format.
  1136. func (g *Generator) PrintComments(path string) bool {
  1137. if !g.writeOutput {
  1138. return false
  1139. }
  1140. if c, ok := g.makeComments(path); ok {
  1141. g.P(c)
  1142. return true
  1143. }
  1144. return false
  1145. }
  1146. // makeComments generates the comment string for the field, no "\n" at the end
  1147. func (g *Generator) makeComments(path string) (string, bool) {
  1148. loc, ok := g.file.comments[path]
  1149. if !ok {
  1150. return "", false
  1151. }
  1152. w := new(bytes.Buffer)
  1153. nl := ""
  1154. for _, line := range strings.Split(strings.TrimSuffix(loc.GetLeadingComments(), "\n"), "\n") {
  1155. fmt.Fprintf(w, "%s//%s", nl, line)
  1156. nl = "\n"
  1157. }
  1158. return w.String(), true
  1159. }
  1160. func (g *Generator) fileByName(filename string) *FileDescriptor {
  1161. return g.allFilesByName[filename]
  1162. }
  1163. // weak returns whether the ith import of the current file is a weak import.
  1164. func (g *Generator) weak(i int32) bool {
  1165. for _, j := range g.file.WeakDependency {
  1166. if j == i {
  1167. return true
  1168. }
  1169. }
  1170. return false
  1171. }
  1172. // Generate the imports
  1173. func (g *Generator) generateImports() {
  1174. imports := make(map[GoImportPath]GoPackageName)
  1175. for i, s := range g.file.Dependency {
  1176. fd := g.fileByName(s)
  1177. importPath := fd.importPath
  1178. // Do not import our own package.
  1179. if importPath == g.file.importPath {
  1180. continue
  1181. }
  1182. // Do not import weak imports.
  1183. if g.weak(int32(i)) {
  1184. continue
  1185. }
  1186. // Do not import a package twice.
  1187. if _, ok := imports[importPath]; ok {
  1188. continue
  1189. }
  1190. // We need to import all the dependencies, even if we don't reference them,
  1191. // because other code and tools depend on having the full transitive closure
  1192. // of protocol buffer types in the binary.
  1193. packageName := g.GoPackageName(importPath)
  1194. if _, ok := g.usedPackages[importPath]; !ok {
  1195. packageName = "_"
  1196. }
  1197. imports[importPath] = packageName
  1198. }
  1199. for importPath := range g.addedImports {
  1200. imports[importPath] = g.GoPackageName(importPath)
  1201. }
  1202. // We almost always need a proto import. Rather than computing when we
  1203. // do, which is tricky when there's a plugin, just import it and
  1204. // reference it later. The same argument applies to the fmt and math packages.
  1205. g.P("import (")
  1206. g.P(g.Pkg["fmt"] + ` "fmt"`)
  1207. g.P(g.Pkg["math"] + ` "math"`)
  1208. g.P(g.Pkg["proto"]+" ", GoImportPath(g.ImportPrefix)+"github.com/golang/protobuf/proto")
  1209. for importPath, packageName := range imports {
  1210. g.P(packageName, " ", GoImportPath(g.ImportPrefix)+importPath)
  1211. }
  1212. g.P(")")
  1213. g.P()
  1214. // TODO: may need to worry about uniqueness across plugins
  1215. for _, p := range plugins {
  1216. p.GenerateImports(g.file)
  1217. g.P()
  1218. }
  1219. g.P("// Reference imports to suppress errors if they are not otherwise used.")
  1220. g.P("var _ = ", g.Pkg["proto"], ".Marshal")
  1221. g.P("var _ = ", g.Pkg["fmt"], ".Errorf")
  1222. g.P("var _ = ", g.Pkg["math"], ".Inf")
  1223. g.P()
  1224. }
  1225. func (g *Generator) generateImported(id *ImportedDescriptor) {
  1226. df := id.o.File()
  1227. filename := *df.Name
  1228. if df.importPath == g.file.importPath {
  1229. // Don't generate type aliases for files in the same Go package as this one.
  1230. return
  1231. }
  1232. if !supportTypeAliases {
  1233. g.Fail(fmt.Sprintf("%s: public imports require at least go1.9", filename))
  1234. }
  1235. g.usedPackages[df.importPath] = true
  1236. for _, sym := range df.exported[id.o] {
  1237. sym.GenerateAlias(g, filename, g.GoPackageName(df.importPath))
  1238. }
  1239. g.P()
  1240. }
  1241. // Generate the enum definitions for this EnumDescriptor.
  1242. func (g *Generator) generateEnum(enum *EnumDescriptor) {
  1243. // The full type name
  1244. typeName := enum.TypeName()
  1245. // The full type name, CamelCased.
  1246. ccTypeName := CamelCaseSlice(typeName)
  1247. ccPrefix := enum.prefix()
  1248. deprecatedEnum := ""
  1249. if enum.GetOptions().GetDeprecated() {
  1250. deprecatedEnum = deprecationComment
  1251. }
  1252. g.PrintComments(enum.path)
  1253. g.P("type ", Annotate(enum.file, enum.path, ccTypeName), " int32", deprecatedEnum)
  1254. g.file.addExport(enum, enumSymbol{ccTypeName, enum.proto3()})
  1255. g.P("const (")
  1256. for i, e := range enum.Value {
  1257. etorPath := fmt.Sprintf("%s,%d,%d", enum.path, enumValuePath, i)
  1258. g.PrintComments(etorPath)
  1259. deprecatedValue := ""
  1260. if e.GetOptions().GetDeprecated() {
  1261. deprecatedValue = deprecationComment
  1262. }
  1263. name := ccPrefix + *e.Name
  1264. g.P(Annotate(enum.file, etorPath, name), " ", ccTypeName, " = ", e.Number, " ", deprecatedValue)
  1265. g.file.addExport(enum, constOrVarSymbol{name, "const", ccTypeName})
  1266. }
  1267. g.P(")")
  1268. g.P()
  1269. g.P("var ", ccTypeName, "_name = map[int32]string{")
  1270. generated := make(map[int32]bool) // avoid duplicate values
  1271. for _, e := range enum.Value {
  1272. duplicate := ""
  1273. if _, present := generated[*e.Number]; present {
  1274. duplicate = "// Duplicate value: "
  1275. }
  1276. g.P(duplicate, e.Number, ": ", strconv.Quote(*e.Name), ",")
  1277. generated[*e.Number] = true
  1278. }
  1279. g.P("}")
  1280. g.P()
  1281. g.P("var ", ccTypeName, "_value = map[string]int32{")
  1282. for _, e := range enum.Value {
  1283. g.P(strconv.Quote(*e.Name), ": ", e.Number, ",")
  1284. }
  1285. g.P("}")
  1286. g.P()
  1287. if !enum.proto3() {
  1288. g.P("func (x ", ccTypeName, ") Enum() *", ccTypeName, " {")
  1289. g.P("p := new(", ccTypeName, ")")
  1290. g.P("*p = x")
  1291. g.P("return p")
  1292. g.P("}")
  1293. g.P()
  1294. }
  1295. g.P("func (x ", ccTypeName, ") String() string {")
  1296. g.P("return ", g.Pkg["proto"], ".EnumName(", ccTypeName, "_name, int32(x))")
  1297. g.P("}")
  1298. g.P()
  1299. if !enum.proto3() {
  1300. g.P("func (x *", ccTypeName, ") UnmarshalJSON(data []byte) error {")
  1301. g.P("value, err := ", g.Pkg["proto"], ".UnmarshalJSONEnum(", ccTypeName, `_value, data, "`, ccTypeName, `")`)
  1302. g.P("if err != nil {")
  1303. g.P("return err")
  1304. g.P("}")
  1305. g.P("*x = ", ccTypeName, "(value)")
  1306. g.P("return nil")
  1307. g.P("}")
  1308. g.P()
  1309. }
  1310. var indexes []string
  1311. for m := enum.parent; m != nil; m = m.parent {
  1312. // XXX: skip groups?
  1313. indexes = append([]string{strconv.Itoa(m.index)}, indexes...)
  1314. }
  1315. indexes = append(indexes, strconv.Itoa(enum.index))
  1316. g.P("func (", ccTypeName, ") EnumDescriptor() ([]byte, []int) {")
  1317. g.P("return ", g.file.VarName(), ", []int{", strings.Join(indexes, ", "), "}")
  1318. g.P("}")
  1319. g.P()
  1320. if enum.file.GetPackage() == "google.protobuf" && enum.GetName() == "NullValue" {
  1321. g.P("func (", ccTypeName, `) XXX_WellKnownType() string { return "`, enum.GetName(), `" }`)
  1322. g.P()
  1323. }
  1324. g.generateEnumRegistration(enum)
  1325. }
  1326. // The tag is a string like "varint,2,opt,name=fieldname,def=7" that
  1327. // identifies details of the field for the protocol buffer marshaling and unmarshaling
  1328. // code. The fields are:
  1329. // wire encoding
  1330. // protocol tag number
  1331. // opt,req,rep for optional, required, or repeated
  1332. // packed whether the encoding is "packed" (optional; repeated primitives only)
  1333. // name= the original declared name
  1334. // enum= the name of the enum type if it is an enum-typed field.
  1335. // proto3 if this field is in a proto3 message
  1336. // def= string representation of the default value, if any.
  1337. // The default value must be in a representation that can be used at run-time
  1338. // to generate the default value. Thus bools become 0 and 1, for instance.
  1339. func (g *Generator) goTag(message *Descriptor, field *descriptor.FieldDescriptorProto, wiretype string) string {
  1340. optrepreq := ""
  1341. switch {
  1342. case isOptional(field):
  1343. optrepreq = "opt"
  1344. case isRequired(field):
  1345. optrepreq = "req"
  1346. case isRepeated(field):
  1347. optrepreq = "rep"
  1348. }
  1349. var defaultValue string
  1350. if dv := field.DefaultValue; dv != nil { // set means an explicit default
  1351. defaultValue = *dv
  1352. // Some types need tweaking.
  1353. switch *field.Type {
  1354. case descriptor.FieldDescriptorProto_TYPE_BOOL:
  1355. if defaultValue == "true" {
  1356. defaultValue = "1"
  1357. } else {
  1358. defaultValue = "0"
  1359. }
  1360. case descriptor.FieldDescriptorProto_TYPE_STRING,
  1361. descriptor.FieldDescriptorProto_TYPE_BYTES:
  1362. // Nothing to do. Quoting is done for the whole tag.
  1363. case descriptor.FieldDescriptorProto_TYPE_ENUM:
  1364. // For enums we need to provide the integer constant.
  1365. obj := g.ObjectNamed(field.GetTypeName())
  1366. if id, ok := obj.(*ImportedDescriptor); ok {
  1367. // It is an enum that was publicly imported.
  1368. // We need the underlying type.
  1369. obj = id.o
  1370. }
  1371. enum, ok := obj.(*EnumDescriptor)
  1372. if !ok {
  1373. log.Printf("obj is a %T", obj)
  1374. if id, ok := obj.(*ImportedDescriptor); ok {
  1375. log.Printf("id.o is a %T", id.o)
  1376. }
  1377. g.Fail("unknown enum type", CamelCaseSlice(obj.TypeName()))
  1378. }
  1379. defaultValue = enum.integerValueAsString(defaultValue)
  1380. case descriptor.FieldDescriptorProto_TYPE_FLOAT:
  1381. if def := defaultValue; def != "inf" && def != "-inf" && def != "nan" {
  1382. if f, err := strconv.ParseFloat(defaultValue, 32); err == nil {
  1383. defaultValue = fmt.Sprint(float32(f))
  1384. }
  1385. }
  1386. case descriptor.FieldDescriptorProto_TYPE_DOUBLE:
  1387. if def := defaultValue; def != "inf" && def != "-inf" && def != "nan" {
  1388. if f, err := strconv.ParseFloat(defaultValue, 64); err == nil {
  1389. defaultValue = fmt.Sprint(f)
  1390. }
  1391. }
  1392. }
  1393. defaultValue = ",def=" + defaultValue
  1394. }
  1395. enum := ""
  1396. if *field.Type == descriptor.FieldDescriptorProto_TYPE_ENUM {
  1397. // We avoid using obj.GoPackageName(), because we want to use the
  1398. // original (proto-world) package name.
  1399. obj := g.ObjectNamed(field.GetTypeName())
  1400. if id, ok := obj.(*ImportedDescriptor); ok {
  1401. obj = id.o
  1402. }
  1403. enum = ",enum="
  1404. if pkg := obj.File().GetPackage(); pkg != "" {
  1405. enum += pkg + "."
  1406. }
  1407. enum += CamelCaseSlice(obj.TypeName())
  1408. }
  1409. packed := ""
  1410. if (field.Options != nil && field.Options.GetPacked()) ||
  1411. // Per https://developers.google.com/protocol-buffers/docs/proto3#simple:
  1412. // "In proto3, repeated fields of scalar numeric types use packed encoding by default."
  1413. (message.proto3() && (field.Options == nil || field.Options.Packed == nil) &&
  1414. isRepeated(field) && isScalar(field)) {
  1415. packed = ",packed"
  1416. }
  1417. fieldName := field.GetName()
  1418. name := fieldName
  1419. if *field.Type == descriptor.FieldDescriptorProto_TYPE_GROUP {
  1420. // We must use the type name for groups instead of
  1421. // the field name to preserve capitalization.
  1422. // type_name in FieldDescriptorProto is fully-qualified,
  1423. // but we only want the local part.
  1424. name = *field.TypeName
  1425. if i := strings.LastIndex(name, "."); i >= 0 {
  1426. name = name[i+1:]
  1427. }
  1428. }
  1429. if json := field.GetJsonName(); field.Extendee == nil && json != "" && json != name {
  1430. // TODO: escaping might be needed, in which case
  1431. // perhaps this should be in its own "json" tag.
  1432. name += ",json=" + json
  1433. }
  1434. name = ",name=" + name
  1435. if message.proto3() {
  1436. name += ",proto3"
  1437. }
  1438. oneof := ""
  1439. if field.OneofIndex != nil {
  1440. oneof = ",oneof"
  1441. }
  1442. return strconv.Quote(fmt.Sprintf("%s,%d,%s%s%s%s%s%s",
  1443. wiretype,
  1444. field.GetNumber(),
  1445. optrepreq,
  1446. packed,
  1447. name,
  1448. enum,
  1449. oneof,
  1450. defaultValue))
  1451. }
  1452. func needsStar(typ descriptor.FieldDescriptorProto_Type) bool {
  1453. switch typ {
  1454. case descriptor.FieldDescriptorProto_TYPE_GROUP:
  1455. return false
  1456. case descriptor.FieldDescriptorProto_TYPE_MESSAGE:
  1457. return false
  1458. case descriptor.FieldDescriptorProto_TYPE_BYTES:
  1459. return false
  1460. }
  1461. return true
  1462. }
  1463. // TypeName is the printed name appropriate for an item. If the object is in the current file,
  1464. // TypeName drops the package name and underscores the rest.
  1465. // Otherwise the object is from another package; and the result is the underscored
  1466. // package name followed by the item name.
  1467. // The result always has an initial capital.
  1468. func (g *Generator) TypeName(obj Object) string {
  1469. return g.DefaultPackageName(obj) + CamelCaseSlice(obj.TypeName())
  1470. }
  1471. // GoType returns a string representing the type name, and the wire type
  1472. func (g *Generator) GoType(message *Descriptor, field *descriptor.FieldDescriptorProto) (typ string, wire string) {
  1473. // TODO: Options.
  1474. switch *field.Type {
  1475. case descriptor.FieldDescriptorProto_TYPE_DOUBLE:
  1476. typ, wire = "float64", "fixed64"
  1477. case descriptor.FieldDescriptorProto_TYPE_FLOAT:
  1478. typ, wire = "float32", "fixed32"
  1479. case descriptor.FieldDescriptorProto_TYPE_INT64:
  1480. typ, wire = "int64", "varint"
  1481. case descriptor.FieldDescriptorProto_TYPE_UINT64:
  1482. typ, wire = "uint64", "varint"
  1483. case descriptor.FieldDescriptorProto_TYPE_INT32:
  1484. typ, wire = "int32", "varint"
  1485. case descriptor.FieldDescriptorProto_TYPE_UINT32:
  1486. typ, wire = "uint32", "varint"
  1487. case descriptor.FieldDescriptorProto_TYPE_FIXED64:
  1488. typ, wire = "uint64", "fixed64"
  1489. case descriptor.FieldDescriptorProto_TYPE_FIXED32:
  1490. typ, wire = "uint32", "fixed32"
  1491. case descriptor.FieldDescriptorProto_TYPE_BOOL:
  1492. typ, wire = "bool", "varint"
  1493. case descriptor.FieldDescriptorProto_TYPE_STRING:
  1494. typ, wire = "string", "bytes"
  1495. case descriptor.FieldDescriptorProto_TYPE_GROUP:
  1496. desc := g.ObjectNamed(field.GetTypeName())
  1497. typ, wire = "*"+g.TypeName(desc), "group"
  1498. case descriptor.FieldDescriptorProto_TYPE_MESSAGE:
  1499. desc := g.ObjectNamed(field.GetTypeName())
  1500. typ, wire = "*"+g.TypeName(desc), "bytes"
  1501. case descriptor.FieldDescriptorProto_TYPE_BYTES:
  1502. typ, wire = "[]byte", "bytes"
  1503. case descriptor.FieldDescriptorProto_TYPE_ENUM:
  1504. desc := g.ObjectNamed(field.GetTypeName())
  1505. typ, wire = g.TypeName(desc), "varint"
  1506. case descriptor.FieldDescriptorProto_TYPE_SFIXED32:
  1507. typ, wire = "int32", "fixed32"
  1508. case descriptor.FieldDescriptorProto_TYPE_SFIXED64:
  1509. typ, wire = "int64", "fixed64"
  1510. case descriptor.FieldDescriptorProto_TYPE_SINT32:
  1511. typ, wire = "int32", "zigzag32"
  1512. case descriptor.FieldDescriptorProto_TYPE_SINT64:
  1513. typ, wire = "int64", "zigzag64"
  1514. default:
  1515. g.Fail("unknown type for", field.GetName())
  1516. }
  1517. if isRepeated(field) {
  1518. typ = "[]" + typ
  1519. } else if message != nil && message.proto3() {
  1520. return
  1521. } else if field.OneofIndex != nil && message != nil {
  1522. return
  1523. } else if needsStar(*field.Type) {
  1524. typ = "*" + typ
  1525. }
  1526. return
  1527. }
  1528. func (g *Generator) RecordTypeUse(t string) {
  1529. if _, ok := g.typeNameToObject[t]; !ok {
  1530. return
  1531. }
  1532. importPath := g.ObjectNamed(t).GoImportPath()
  1533. if importPath == g.outputImportPath {
  1534. // Don't record use of objects in our package.
  1535. return
  1536. }
  1537. g.AddImport(importPath)
  1538. g.usedPackages[importPath] = true
  1539. }
  1540. // Method names that may be generated. Fields with these names get an
  1541. // underscore appended. Any change to this set is a potential incompatible
  1542. // API change because it changes generated field names.
  1543. var methodNames = [...]string{
  1544. "Reset",
  1545. "String",
  1546. "ProtoMessage",
  1547. "Marshal",
  1548. "Unmarshal",
  1549. "ExtensionRangeArray",
  1550. "ExtensionMap",
  1551. "Descriptor",
  1552. }
  1553. // Names of messages in the `google.protobuf` package for which
  1554. // we will generate XXX_WellKnownType methods.
  1555. var wellKnownTypes = map[string]bool{
  1556. "Any": true,
  1557. "Duration": true,
  1558. "Empty": true,
  1559. "Struct": true,
  1560. "Timestamp": true,
  1561. "Value": true,
  1562. "ListValue": true,
  1563. "DoubleValue": true,
  1564. "FloatValue": true,
  1565. "Int64Value": true,
  1566. "UInt64Value": true,
  1567. "Int32Value": true,
  1568. "UInt32Value": true,
  1569. "BoolValue": true,
  1570. "StringValue": true,
  1571. "BytesValue": true,
  1572. }
  1573. // getterDefault finds the default value for the field to return from a getter,
  1574. // regardless of if it's a built in default or explicit from the source. Returns e.g. "nil", `""`, "Default_MessageType_FieldName"
  1575. func (g *Generator) getterDefault(field *descriptor.FieldDescriptorProto, goMessageType string) string {
  1576. if isRepeated(field) {
  1577. return "nil"
  1578. }
  1579. if def := field.GetDefaultValue(); def != "" {
  1580. defaultConstant := g.defaultConstantName(goMessageType, field.GetName())
  1581. if *field.Type != descriptor.FieldDescriptorProto_TYPE_BYTES {
  1582. return defaultConstant
  1583. }
  1584. return "append([]byte(nil), " + defaultConstant + "...)"
  1585. }
  1586. switch *field.Type {
  1587. case descriptor.FieldDescriptorProto_TYPE_BOOL:
  1588. return "false"
  1589. case descriptor.FieldDescriptorProto_TYPE_STRING:
  1590. return `""`
  1591. case descriptor.FieldDescriptorProto_TYPE_GROUP, descriptor.FieldDescriptorProto_TYPE_MESSAGE, descriptor.FieldDescriptorProto_TYPE_BYTES:
  1592. return "nil"
  1593. case descriptor.FieldDescriptorProto_TYPE_ENUM:
  1594. obj := g.ObjectNamed(field.GetTypeName())
  1595. var enum *EnumDescriptor
  1596. if id, ok := obj.(*ImportedDescriptor); ok {
  1597. // The enum type has been publicly imported.
  1598. enum, _ = id.o.(*EnumDescriptor)
  1599. } else {
  1600. enum, _ = obj.(*EnumDescriptor)
  1601. }
  1602. if enum == nil {
  1603. log.Printf("don't know how to generate getter for %s", field.GetName())
  1604. return "nil"
  1605. }
  1606. if len(enum.Value) == 0 {
  1607. return "0 // empty enum"
  1608. }
  1609. first := enum.Value[0].GetName()
  1610. return g.DefaultPackageName(obj) + enum.prefix() + first
  1611. default:
  1612. return "0"
  1613. }
  1614. }
  1615. // defaultConstantName builds the name of the default constant from the message
  1616. // type name and the untouched field name, e.g. "Default_MessageType_FieldName"
  1617. func (g *Generator) defaultConstantName(goMessageType, protoFieldName string) string {
  1618. return "Default_" + goMessageType + "_" + CamelCase(protoFieldName)
  1619. }
  1620. // The different types of fields in a message and how to actually print them
  1621. // Most of the logic for generateMessage is in the methods of these types.
  1622. //
  1623. // Note that the content of the field is irrelevant, a simpleField can contain
  1624. // anything from a scalar to a group (which is just a message).
  1625. //
  1626. // Extension fields (and message sets) are however handled separately.
  1627. //
  1628. // simpleField - a field that is neiter weak nor oneof, possibly repeated
  1629. // oneofField - field containing list of subfields:
  1630. // - oneofSubField - a field within the oneof
  1631. // msgCtx contains the context for the generator functions.
  1632. type msgCtx struct {
  1633. goName string // Go struct name of the message, e.g. MessageName
  1634. message *Descriptor // The descriptor for the message
  1635. }
  1636. // fieldCommon contains data common to all types of fields.
  1637. type fieldCommon struct {
  1638. goName string // Go name of field, e.g. "FieldName" or "Descriptor_"
  1639. protoName string // Name of field in proto language, e.g. "field_name" or "descriptor"
  1640. getterName string // Name of the getter, e.g. "GetFieldName" or "GetDescriptor_"
  1641. goType string // The Go type as a string, e.g. "*int32" or "*OtherMessage"
  1642. tags string // The tag string/annotation for the type, e.g. `protobuf:"varint,8,opt,name=region_id,json=regionId"`
  1643. fullPath string // The full path of the field as used by Annotate etc, e.g. "4,0,2,0"
  1644. }
  1645. // getProtoName gets the proto name of a field, e.g. "field_name" or "descriptor".
  1646. func (f *fieldCommon) getProtoName() string {
  1647. return f.protoName
  1648. }
  1649. // getGoType returns the go type of the field as a string, e.g. "*int32".
  1650. func (f *fieldCommon) getGoType() string {
  1651. return f.goType
  1652. }
  1653. // simpleField is not weak, not a oneof, not an extension. Can be required, optional or repeated.
  1654. type simpleField struct {
  1655. fieldCommon
  1656. protoTypeName string // Proto type name, empty if primitive, e.g. ".google.protobuf.Duration"
  1657. protoType descriptor.FieldDescriptorProto_Type // Actual type enum value, e.g. descriptor.FieldDescriptorProto_TYPE_FIXED64
  1658. deprecated string // Deprecation comment, if any, e.g. "// Deprecated: Do not use."
  1659. getterDef string // Default for getters, e.g. "nil", `""` or "Default_MessageType_FieldName"
  1660. protoDef string // Default value as defined in the proto file, e.g "yoshi" or "5"
  1661. comment string // The full comment for the field, e.g. "// Useful information"
  1662. }
  1663. // decl prints the declaration of the field in the struct (if any).
  1664. func (f *simpleField) decl(g *Generator, mc *msgCtx) {
  1665. g.P(f.comment, Annotate(mc.message.file, f.fullPath, f.goName), "\t", f.goType, "\t`", f.tags, "`", f.deprecated)
  1666. }
  1667. // getter prints the getter for the field.
  1668. func (f *simpleField) getter(g *Generator, mc *msgCtx) {
  1669. star := ""
  1670. tname := f.goType
  1671. if needsStar(f.protoType) && tname[0] == '*' {
  1672. tname = tname[1:]
  1673. star = "*"
  1674. }
  1675. if f.deprecated != "" {
  1676. g.P(f.deprecated)
  1677. }
  1678. g.P("func (m *", mc.goName, ") ", Annotate(mc.message.file, f.fullPath, f.getterName), "() "+tname+" {")
  1679. if f.getterDef == "nil" { // Simpler getter
  1680. g.P("if m != nil {")
  1681. g.P("return m." + f.goName)
  1682. g.P("}")
  1683. g.P("return nil")
  1684. g.P("}")
  1685. g.P()
  1686. return
  1687. }
  1688. if mc.message.proto3() {
  1689. g.P("if m != nil {")
  1690. } else {
  1691. g.P("if m != nil && m." + f.goName + " != nil {")
  1692. }
  1693. g.P("return " + star + "m." + f.goName)
  1694. g.P("}")
  1695. g.P("return ", f.getterDef)
  1696. g.P("}")
  1697. g.P()
  1698. }
  1699. // setter prints the setter method of the field.
  1700. func (f *simpleField) setter(g *Generator, mc *msgCtx) {
  1701. // No setter for regular fields yet
  1702. }
  1703. // getProtoDef returns the default value explicitly stated in the proto file, e.g "yoshi" or "5".
  1704. func (f *simpleField) getProtoDef() string {
  1705. return f.protoDef
  1706. }
  1707. // getProtoTypeName returns the protobuf type name for the field as returned by field.GetTypeName(), e.g. ".google.protobuf.Duration".
  1708. func (f *simpleField) getProtoTypeName() string {
  1709. return f.protoTypeName
  1710. }
  1711. // getProtoType returns the *field.Type value, e.g. descriptor.FieldDescriptorProto_TYPE_FIXED64.
  1712. func (f *simpleField) getProtoType() descriptor.FieldDescriptorProto_Type {
  1713. return f.protoType
  1714. }
  1715. // oneofSubFields are kept slize held by each oneofField. They do not appear in the top level slize of fields for the message.
  1716. type oneofSubField struct {
  1717. fieldCommon
  1718. protoTypeName string // Proto type name, empty if primitive, e.g. ".google.protobuf.Duration"
  1719. protoType descriptor.FieldDescriptorProto_Type // Actual type enum value, e.g. descriptor.FieldDescriptorProto_TYPE_FIXED64
  1720. oneofTypeName string // Type name of the enclosing struct, e.g. "MessageName_FieldName"
  1721. fieldNumber int // Actual field number, as defined in proto, e.g. 12
  1722. getterDef string // Default for getters, e.g. "nil", `""` or "Default_MessageType_FieldName"
  1723. protoDef string // Default value as defined in the proto file, e.g "yoshi" or "5"
  1724. deprecated string // Deprecation comment, if any.
  1725. }
  1726. // typedNil prints a nil casted to the pointer to this field.
  1727. // - for XXX_OneofWrappers
  1728. func (f *oneofSubField) typedNil(g *Generator) {
  1729. g.P("(*", f.oneofTypeName, ")(nil),")
  1730. }
  1731. // getProtoDef returns the default value explicitly stated in the proto file, e.g "yoshi" or "5".
  1732. func (f *oneofSubField) getProtoDef() string {
  1733. return f.protoDef
  1734. }
  1735. // getProtoTypeName returns the protobuf type name for the field as returned by field.GetTypeName(), e.g. ".google.protobuf.Duration".
  1736. func (f *oneofSubField) getProtoTypeName() string {
  1737. return f.protoTypeName
  1738. }
  1739. // getProtoType returns the *field.Type value, e.g. descriptor.FieldDescriptorProto_TYPE_FIXED64.
  1740. func (f *oneofSubField) getProtoType() descriptor.FieldDescriptorProto_Type {
  1741. return f.protoType
  1742. }
  1743. // oneofField represents the oneof on top level.
  1744. // The alternative fields within the oneof are represented by oneofSubField.
  1745. type oneofField struct {
  1746. fieldCommon
  1747. subFields []*oneofSubField // All the possible oneof fields
  1748. comment string // The full comment for the field, e.g. "// Types that are valid to be assigned to MyOneof:\n\\"
  1749. }
  1750. // decl prints the declaration of the field in the struct (if any).
  1751. func (f *oneofField) decl(g *Generator, mc *msgCtx) {
  1752. comment := f.comment
  1753. for _, sf := range f.subFields {
  1754. comment += "//\t*" + sf.oneofTypeName + "\n"
  1755. }
  1756. g.P(comment, Annotate(mc.message.file, f.fullPath, f.goName), " ", f.goType, " `", f.tags, "`")
  1757. }
  1758. // getter for a oneof field will print additional discriminators and interfaces for the oneof,
  1759. // also it prints all the getters for the sub fields.
  1760. func (f *oneofField) getter(g *Generator, mc *msgCtx) {
  1761. // The discriminator type
  1762. g.P("type ", f.goType, " interface {")
  1763. g.P(f.goType, "()")
  1764. g.P("}")
  1765. g.P()
  1766. // The subField types, fulfilling the discriminator type contract
  1767. for _, sf := range f.subFields {
  1768. g.P("type ", Annotate(mc.message.file, sf.fullPath, sf.oneofTypeName), " struct {")
  1769. g.P(Annotate(mc.message.file, sf.fullPath, sf.goName), " ", sf.goType, " `", sf.tags, "`")
  1770. g.P("}")
  1771. g.P()
  1772. }
  1773. for _, sf := range f.subFields {
  1774. g.P("func (*", sf.oneofTypeName, ") ", f.goType, "() {}")
  1775. g.P()
  1776. }
  1777. // Getter for the oneof field
  1778. g.P("func (m *", mc.goName, ") ", Annotate(mc.message.file, f.fullPath, f.getterName), "() ", f.goType, " {")
  1779. g.P("if m != nil { return m.", f.goName, " }")
  1780. g.P("return nil")
  1781. g.P("}")
  1782. g.P()
  1783. // Getters for each oneof
  1784. for _, sf := range f.subFields {
  1785. if sf.deprecated != "" {
  1786. g.P(sf.deprecated)
  1787. }
  1788. g.P("func (m *", mc.goName, ") ", Annotate(mc.message.file, sf.fullPath, sf.getterName), "() "+sf.goType+" {")
  1789. g.P("if x, ok := m.", f.getterName, "().(*", sf.oneofTypeName, "); ok {")
  1790. g.P("return x.", sf.goName)
  1791. g.P("}")
  1792. g.P("return ", sf.getterDef)
  1793. g.P("}")
  1794. g.P()
  1795. }
  1796. }
  1797. // setter prints the setter method of the field.
  1798. func (f *oneofField) setter(g *Generator, mc *msgCtx) {
  1799. // No setters for oneof yet
  1800. }
  1801. // topLevelField interface implemented by all types of fields on the top level (not oneofSubField).
  1802. type topLevelField interface {
  1803. decl(g *Generator, mc *msgCtx) // print declaration within the struct
  1804. getter(g *Generator, mc *msgCtx) // print getter
  1805. setter(g *Generator, mc *msgCtx) // print setter if applicable
  1806. }
  1807. // defField interface implemented by all types of fields that can have defaults (not oneofField, but instead oneofSubField).
  1808. type defField interface {
  1809. getProtoDef() string // default value explicitly stated in the proto file, e.g "yoshi" or "5"
  1810. getProtoName() string // proto name of a field, e.g. "field_name" or "descriptor"
  1811. getGoType() string // go type of the field as a string, e.g. "*int32"
  1812. getProtoTypeName() string // protobuf type name for the field, e.g. ".google.protobuf.Duration"
  1813. getProtoType() descriptor.FieldDescriptorProto_Type // *field.Type value, e.g. descriptor.FieldDescriptorProto_TYPE_FIXED64
  1814. }
  1815. // generateDefaultConstants adds constants for default values if needed, which is only if the default value is.
  1816. // explicit in the proto.
  1817. func (g *Generator) generateDefaultConstants(mc *msgCtx, topLevelFields []topLevelField) {
  1818. // Collect fields that can have defaults
  1819. dFields := []defField{}
  1820. for _, pf := range topLevelFields {
  1821. if f, ok := pf.(*oneofField); ok {
  1822. for _, osf := range f.subFields {
  1823. dFields = append(dFields, osf)
  1824. }
  1825. continue
  1826. }
  1827. dFields = append(dFields, pf.(defField))
  1828. }
  1829. for _, df := range dFields {
  1830. def := df.getProtoDef()
  1831. if def == "" {
  1832. continue
  1833. }
  1834. fieldname := g.defaultConstantName(mc.goName, df.getProtoName())
  1835. typename := df.getGoType()
  1836. if typename[0] == '*' {
  1837. typename = typename[1:]
  1838. }
  1839. kind := "const "
  1840. switch {
  1841. case typename == "bool":
  1842. case typename == "string":
  1843. def = strconv.Quote(def)
  1844. case typename == "[]byte":
  1845. def = "[]byte(" + strconv.Quote(unescape(def)) + ")"
  1846. kind = "var "
  1847. case def == "inf", def == "-inf", def == "nan":
  1848. // These names are known to, and defined by, the protocol language.
  1849. switch def {
  1850. case "inf":
  1851. def = "math.Inf(1)"
  1852. case "-inf":
  1853. def = "math.Inf(-1)"
  1854. case "nan":
  1855. def = "math.NaN()"
  1856. }
  1857. if df.getProtoType() == descriptor.FieldDescriptorProto_TYPE_FLOAT {
  1858. def = "float32(" + def + ")"
  1859. }
  1860. kind = "var "
  1861. case df.getProtoType() == descriptor.FieldDescriptorProto_TYPE_FLOAT:
  1862. if f, err := strconv.ParseFloat(def, 32); err == nil {
  1863. def = fmt.Sprint(float32(f))
  1864. }
  1865. case df.getProtoType() == descriptor.FieldDescriptorProto_TYPE_DOUBLE:
  1866. if f, err := strconv.ParseFloat(def, 64); err == nil {
  1867. def = fmt.Sprint(f)
  1868. }
  1869. case df.getProtoType() == descriptor.FieldDescriptorProto_TYPE_ENUM:
  1870. // Must be an enum. Need to construct the prefixed name.
  1871. obj := g.ObjectNamed(df.getProtoTypeName())
  1872. var enum *EnumDescriptor
  1873. if id, ok := obj.(*ImportedDescriptor); ok {
  1874. // The enum type has been publicly imported.
  1875. enum, _ = id.o.(*EnumDescriptor)
  1876. } else {
  1877. enum, _ = obj.(*EnumDescriptor)
  1878. }
  1879. if enum == nil {
  1880. log.Printf("don't know how to generate constant for %s", fieldname)
  1881. continue
  1882. }
  1883. def = g.DefaultPackageName(obj) + enum.prefix() + def
  1884. }
  1885. g.P(kind, fieldname, " ", typename, " = ", def)
  1886. g.file.addExport(mc.message, constOrVarSymbol{fieldname, kind, ""})
  1887. }
  1888. g.P()
  1889. }
  1890. // generateInternalStructFields just adds the XXX_<something> fields to the message struct.
  1891. func (g *Generator) generateInternalStructFields(mc *msgCtx, topLevelFields []topLevelField) {
  1892. g.P("XXX_NoUnkeyedLiteral\tstruct{} `json:\"-\"`") // prevent unkeyed struct literals
  1893. if len(mc.message.ExtensionRange) > 0 {
  1894. messageset := ""
  1895. if opts := mc.message.Options; opts != nil && opts.GetMessageSetWireFormat() {
  1896. messageset = "protobuf_messageset:\"1\" "
  1897. }
  1898. g.P(g.Pkg["proto"], ".XXX_InternalExtensions `", messageset, "json:\"-\"`")
  1899. }
  1900. g.P("XXX_unrecognized\t[]byte `json:\"-\"`")
  1901. g.P("XXX_sizecache\tint32 `json:\"-\"`")
  1902. }
  1903. // generateOneofFuncs adds all the utility functions for oneof, including marshalling, unmarshalling and sizer.
  1904. func (g *Generator) generateOneofFuncs(mc *msgCtx, topLevelFields []topLevelField) {
  1905. ofields := []*oneofField{}
  1906. for _, f := range topLevelFields {
  1907. if o, ok := f.(*oneofField); ok {
  1908. ofields = append(ofields, o)
  1909. }
  1910. }
  1911. if len(ofields) == 0 {
  1912. return
  1913. }
  1914. // OneofFuncs
  1915. g.P("// XXX_OneofWrappers is for the internal use of the proto package.")
  1916. g.P("func (*", mc.goName, ") XXX_OneofWrappers() []interface{} {")
  1917. g.P("return []interface{}{")
  1918. for _, of := range ofields {
  1919. for _, sf := range of.subFields {
  1920. sf.typedNil(g)
  1921. }
  1922. }
  1923. g.P("}")
  1924. g.P("}")
  1925. g.P()
  1926. }
  1927. // generateMessageStruct adds the actual struct with it's members (but not methods) to the output.
  1928. func (g *Generator) generateMessageStruct(mc *msgCtx, topLevelFields []topLevelField) {
  1929. comments := g.PrintComments(mc.message.path)
  1930. // Guarantee deprecation comments appear after user-provided comments.
  1931. if mc.message.GetOptions().GetDeprecated() {
  1932. if comments {
  1933. // Convention: Separate deprecation comments from original
  1934. // comments with an empty line.
  1935. g.P("//")
  1936. }
  1937. g.P(deprecationComment)
  1938. }
  1939. g.P("type ", Annotate(mc.message.file, mc.message.path, mc.goName), " struct {")
  1940. for _, pf := range topLevelFields {
  1941. pf.decl(g, mc)
  1942. }
  1943. g.generateInternalStructFields(mc, topLevelFields)
  1944. g.P("}")
  1945. }
  1946. // generateGetters adds getters for all fields, including oneofs and weak fields when applicable.
  1947. func (g *Generator) generateGetters(mc *msgCtx, topLevelFields []topLevelField) {
  1948. for _, pf := range topLevelFields {
  1949. pf.getter(g, mc)
  1950. }
  1951. }
  1952. // generateSetters add setters for all fields, including oneofs and weak fields when applicable.
  1953. func (g *Generator) generateSetters(mc *msgCtx, topLevelFields []topLevelField) {
  1954. for _, pf := range topLevelFields {
  1955. pf.setter(g, mc)
  1956. }
  1957. }
  1958. // generateCommonMethods adds methods to the message that are not on a per field basis.
  1959. func (g *Generator) generateCommonMethods(mc *msgCtx) {
  1960. // Reset, String and ProtoMessage methods.
  1961. g.P("func (m *", mc.goName, ") Reset() { *m = ", mc.goName, "{} }")
  1962. g.P("func (m *", mc.goName, ") String() string { return ", g.Pkg["proto"], ".CompactTextString(m) }")
  1963. g.P("func (*", mc.goName, ") ProtoMessage() {}")
  1964. var indexes []string
  1965. for m := mc.message; m != nil; m = m.parent {
  1966. indexes = append([]string{strconv.Itoa(m.index)}, indexes...)
  1967. }
  1968. g.P("func (*", mc.goName, ") Descriptor() ([]byte, []int) {")
  1969. g.P("return ", g.file.VarName(), ", []int{", strings.Join(indexes, ", "), "}")
  1970. g.P("}")
  1971. g.P()
  1972. // TODO: Revisit the decision to use a XXX_WellKnownType method
  1973. // if we change proto.MessageName to work with multiple equivalents.
  1974. if mc.message.file.GetPackage() == "google.protobuf" && wellKnownTypes[mc.message.GetName()] {
  1975. g.P("func (*", mc.goName, `) XXX_WellKnownType() string { return "`, mc.message.GetName(), `" }`)
  1976. g.P()
  1977. }
  1978. // Extension support methods
  1979. if len(mc.message.ExtensionRange) > 0 {
  1980. g.P()
  1981. g.P("var extRange_", mc.goName, " = []", g.Pkg["proto"], ".ExtensionRange{")
  1982. for _, r := range mc.message.ExtensionRange {
  1983. end := fmt.Sprint(*r.End - 1) // make range inclusive on both ends
  1984. g.P("{Start: ", r.Start, ", End: ", end, "},")
  1985. }
  1986. g.P("}")
  1987. g.P("func (*", mc.goName, ") ExtensionRangeArray() []", g.Pkg["proto"], ".ExtensionRange {")
  1988. g.P("return extRange_", mc.goName)
  1989. g.P("}")
  1990. g.P()
  1991. }
  1992. // TODO: It does not scale to keep adding another method for every
  1993. // operation on protos that we want to switch over to using the
  1994. // table-driven approach. Instead, we should only add a single method
  1995. // that allows getting access to the *InternalMessageInfo struct and then
  1996. // calling Unmarshal, Marshal, Merge, Size, and Discard directly on that.
  1997. // Wrapper for table-driven marshaling and unmarshaling.
  1998. g.P("func (m *", mc.goName, ") XXX_Unmarshal(b []byte) error {")
  1999. g.P("return xxx_messageInfo_", mc.goName, ".Unmarshal(m, b)")
  2000. g.P("}")
  2001. g.P("func (m *", mc.goName, ") XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {")
  2002. g.P("return xxx_messageInfo_", mc.goName, ".Marshal(b, m, deterministic)")
  2003. g.P("}")
  2004. g.P("func (m *", mc.goName, ") XXX_Merge(src ", g.Pkg["proto"], ".Message) {")
  2005. g.P("xxx_messageInfo_", mc.goName, ".Merge(m, src)")
  2006. g.P("}")
  2007. g.P("func (m *", mc.goName, ") XXX_Size() int {") // avoid name clash with "Size" field in some message
  2008. g.P("return xxx_messageInfo_", mc.goName, ".Size(m)")
  2009. g.P("}")
  2010. g.P("func (m *", mc.goName, ") XXX_DiscardUnknown() {")
  2011. g.P("xxx_messageInfo_", mc.goName, ".DiscardUnknown(m)")
  2012. g.P("}")
  2013. g.P("var xxx_messageInfo_", mc.goName, " ", g.Pkg["proto"], ".InternalMessageInfo")
  2014. g.P()
  2015. }
  2016. // Generate the type, methods and default constant definitions for this Descriptor.
  2017. func (g *Generator) generateMessage(message *Descriptor) {
  2018. topLevelFields := []topLevelField{}
  2019. oFields := make(map[int32]*oneofField)
  2020. // The full type name
  2021. typeName := message.TypeName()
  2022. // The full type name, CamelCased.
  2023. goTypeName := CamelCaseSlice(typeName)
  2024. usedNames := make(map[string]bool)
  2025. for _, n := range methodNames {
  2026. usedNames[n] = true
  2027. }
  2028. // allocNames finds a conflict-free variation of the given strings,
  2029. // consistently mutating their suffixes.
  2030. // It returns the same number of strings.
  2031. allocNames := func(ns ...string) []string {
  2032. Loop:
  2033. for {
  2034. for _, n := range ns {
  2035. if usedNames[n] {
  2036. for i := range ns {
  2037. ns[i] += "_"
  2038. }
  2039. continue Loop
  2040. }
  2041. }
  2042. for _, n := range ns {
  2043. usedNames[n] = true
  2044. }
  2045. return ns
  2046. }
  2047. }
  2048. mapFieldTypes := make(map[*descriptor.FieldDescriptorProto]string) // keep track of the map fields to be added later
  2049. // Build a structure more suitable for generating the text in one pass
  2050. for i, field := range message.Field {
  2051. // Allocate the getter and the field at the same time so name
  2052. // collisions create field/method consistent names.
  2053. // TODO: This allocation occurs based on the order of the fields
  2054. // in the proto file, meaning that a change in the field
  2055. // ordering can change generated Method/Field names.
  2056. base := CamelCase(*field.Name)
  2057. ns := allocNames(base, "Get"+base)
  2058. fieldName, fieldGetterName := ns[0], ns[1]
  2059. typename, wiretype := g.GoType(message, field)
  2060. jsonName := *field.Name
  2061. tag := fmt.Sprintf("protobuf:%s json:%q", g.goTag(message, field, wiretype), jsonName+",omitempty")
  2062. oneof := field.OneofIndex != nil
  2063. if oneof && oFields[*field.OneofIndex] == nil {
  2064. odp := message.OneofDecl[int(*field.OneofIndex)]
  2065. base := CamelCase(odp.GetName())
  2066. fname := allocNames(base)[0]
  2067. // This is the first field of a oneof we haven't seen before.
  2068. // Generate the union field.
  2069. oneofFullPath := fmt.Sprintf("%s,%d,%d", message.path, messageOneofPath, *field.OneofIndex)
  2070. c, ok := g.makeComments(oneofFullPath)
  2071. if ok {
  2072. c += "\n//\n"
  2073. }
  2074. c += "// Types that are valid to be assigned to " + fname + ":\n"
  2075. // Generate the rest of this comment later,
  2076. // when we've computed any disambiguation.
  2077. dname := "is" + goTypeName + "_" + fname
  2078. tag := `protobuf_oneof:"` + odp.GetName() + `"`
  2079. of := oneofField{
  2080. fieldCommon: fieldCommon{
  2081. goName: fname,
  2082. getterName: "Get"+fname,
  2083. goType: dname,
  2084. tags: tag,
  2085. protoName: odp.GetName(),
  2086. fullPath: oneofFullPath,
  2087. },
  2088. comment: c,
  2089. }
  2090. topLevelFields = append(topLevelFields, &of)
  2091. oFields[*field.OneofIndex] = &of
  2092. }
  2093. if *field.Type == descriptor.FieldDescriptorProto_TYPE_MESSAGE {
  2094. desc := g.ObjectNamed(field.GetTypeName())
  2095. if d, ok := desc.(*Descriptor); ok && d.GetOptions().GetMapEntry() {
  2096. // Figure out the Go types and tags for the key and value types.
  2097. keyField, valField := d.Field[0], d.Field[1]
  2098. keyType, keyWire := g.GoType(d, keyField)
  2099. valType, valWire := g.GoType(d, valField)
  2100. keyTag, valTag := g.goTag(d, keyField, keyWire), g.goTag(d, valField, valWire)
  2101. // We don't use stars, except for message-typed values.
  2102. // Message and enum types are the only two possibly foreign types used in maps,
  2103. // so record their use. They are not permitted as map keys.
  2104. keyType = strings.TrimPrefix(keyType, "*")
  2105. switch *valField.Type {
  2106. case descriptor.FieldDescriptorProto_TYPE_ENUM:
  2107. valType = strings.TrimPrefix(valType, "*")
  2108. g.RecordTypeUse(valField.GetTypeName())
  2109. case descriptor.FieldDescriptorProto_TYPE_MESSAGE:
  2110. g.RecordTypeUse(valField.GetTypeName())
  2111. default:
  2112. valType = strings.TrimPrefix(valType, "*")
  2113. }
  2114. typename = fmt.Sprintf("map[%s]%s", keyType, valType)
  2115. mapFieldTypes[field] = typename // record for the getter generation
  2116. tag += fmt.Sprintf(" protobuf_key:%s protobuf_val:%s", keyTag, valTag)
  2117. }
  2118. }
  2119. fieldDeprecated := ""
  2120. if field.GetOptions().GetDeprecated() {
  2121. fieldDeprecated = deprecationComment
  2122. }
  2123. dvalue := g.getterDefault(field, goTypeName)
  2124. if oneof {
  2125. tname := goTypeName + "_" + fieldName
  2126. // It is possible for this to collide with a message or enum
  2127. // nested in this message. Check for collisions.
  2128. for {
  2129. ok := true
  2130. for _, desc := range message.nested {
  2131. if CamelCaseSlice(desc.TypeName()) == tname {
  2132. ok = false
  2133. break
  2134. }
  2135. }
  2136. for _, enum := range message.enums {
  2137. if CamelCaseSlice(enum.TypeName()) == tname {
  2138. ok = false
  2139. break
  2140. }
  2141. }
  2142. if !ok {
  2143. tname += "_"
  2144. continue
  2145. }
  2146. break
  2147. }
  2148. oneofField := oFields[*field.OneofIndex]
  2149. tag := "protobuf:" + g.goTag(message, field, wiretype)
  2150. sf := oneofSubField{
  2151. fieldCommon: fieldCommon{
  2152. goName: fieldName,
  2153. getterName: fieldGetterName,
  2154. goType: typename,
  2155. tags: tag,
  2156. protoName: field.GetName(),
  2157. fullPath: fmt.Sprintf("%s,%d,%d", message.path, messageFieldPath, i),
  2158. },
  2159. protoTypeName: field.GetTypeName(),
  2160. fieldNumber: int(*field.Number),
  2161. protoType: *field.Type,
  2162. getterDef: dvalue,
  2163. protoDef: field.GetDefaultValue(),
  2164. oneofTypeName: tname,
  2165. deprecated: fieldDeprecated,
  2166. }
  2167. oneofField.subFields = append(oneofField.subFields, &sf)
  2168. g.RecordTypeUse(field.GetTypeName())
  2169. continue
  2170. }
  2171. fieldFullPath := fmt.Sprintf("%s,%d,%d", message.path, messageFieldPath, i)
  2172. c, ok := g.makeComments(fieldFullPath)
  2173. if ok {
  2174. c += "\n"
  2175. }
  2176. rf := simpleField{
  2177. fieldCommon: fieldCommon{
  2178. goName: fieldName,
  2179. getterName: fieldGetterName,
  2180. goType: typename,
  2181. tags: tag,
  2182. protoName: field.GetName(),
  2183. fullPath: fieldFullPath,
  2184. },
  2185. protoTypeName: field.GetTypeName(),
  2186. protoType: *field.Type,
  2187. deprecated: fieldDeprecated,
  2188. getterDef: dvalue,
  2189. protoDef: field.GetDefaultValue(),
  2190. comment: c,
  2191. }
  2192. var pf topLevelField = &rf
  2193. topLevelFields = append(topLevelFields, pf)
  2194. g.RecordTypeUse(field.GetTypeName())
  2195. }
  2196. mc := &msgCtx{
  2197. goName: goTypeName,
  2198. message: message,
  2199. }
  2200. g.generateMessageStruct(mc, topLevelFields)
  2201. g.P()
  2202. g.generateCommonMethods(mc)
  2203. g.P()
  2204. g.generateDefaultConstants(mc, topLevelFields)
  2205. g.P()
  2206. g.generateGetters(mc, topLevelFields)
  2207. g.P()
  2208. g.generateSetters(mc, topLevelFields)
  2209. g.P()
  2210. g.generateOneofFuncs(mc, topLevelFields)
  2211. g.P()
  2212. var oneofTypes []string
  2213. for _, f := range topLevelFields {
  2214. if of, ok := f.(*oneofField); ok {
  2215. for _, osf := range of.subFields {
  2216. oneofTypes = append(oneofTypes, osf.oneofTypeName)
  2217. }
  2218. }
  2219. }
  2220. opts := message.Options
  2221. ms := &messageSymbol{
  2222. sym: goTypeName,
  2223. hasExtensions: len(message.ExtensionRange) > 0,
  2224. isMessageSet: opts != nil && opts.GetMessageSetWireFormat(),
  2225. oneofTypes: oneofTypes,
  2226. }
  2227. g.file.addExport(message, ms)
  2228. for _, ext := range message.ext {
  2229. g.generateExtension(ext)
  2230. }
  2231. fullName := strings.Join(message.TypeName(), ".")
  2232. if g.file.Package != nil {
  2233. fullName = *g.file.Package + "." + fullName
  2234. }
  2235. g.addInitf("%s.RegisterType((*%s)(nil), %q)", g.Pkg["proto"], goTypeName, fullName)
  2236. // Register types for native map types.
  2237. for _, k := range mapFieldKeys(mapFieldTypes) {
  2238. fullName := strings.TrimPrefix(*k.TypeName, ".")
  2239. g.addInitf("%s.RegisterMapType((%s)(nil), %q)", g.Pkg["proto"], mapFieldTypes[k], fullName)
  2240. }
  2241. }
  2242. type byTypeName []*descriptor.FieldDescriptorProto
  2243. func (a byTypeName) Len() int { return len(a) }
  2244. func (a byTypeName) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  2245. func (a byTypeName) Less(i, j int) bool { return *a[i].TypeName < *a[j].TypeName }
  2246. // mapFieldKeys returns the keys of m in a consistent order.
  2247. func mapFieldKeys(m map[*descriptor.FieldDescriptorProto]string) []*descriptor.FieldDescriptorProto {
  2248. keys := make([]*descriptor.FieldDescriptorProto, 0, len(m))
  2249. for k := range m {
  2250. keys = append(keys, k)
  2251. }
  2252. sort.Sort(byTypeName(keys))
  2253. return keys
  2254. }
  2255. var escapeChars = [256]byte{
  2256. 'a': '\a', 'b': '\b', 'f': '\f', 'n': '\n', 'r': '\r', 't': '\t', 'v': '\v', '\\': '\\', '"': '"', '\'': '\'', '?': '?',
  2257. }
  2258. // unescape reverses the "C" escaping that protoc does for default values of bytes fields.
  2259. // It is best effort in that it effectively ignores malformed input. Seemingly invalid escape
  2260. // sequences are conveyed, unmodified, into the decoded result.
  2261. func unescape(s string) string {
  2262. // NB: Sadly, we can't use strconv.Unquote because protoc will escape both
  2263. // single and double quotes, but strconv.Unquote only allows one or the
  2264. // other (based on actual surrounding quotes of its input argument).
  2265. var out []byte
  2266. for len(s) > 0 {
  2267. // regular character, or too short to be valid escape
  2268. if s[0] != '\\' || len(s) < 2 {
  2269. out = append(out, s[0])
  2270. s = s[1:]
  2271. } else if c := escapeChars[s[1]]; c != 0 {
  2272. // escape sequence
  2273. out = append(out, c)
  2274. s = s[2:]
  2275. } else if s[1] == 'x' || s[1] == 'X' {
  2276. // hex escape, e.g. "\x80
  2277. if len(s) < 4 {
  2278. // too short to be valid
  2279. out = append(out, s[:2]...)
  2280. s = s[2:]
  2281. continue
  2282. }
  2283. v, err := strconv.ParseUint(s[2:4], 16, 8)
  2284. if err != nil {
  2285. out = append(out, s[:4]...)
  2286. } else {
  2287. out = append(out, byte(v))
  2288. }
  2289. s = s[4:]
  2290. } else if '0' <= s[1] && s[1] <= '7' {
  2291. // octal escape, can vary from 1 to 3 octal digits; e.g., "\0" "\40" or "\164"
  2292. // so consume up to 2 more bytes or up to end-of-string
  2293. n := len(s[1:]) - len(strings.TrimLeft(s[1:], "01234567"))
  2294. if n > 3 {
  2295. n = 3
  2296. }
  2297. v, err := strconv.ParseUint(s[1:1+n], 8, 8)
  2298. if err != nil {
  2299. out = append(out, s[:1+n]...)
  2300. } else {
  2301. out = append(out, byte(v))
  2302. }
  2303. s = s[1+n:]
  2304. } else {
  2305. // bad escape, just propagate the slash as-is
  2306. out = append(out, s[0])
  2307. s = s[1:]
  2308. }
  2309. }
  2310. return string(out)
  2311. }
  2312. func (g *Generator) generateExtension(ext *ExtensionDescriptor) {
  2313. ccTypeName := ext.DescName()
  2314. extObj := g.ObjectNamed(*ext.Extendee)
  2315. var extDesc *Descriptor
  2316. if id, ok := extObj.(*ImportedDescriptor); ok {
  2317. // This is extending a publicly imported message.
  2318. // We need the underlying type for goTag.
  2319. extDesc = id.o.(*Descriptor)
  2320. } else {
  2321. extDesc = extObj.(*Descriptor)
  2322. }
  2323. extendedType := "*" + g.TypeName(extObj) // always use the original
  2324. field := ext.FieldDescriptorProto
  2325. fieldType, wireType := g.GoType(ext.parent, field)
  2326. tag := g.goTag(extDesc, field, wireType)
  2327. g.RecordTypeUse(*ext.Extendee)
  2328. if n := ext.FieldDescriptorProto.TypeName; n != nil {
  2329. // foreign extension type
  2330. g.RecordTypeUse(*n)
  2331. }
  2332. typeName := ext.TypeName()
  2333. // Special case for proto2 message sets: If this extension is extending
  2334. // proto2.bridge.MessageSet, and its final name component is "message_set_extension",
  2335. // then drop that last component.
  2336. //
  2337. // TODO: This should be implemented in the text formatter rather than the generator.
  2338. // In addition, the situation for when to apply this special case is implemented
  2339. // differently in other languages:
  2340. // https://github.com/google/protobuf/blob/aff10976/src/google/protobuf/text_format.cc#L1560
  2341. if extDesc.GetOptions().GetMessageSetWireFormat() && typeName[len(typeName)-1] == "message_set_extension" {
  2342. typeName = typeName[:len(typeName)-1]
  2343. }
  2344. // For text formatting, the package must be exactly what the .proto file declares,
  2345. // ignoring overrides such as the go_package option, and with no dot/underscore mapping.
  2346. extName := strings.Join(typeName, ".")
  2347. if g.file.Package != nil {
  2348. extName = *g.file.Package + "." + extName
  2349. }
  2350. g.P("var ", ccTypeName, " = &", g.Pkg["proto"], ".ExtensionDesc{")
  2351. g.P("ExtendedType: (", extendedType, ")(nil),")
  2352. g.P("ExtensionType: (", fieldType, ")(nil),")
  2353. g.P("Field: ", field.Number, ",")
  2354. g.P(`Name: "`, extName, `",`)
  2355. g.P("Tag: ", tag, ",")
  2356. g.P(`Filename: "`, g.file.GetName(), `",`)
  2357. g.P("}")
  2358. g.P()
  2359. g.addInitf("%s.RegisterExtension(%s)", g.Pkg["proto"], ext.DescName())
  2360. g.file.addExport(ext, constOrVarSymbol{ccTypeName, "var", ""})
  2361. }
  2362. func (g *Generator) generateInitFunction() {
  2363. if len(g.init) == 0 {
  2364. return
  2365. }
  2366. g.P("func init() {")
  2367. for _, l := range g.init {
  2368. g.P(l)
  2369. }
  2370. g.P("}")
  2371. g.init = nil
  2372. }
  2373. func (g *Generator) generateFileDescriptor(file *FileDescriptor) {
  2374. // Make a copy and trim source_code_info data.
  2375. // TODO: Trim this more when we know exactly what we need.
  2376. pb := proto.Clone(file.FileDescriptorProto).(*descriptor.FileDescriptorProto)
  2377. pb.SourceCodeInfo = nil
  2378. b, err := proto.Marshal(pb)
  2379. if err != nil {
  2380. g.Fail(err.Error())
  2381. }
  2382. var buf bytes.Buffer
  2383. w, _ := gzip.NewWriterLevel(&buf, gzip.BestCompression)
  2384. w.Write(b)
  2385. w.Close()
  2386. b = buf.Bytes()
  2387. v := file.VarName()
  2388. g.P()
  2389. g.P("func init() { ", g.Pkg["proto"], ".RegisterFile(", strconv.Quote(*file.Name), ", ", v, ") }")
  2390. g.P("var ", v, " = []byte{")
  2391. g.P("// ", len(b), " bytes of a gzipped FileDescriptorProto")
  2392. for len(b) > 0 {
  2393. n := 16
  2394. if n > len(b) {
  2395. n = len(b)
  2396. }
  2397. s := ""
  2398. for _, c := range b[:n] {
  2399. s += fmt.Sprintf("0x%02x,", c)
  2400. }
  2401. g.P(s)
  2402. b = b[n:]
  2403. }
  2404. g.P("}")
  2405. }
  2406. func (g *Generator) generateEnumRegistration(enum *EnumDescriptor) {
  2407. // // We always print the full (proto-world) package name here.
  2408. pkg := enum.File().GetPackage()
  2409. if pkg != "" {
  2410. pkg += "."
  2411. }
  2412. // The full type name
  2413. typeName := enum.TypeName()
  2414. // The full type name, CamelCased.
  2415. ccTypeName := CamelCaseSlice(typeName)
  2416. g.addInitf("%s.RegisterEnum(%q, %[3]s_name, %[3]s_value)", g.Pkg["proto"], pkg+ccTypeName, ccTypeName)
  2417. }
  2418. // And now lots of helper functions.
  2419. // Is c an ASCII lower-case letter?
  2420. func isASCIILower(c byte) bool {
  2421. return 'a' <= c && c <= 'z'
  2422. }
  2423. // Is c an ASCII digit?
  2424. func isASCIIDigit(c byte) bool {
  2425. return '0' <= c && c <= '9'
  2426. }
  2427. // CamelCase returns the CamelCased name.
  2428. // If there is an interior underscore followed by a lower case letter,
  2429. // drop the underscore and convert the letter to upper case.
  2430. // There is a remote possibility of this rewrite causing a name collision,
  2431. // but it's so remote we're prepared to pretend it's nonexistent - since the
  2432. // C++ generator lowercases names, it's extremely unlikely to have two fields
  2433. // with different capitalizations.
  2434. // In short, _my_field_name_2 becomes XMyFieldName_2.
  2435. func CamelCase(s string) string {
  2436. if s == "" {
  2437. return ""
  2438. }
  2439. t := make([]byte, 0, 32)
  2440. i := 0
  2441. if s[0] == '_' {
  2442. // Need a capital letter; drop the '_'.
  2443. t = append(t, 'X')
  2444. i++
  2445. }
  2446. // Invariant: if the next letter is lower case, it must be converted
  2447. // to upper case.
  2448. // That is, we process a word at a time, where words are marked by _ or
  2449. // upper case letter. Digits are treated as words.
  2450. for ; i < len(s); i++ {
  2451. c := s[i]
  2452. if c == '_' && i+1 < len(s) && isASCIILower(s[i+1]) {
  2453. continue // Skip the underscore in s.
  2454. }
  2455. if isASCIIDigit(c) {
  2456. t = append(t, c)
  2457. continue
  2458. }
  2459. // Assume we have a letter now - if not, it's a bogus identifier.
  2460. // The next word is a sequence of characters that must start upper case.
  2461. if isASCIILower(c) {
  2462. c ^= ' ' // Make it a capital letter.
  2463. }
  2464. t = append(t, c) // Guaranteed not lower case.
  2465. // Accept lower case sequence that follows.
  2466. for i+1 < len(s) && isASCIILower(s[i+1]) {
  2467. i++
  2468. t = append(t, s[i])
  2469. }
  2470. }
  2471. return string(t)
  2472. }
  2473. // CamelCaseSlice is like CamelCase, but the argument is a slice of strings to
  2474. // be joined with "_".
  2475. func CamelCaseSlice(elem []string) string { return CamelCase(strings.Join(elem, "_")) }
  2476. // dottedSlice turns a sliced name into a dotted name.
  2477. func dottedSlice(elem []string) string { return strings.Join(elem, ".") }
  2478. // Is this field optional?
  2479. func isOptional(field *descriptor.FieldDescriptorProto) bool {
  2480. return field.Label != nil && *field.Label == descriptor.FieldDescriptorProto_LABEL_OPTIONAL
  2481. }
  2482. // Is this field required?
  2483. func isRequired(field *descriptor.FieldDescriptorProto) bool {
  2484. return field.Label != nil && *field.Label == descriptor.FieldDescriptorProto_LABEL_REQUIRED
  2485. }
  2486. // Is this field repeated?
  2487. func isRepeated(field *descriptor.FieldDescriptorProto) bool {
  2488. return field.Label != nil && *field.Label == descriptor.FieldDescriptorProto_LABEL_REPEATED
  2489. }
  2490. // Is this field a scalar numeric type?
  2491. func isScalar(field *descriptor.FieldDescriptorProto) bool {
  2492. if field.Type == nil {
  2493. return false
  2494. }
  2495. switch *field.Type {
  2496. case descriptor.FieldDescriptorProto_TYPE_DOUBLE,
  2497. descriptor.FieldDescriptorProto_TYPE_FLOAT,
  2498. descriptor.FieldDescriptorProto_TYPE_INT64,
  2499. descriptor.FieldDescriptorProto_TYPE_UINT64,
  2500. descriptor.FieldDescriptorProto_TYPE_INT32,
  2501. descriptor.FieldDescriptorProto_TYPE_FIXED64,
  2502. descriptor.FieldDescriptorProto_TYPE_FIXED32,
  2503. descriptor.FieldDescriptorProto_TYPE_BOOL,
  2504. descriptor.FieldDescriptorProto_TYPE_UINT32,
  2505. descriptor.FieldDescriptorProto_TYPE_ENUM,
  2506. descriptor.FieldDescriptorProto_TYPE_SFIXED32,
  2507. descriptor.FieldDescriptorProto_TYPE_SFIXED64,
  2508. descriptor.FieldDescriptorProto_TYPE_SINT32,
  2509. descriptor.FieldDescriptorProto_TYPE_SINT64:
  2510. return true
  2511. default:
  2512. return false
  2513. }
  2514. }
  2515. // badToUnderscore is the mapping function used to generate Go names from package names,
  2516. // which can be dotted in the input .proto file. It replaces non-identifier characters such as
  2517. // dot or dash with underscore.
  2518. func badToUnderscore(r rune) rune {
  2519. if unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' {
  2520. return r
  2521. }
  2522. return '_'
  2523. }
  2524. // baseName returns the last path element of the name, with the last dotted suffix removed.
  2525. func baseName(name string) string {
  2526. // First, find the last element
  2527. if i := strings.LastIndex(name, "/"); i >= 0 {
  2528. name = name[i+1:]
  2529. }
  2530. // Now drop the suffix
  2531. if i := strings.LastIndex(name, "."); i >= 0 {
  2532. name = name[0:i]
  2533. }
  2534. return name
  2535. }
  2536. // The SourceCodeInfo message describes the location of elements of a parsed
  2537. // .proto file by way of a "path", which is a sequence of integers that
  2538. // describe the route from a FileDescriptorProto to the relevant submessage.
  2539. // The path alternates between a field number of a repeated field, and an index
  2540. // into that repeated field. The constants below define the field numbers that
  2541. // are used.
  2542. //
  2543. // See descriptor.proto for more information about this.
  2544. const (
  2545. // tag numbers in FileDescriptorProto
  2546. packagePath = 2 // package
  2547. messagePath = 4 // message_type
  2548. enumPath = 5 // enum_type
  2549. // tag numbers in DescriptorProto
  2550. messageFieldPath = 2 // field
  2551. messageMessagePath = 3 // nested_type
  2552. messageEnumPath = 4 // enum_type
  2553. messageOneofPath = 8 // oneof_decl
  2554. // tag numbers in EnumDescriptorProto
  2555. enumValuePath = 2 // value
  2556. )
  2557. var supportTypeAliases bool
  2558. func init() {
  2559. for _, tag := range build.Default.ReleaseTags {
  2560. if tag == "go1.9" {
  2561. supportTypeAliases = true
  2562. return
  2563. }
  2564. }
  2565. }