/
generate.go
442 lines (377 loc) · 10.8 KB
/
generate.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
// Package types is responsible for parsing the Godot headers for type definitions
// and generating Go wrappers around that structure.
package types
import (
"bytes"
"github.com/kr/pretty"
"github.com/pinzolo/casee"
"github.com/shadowapex/godot-go/cmd/generate/methods"
"log"
"os"
"os/exec"
"sort"
"strings"
"text/template"
)
// View is a structure that holds the api struct, so it can be used inside
// our temaplte.
type View struct {
Headers []string
TypeDefinitions []TypeDef
MethodDefinitions []Method
IgnoreMethods []string
}
// Debug will allow you to log inside the running template.
func (v View) Debug(itm string) string {
log.Println("Template Log:", itm)
return ""
}
// IsValidProperty will determine if we should be generating the given property
// in our Go structure.
func (v View) IsValidProperty(prop TypeDef) bool {
if strings.Contains(prop.Name, "_touch_that") {
return false
}
return true
}
// IsGodotBaseType will check to see if the given simple type definition is defining
// a built-in C type or a Godot type.
func (v View) IsGodotBaseType(typeDef TypeDef) bool {
if strings.Contains(typeDef.Base, "godot_") {
return true
}
return false
}
// ToGoBaseType will convert a base type name to the correct Go base type.
func (v View) ToGoBaseType(base string) string {
switch base {
case "float":
return "float64"
case "wchar_t":
return "string"
}
return base
}
func (v View) ToGoName(str string) string {
str = strings.Replace(str, "godot_", "", 1)
str = strings.Replace(str, "GODOT_", "", 1)
return casee.ToPascalCase(str)
}
func (v View) ToGoReturnType(str string) string {
str = v.ToGoArgType(str, true)
if strings.Contains(str, "Void") {
return ""
}
return str
}
func (v View) HasReturn(str string) bool {
if str == "void" || str == "Void" || strings.Contains(str, "void") {
return false
}
return true
}
func (v View) HasPointerReturn(str string) bool {
if strings.Contains(str, "*") {
return true
}
return false
}
func (v View) IsVoidPointerType(str string) bool {
switch str {
case "godot_object *", "const godot_object *":
return true
}
return false
}
func (v View) IsWcharT(str string) bool {
if strings.Contains(str, "wchar_t") {
return true
}
return false
}
func (v View) IsDoublePointer(str string) bool {
if strings.Contains(str, "**") {
return true
}
return false
}
func (v View) ToGoArgType(str string, parseArray bool) string {
str = strings.Replace(str, "const ", "", -1)
str = v.ToGoName(str)
str = strings.Replace(str, "*", "", 1)
str = strings.TrimSpace(str)
// If the string still contains a *, it is a list.
if strings.Contains(str, "*") {
str = strings.Replace(str, "*", "", 1)
if parseArray {
str = "[]" + str
}
}
return str
}
func (v View) ToGoArgName(str string) string {
if strings.HasPrefix(str, "p_") {
str = strings.Replace(str, "p_", "", 1)
}
if strings.HasPrefix(str, "r_") {
str = strings.Replace(str, "r_", "", 1)
}
str = casee.ToCamelCase(str)
// Check for any reserved names
switch str {
case "type":
return "aType"
case "default":
return "aDefault"
case "var":
return "variable"
case "func":
return "function"
case "return":
return "returns"
case "interface":
return "intrfce"
case "string":
return "str"
}
return str
}
func (v View) IsBasicType(str string) bool {
switch str {
case "Uint", "WcharT", "Bool", "Double", "Error", "Int", "Int64T", "Uint64T", "Uint8T", "Uint32T", "Real", "MethodRpcMode", "PropertyHint", "SignedChar", "UnsignedChar", "Vector3Axis":
return true
}
return false
}
// OutputCArg will determine if we need to reference, dereference, etc. an argument
// before passing it to a C function.
func (v View) OutputCArg(arg []string) string {
argType := arg[0]
// For basic types, we usually don't pass by pointer.
if v.IsBasicType(v.ToGoArgType(argType, true)) {
if v.HasPointerReturn(argType) {
return "&"
}
if argType == "wchar_t" && !v.HasPointerReturn(argType) {
return "*"
}
return ""
}
// Non-basic types are returned as pointers. If the C function doesn't want
// a pointer, we need to dereference the argument.
if !v.HasPointerReturn(argType) {
return "*"
}
return ""
}
// MethodsList returns all of the methods that match this typedef.
func (v View) MethodsList(typeDef TypeDef) []Method {
methods := []Method{}
// Look for all methods that match this typedef name.
for _, method := range v.MethodDefinitions {
ignoreMethod := false
for _, ignMethod := range v.IgnoreMethods {
if method.Name == ignMethod {
ignoreMethod = true
}
}
if ignoreMethod {
continue
}
for _, arg := range method.Arguments {
argName := arg[1]
argType := strings.Replace(arg[0], "const", "", 1)
argType = strings.Replace(argType, "*", "", 1)
argType = strings.TrimSpace(argType)
if argType == typeDef.Name && argName == "p_self" {
methods = append(methods, method)
break
} else if strings.Contains(method.Name, typeDef.Name) && v.MethodIsConstructor(method) {
methods = append(methods, method)
break
}
}
}
return methods
}
func (v View) MethodIsConstructor(method Method) bool {
if strings.Contains(method.Name, "_new") {
return true
}
return false
}
func (v View) NotSelfArg(str string) bool {
if str == "self" || str == "p_self" {
return false
}
return true
}
func (v View) StripPointer(str string) string {
str = strings.Replace(str, "*", "", 1)
str = strings.TrimSpace(str)
return str
}
func (v View) ToGoMethodName(typeDef TypeDef, method Method) string {
methodName := method.Name
// Replace the typedef in the method name
methodName = strings.Replace(methodName, typeDef.Name, "", 1)
// Swap some things around if this is a constructor
if v.MethodIsConstructor(method) {
methodName = strings.Replace(methodName, "_new", "", 1)
methodName = "new_" + typeDef.GoName + "_" + methodName
}
if strings.HasPrefix(methodName, "2") {
methodName = "T" + methodName
}
return casee.ToPascalCase(methodName)
}
type Method struct {
Name string
ReturnType string
Arguments [][]string
}
// Generate will generate Go wrappers for all Godot base types
func Generate() {
// Get the GOPATH so we can locate our templates.
goPath := os.Getenv("GOPATH")
if goPath == "" {
panic("$GOPATH is not defined. Run 'export GOPATH=/path/to/go/path' before executing this.")
}
packagePath := goPath + "/src/github.com/shadowapex/godot-go"
// Set up headers/structs to ignore. Definitions in the given headers
// with the given name will not be added to the returned list of type definitions.
// We'll need to manually create these structures.
ignoreHeaders := []string{
"pluginscript/godot_pluginscript.h",
}
ignoreStructs := []string{
"godot_char_type",
"godot_gdnative_api_struct",
"godot_gdnative_core_api_struct",
"godot_gdnative_ext_arvr_api_struct",
"godot_gdnative_ext_nativescript_1_1_api_struct",
"godot_gdnative_ext_nativescript_api_struct",
"godot_gdnative_ext_pluginscript_api_struct",
"godot_gdnative_init_options",
"godot_instance_binding_functions",
"godot_instance_create_func",
"godot_instance_destroy_func",
"godot_instance_method",
"godot_method_attributes",
"godot_property_get_func",
"godot_property_set_func",
"godot_property_usage_flags",
}
ignoreMethods := []string{
"godot_string_new_with_wide_string",
"godot_string_new",
"godot_string_new_copy",
"godot_string_name_new",
"godot_string_name_new_data",
"godot_transform2d_new",
"godot_transform2d_new_axis_origin",
"godot_transform2d_new_identity",
}
// Parse all available methods
gdnativeAPI := methods.Parse()
// Convert the API definitions into a method struct
allMethodDefinitions := []Method{}
for _, api := range gdnativeAPI.Core.API {
method := Method{
Name: api.Name,
ReturnType: api.ReturnType,
Arguments: api.Arguments,
}
allMethodDefinitions = append(allMethodDefinitions, method)
}
// Parse the Godot header files for type definitions
allTypeDefinitions := Parse(ignoreHeaders, ignoreStructs)
// Create a map of the type definitions by header name
defMap := map[string][]TypeDef{}
// Organize the type definitions by header name
for _, typeDef := range allTypeDefinitions {
if _, ok := defMap[typeDef.HeaderName]; ok {
defMap[typeDef.HeaderName] = append(defMap[typeDef.HeaderName], typeDef)
} else {
defMap[typeDef.HeaderName] = []TypeDef{typeDef}
}
}
pretty.Println(defMap)
// Loop through each header name and generate the Go code in a file based
// on the header name.
log.Println("Generating Go wrappers for Godot base types...")
for headerName, typeDefs := range defMap {
// Convert the header name into the Go filename
headerPath := strings.Split(headerName, "/")
outFileName := strings.Replace(headerPath[len(headerPath)-1], ".h", ".gen.go", 1)
outFileName = strings.Replace(outFileName, "godot_", "", 1)
log.Println(" Generating Go code for:", outFileName+"...")
// Create a structure for our template view. This will contain all of
// the data we need to construct our Go wrappers.
var view View
// Add the type definitions for this file to our view.
view.MethodDefinitions = allMethodDefinitions
view.TypeDefinitions = typeDefs
view.Headers = []string{}
view.IgnoreMethods = ignoreMethods
// Collect all of the headers we need to use in our template.
headers := map[string]bool{}
for _, typeDef := range view.TypeDefinitions {
headers[typeDef.HeaderName] = true
}
for header := range headers {
view.Headers = append(view.Headers, header)
}
sort.Strings(view.Headers)
// Write the file using our template.
WriteTemplate(
packagePath+"/cmd/generate/templates/types.go.tmpl",
packagePath+"/gdnative/"+outFileName,
view,
)
// Run gofmt on the generated Go file.
log.Println(" Running gofmt on output:", outFileName+"...")
GoFmt(packagePath + "/gdnative/" + outFileName)
log.Println(" Running goimports on output:", outFileName+"...")
GoImports(packagePath + "/gdnative/" + outFileName)
}
pretty.Println(allMethodDefinitions)
}
func WriteTemplate(templatePath, outputPath string, view View) {
// Create a template from our template file.
t, err := template.ParseFiles(templatePath)
if err != nil {
log.Fatal("Error parsing template:", err)
}
// Open the output file for writing
f, err := os.Create(outputPath)
defer f.Close()
if err != nil {
panic(err)
}
// Write the template with the given view.
err = t.Execute(f, view)
if err != nil {
panic(err)
}
}
func GoFmt(filePath string) {
cmd := exec.Command("gofmt", "-w", filePath)
var stdErr bytes.Buffer
cmd.Stderr = &stdErr
err := cmd.Run()
if err != nil {
log.Println("Error running gofmt:", err)
panic(stdErr.String())
}
}
func GoImports(filePath string) {
cmd := exec.Command("goimports", "-w", filePath)
var stdErr bytes.Buffer
cmd.Stderr = &stdErr
err := cmd.Run()
if err != nil {
log.Println("Error running goimports:", err)
panic(stdErr.String())
}
}