blob: e291805fb8a66b74d56f97588a0ab52c56d38248 [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
Joe Tsaib6405bd2018-11-15 14:44:37 -080049// cleanPackageName converts a string to a valid Go package name.
Damien Neil220c2022018-08-15 11:24:18 -070050func cleanPackageName(name string) GoPackageName {
Joe Tsaib6405bd2018-11-15 14:44:37 -080051 return GoPackageName(cleanGoName(name, false))
52}
53
54// cleanGoName converts a string to a valid Go identifier.
55// If mustExport, then the returned identifier is exported if not already.
Joe Tsai2c6f0982018-12-13 18:37:25 -080056func cleanGoName(s string, mustExport bool) string {
57 // Sanitize the input to the set of valid characters,
58 // which must be '_' or be in the Unicode L or N categories.
59 s = strings.Map(func(r rune) rune {
Joe Tsaib6405bd2018-11-15 14:44:37 -080060 if unicode.IsLetter(r) || unicode.IsDigit(r) {
61 return r
62 }
63 return '_'
Joe Tsai2c6f0982018-12-13 18:37:25 -080064 }, s)
65 r, n := utf8.DecodeRuneInString(s)
66
67 // Export the identifier by either uppercasing the first character or by
68 // prepending 'X' (to ensure name starts in the Unicode Lu category).
Joe Tsaib6405bd2018-11-15 14:44:37 -080069 if mustExport {
Joe Tsai2c6f0982018-12-13 18:37:25 -080070 // If possible, uppercase the first character. However, not all
71 // characters in the Unicode L category have an Lu equivalent.
72 if unicode.IsUpper(unicode.ToUpper(r)) {
73 return string(unicode.ToUpper(r)) + s[n:]
Joe Tsaib6405bd2018-11-15 14:44:37 -080074 }
Joe Tsai2c6f0982018-12-13 18:37:25 -080075 return "X" + s
Damien Neil220c2022018-08-15 11:24:18 -070076 }
Joe Tsai2c6f0982018-12-13 18:37:25 -080077
78 // Prepend '_' in the event of a Go keyword conflict or if
79 // the identifier is invalid (does not start in the Unicode L category).
80 if token.Lookup(s).IsKeyword() || !unicode.IsLetter(r) {
81 return "_" + s
82 }
83 return s
Damien Neil220c2022018-08-15 11:24:18 -070084}
85
Damien Neil87214662018-10-05 11:23:35 -070086var isGoPredeclaredIdentifier = map[string]bool{
87 "append": true,
88 "bool": true,
89 "byte": true,
90 "cap": true,
91 "close": true,
92 "complex": true,
93 "complex128": true,
94 "complex64": true,
95 "copy": true,
96 "delete": true,
97 "error": true,
98 "false": true,
99 "float32": true,
100 "float64": true,
101 "imag": true,
102 "int": true,
103 "int16": true,
104 "int32": true,
105 "int64": true,
106 "int8": true,
107 "iota": true,
108 "len": true,
109 "make": true,
110 "new": true,
111 "nil": true,
112 "panic": true,
113 "print": true,
114 "println": true,
115 "real": true,
116 "recover": true,
117 "rune": true,
118 "string": true,
119 "true": true,
120 "uint": true,
121 "uint16": true,
122 "uint32": true,
123 "uint64": true,
124 "uint8": true,
125 "uintptr": true,
126}
127
Damien Neil220c2022018-08-15 11:24:18 -0700128// baseName returns the last path element of the name, with the last dotted suffix removed.
129func baseName(name string) string {
130 // First, find the last element
131 if i := strings.LastIndex(name, "/"); i >= 0 {
132 name = name[i+1:]
133 }
134 // Now drop the suffix
135 if i := strings.LastIndex(name, "."); i >= 0 {
136 name = name[:i]
137 }
138 return name
139}
Damien Neilc7d07d92018-08-22 13:46:02 -0700140
141// camelCase converts a name to CamelCase.
142//
143// If there is an interior underscore followed by a lower case letter,
144// drop the underscore and convert the letter to upper case.
145// There is a remote possibility of this rewrite causing a name collision,
146// but it's so remote we're prepared to pretend it's nonexistent - since the
147// C++ generator lowercases names, it's extremely unlikely to have two fields
148// with different capitalizations.
Damien Neild9016772018-08-23 14:39:30 -0700149func camelCase(s string) string {
Damien Neilc7d07d92018-08-22 13:46:02 -0700150 // Invariant: if the next letter is lower case, it must be converted
151 // to upper case.
152 // That is, we process a word at a time, where words are marked by _ or
153 // upper case letter. Digits are treated as words.
Joe Tsai2c6f0982018-12-13 18:37:25 -0800154 var b []byte
155 for i := 0; i < len(s); i++ {
Damien Neilc7d07d92018-08-22 13:46:02 -0700156 c := s[i]
157 switch {
Damien Neil3863ee52018-10-09 13:24:04 -0700158 case c == '.' && i+1 < len(s) && isASCIILower(s[i+1]):
Joe Tsai2c6f0982018-12-13 18:37:25 -0800159 // Skip over '.' in ".{{lowercase}}".
Damien Neilc7d07d92018-08-22 13:46:02 -0700160 case c == '.':
Joe Tsai2c6f0982018-12-13 18:37:25 -0800161 b = append(b, '_') // convert '.' to '_'
Damien Neilc7d07d92018-08-22 13:46:02 -0700162 case c == '_' && (i == 0 || s[i-1] == '.'):
Joe Tsai2c6f0982018-12-13 18:37:25 -0800163 // Convert initial '_' to ensure we start with a capital letter.
164 // Do the same for '_' after '.' to match historic behavior.
165 b = append(b, 'X') // convert '_' to 'X'
Damien Neilc7d07d92018-08-22 13:46:02 -0700166 case c == '_' && i+1 < len(s) && isASCIILower(s[i+1]):
Joe Tsai2c6f0982018-12-13 18:37:25 -0800167 // Skip over '_' in "_{{lowercase}}".
Damien Neilc7d07d92018-08-22 13:46:02 -0700168 case isASCIIDigit(c):
Joe Tsai2c6f0982018-12-13 18:37:25 -0800169 b = append(b, c)
Damien Neilc7d07d92018-08-22 13:46:02 -0700170 default:
171 // Assume we have a letter now - if not, it's a bogus identifier.
172 // The next word is a sequence of characters that must start upper case.
173 if isASCIILower(c) {
Joe Tsai2c6f0982018-12-13 18:37:25 -0800174 c -= 'a' - 'A' // convert lowercase to uppercase
Damien Neilc7d07d92018-08-22 13:46:02 -0700175 }
Joe Tsai2c6f0982018-12-13 18:37:25 -0800176 b = append(b, c)
177
Damien Neilc7d07d92018-08-22 13:46:02 -0700178 // Accept lower case sequence that follows.
Joe Tsai2c6f0982018-12-13 18:37:25 -0800179 for ; i+1 < len(s) && isASCIILower(s[i+1]); i++ {
180 b = append(b, s[i+1])
Damien Neilc7d07d92018-08-22 13:46:02 -0700181 }
182 }
183 }
Joe Tsai2c6f0982018-12-13 18:37:25 -0800184 return string(b)
Damien Neilc7d07d92018-08-22 13:46:02 -0700185}
186
187// Is c an ASCII lower-case letter?
188func isASCIILower(c byte) bool {
189 return 'a' <= c && c <= 'z'
190}
191
192// Is c an ASCII digit?
193func isASCIIDigit(c byte) bool {
194 return '0' <= c && c <= '9'
195}