blob: 9da11d9916c0237d15d6ff998dbe351975d742e8 [file] [log] [blame]
Damien Neil220c2022018-08-15 11:24:18 -07001package protogen
2
3import (
Damien Neild9016772018-08-23 14:39:30 -07004 "fmt"
Damien Neil220c2022018-08-15 11:24:18 -07005 "go/token"
6 "strconv"
7 "strings"
8 "unicode"
9 "unicode/utf8"
Damien Neilabc6fc12018-08-23 14:39:30 -070010
Joe Tsai01ab2962018-09-21 17:44:00 -070011 "github.com/golang/protobuf/v2/reflect/protoreflect"
Damien Neil220c2022018-08-15 11:24:18 -070012)
13
Damien Neild9016772018-08-23 14:39:30 -070014// A GoIdent is a Go identifier, consisting of a name and import path.
15type GoIdent struct {
16 GoName string
17 GoImportPath GoImportPath
18}
19
20func (id GoIdent) String() string { return fmt.Sprintf("%q.%v", id.GoImportPath, id.GoName) }
Damien Neilc7d07d92018-08-22 13:46:02 -070021
Damien Neilabc6fc12018-08-23 14:39:30 -070022// newGoIdent returns the Go identifier for a descriptor.
23func newGoIdent(f *File, d protoreflect.Descriptor) GoIdent {
24 name := strings.TrimPrefix(string(d.FullName()), string(f.Desc.Package())+".")
25 return GoIdent{
26 GoName: camelCase(name),
27 GoImportPath: f.GoImportPath,
28 }
29}
30
Damien Neil220c2022018-08-15 11:24:18 -070031// A GoImportPath is the import path of a Go package. e.g., "google.golang.org/genproto/protobuf".
32type GoImportPath string
33
34func (p GoImportPath) String() string { return strconv.Quote(string(p)) }
35
36// A GoPackageName is the name of a Go package. e.g., "protobuf".
37type GoPackageName string
38
39// cleanPacakgeName converts a string to a valid Go package name.
40func cleanPackageName(name string) GoPackageName {
41 name = strings.Map(badToUnderscore, name)
42 // Identifier must not be keyword: insert _.
43 if token.Lookup(name).IsKeyword() {
44 name = "_" + name
45 }
46 // Identifier must not begin with digit: insert _.
47 if r, _ := utf8.DecodeRuneInString(name); unicode.IsDigit(r) {
48 name = "_" + name
49 }
50 return GoPackageName(name)
51}
52
Damien Neil87214662018-10-05 11:23:35 -070053var isGoPredeclaredIdentifier = map[string]bool{
54 "append": true,
55 "bool": true,
56 "byte": true,
57 "cap": true,
58 "close": true,
59 "complex": true,
60 "complex128": true,
61 "complex64": true,
62 "copy": true,
63 "delete": true,
64 "error": true,
65 "false": true,
66 "float32": true,
67 "float64": true,
68 "imag": true,
69 "int": true,
70 "int16": true,
71 "int32": true,
72 "int64": true,
73 "int8": true,
74 "iota": true,
75 "len": true,
76 "make": true,
77 "new": true,
78 "nil": true,
79 "panic": true,
80 "print": true,
81 "println": true,
82 "real": true,
83 "recover": true,
84 "rune": true,
85 "string": true,
86 "true": true,
87 "uint": true,
88 "uint16": true,
89 "uint32": true,
90 "uint64": true,
91 "uint8": true,
92 "uintptr": true,
93}
94
Damien Neil220c2022018-08-15 11:24:18 -070095// badToUnderscore is the mapping function used to generate Go names from package names,
96// which can be dotted in the input .proto file. It replaces non-identifier characters such as
97// dot or dash with underscore.
98func badToUnderscore(r rune) rune {
99 if unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' {
100 return r
101 }
102 return '_'
103}
104
105// baseName returns the last path element of the name, with the last dotted suffix removed.
106func baseName(name string) string {
107 // First, find the last element
108 if i := strings.LastIndex(name, "/"); i >= 0 {
109 name = name[i+1:]
110 }
111 // Now drop the suffix
112 if i := strings.LastIndex(name, "."); i >= 0 {
113 name = name[:i]
114 }
115 return name
116}
Damien Neilc7d07d92018-08-22 13:46:02 -0700117
118// camelCase converts a name to CamelCase.
119//
120// If there is an interior underscore followed by a lower case letter,
121// drop the underscore and convert the letter to upper case.
122// There is a remote possibility of this rewrite causing a name collision,
123// but it's so remote we're prepared to pretend it's nonexistent - since the
124// C++ generator lowercases names, it's extremely unlikely to have two fields
125// with different capitalizations.
Damien Neild9016772018-08-23 14:39:30 -0700126func camelCase(s string) string {
Damien Neilc7d07d92018-08-22 13:46:02 -0700127 if s == "" {
128 return ""
129 }
130 var t []byte
131 i := 0
132 // Invariant: if the next letter is lower case, it must be converted
133 // to upper case.
134 // That is, we process a word at a time, where words are marked by _ or
135 // upper case letter. Digits are treated as words.
136 for ; i < len(s); i++ {
137 c := s[i]
138 switch {
Damien Neil3863ee52018-10-09 13:24:04 -0700139 case c == '.' && i+1 < len(s) && isASCIILower(s[i+1]):
140 // Skip over .<lowercase>, to match historic behavior.
Damien Neilc7d07d92018-08-22 13:46:02 -0700141 case c == '.':
142 t = append(t, '_') // Convert . to _.
143 case c == '_' && (i == 0 || s[i-1] == '.'):
144 // Convert initial _ to X so we start with a capital letter.
145 // Do the same for _ after .; not strictly necessary, but matches
146 // historic behavior.
147 t = append(t, 'X')
148 case c == '_' && i+1 < len(s) && isASCIILower(s[i+1]):
149 // Skip the underscore in s.
150 case isASCIIDigit(c):
151 t = append(t, c)
152 default:
153 // Assume we have a letter now - if not, it's a bogus identifier.
154 // The next word is a sequence of characters that must start upper case.
155 if isASCIILower(c) {
156 c ^= ' ' // Make it a capital letter.
157 }
158 t = append(t, c) // Guaranteed not lower case.
159 // Accept lower case sequence that follows.
160 for i+1 < len(s) && isASCIILower(s[i+1]) {
161 i++
162 t = append(t, s[i])
163 }
164 }
165 }
Damien Neild9016772018-08-23 14:39:30 -0700166 return string(t)
Damien Neilc7d07d92018-08-22 13:46:02 -0700167}
168
169// Is c an ASCII lower-case letter?
170func isASCIILower(c byte) bool {
171 return 'a' <= c && c <= 'z'
172}
173
174// Is c an ASCII digit?
175func isASCIIDigit(c byte) bool {
176 return '0' <= c && c <= '9'
177}