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