-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate_rest_tape.go
121 lines (108 loc) · 2.34 KB
/
generate_rest_tape.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
//go:build ignore
// +build ignore
package main
import (
"io/ioutil"
"reflect"
"strings"
"github.com/Postcord/rest"
)
const start = `// Code generated by generate_rest_tape.go; DO NOT EDIT.
package router
//go:generate go run generate_rest_tape.go
import (
"context"
"image"
"github.com/Postcord/objects"
"github.com/Postcord/rest"
)
type restTape struct {
tape *tape
rest rest.RESTClient
}
`
func strbool(b bool) string {
if b {
return "true"
}
return "false"
}
func generateRestFunctions() string {
letters := []string{"", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j"}
t := reflect.TypeOf((*rest.Client)(nil))
methodNum := t.NumMethod()
funcs := make([]string, methodNum)
for i := 0; i < methodNum; i++ {
method := t.Method(i)
f := "func (r restTape) " + method.Name + "("
params := ""
inNum := method.Type.NumIn()
for j := 1; j < inNum; j++ {
if j > 1 {
f += ", "
params += ", "
}
fVard := ""
inStr := method.Type.In(j).String()
vard := method.Type.IsVariadic() && j == inNum-1
if vard {
fVard = "..."
inStr = inStr[2:]
}
f += letters[j] + " " + fVard + inStr
params += letters[j]
if vard {
params += "..."
}
}
tapeParams := params
if strings.HasSuffix(params, "...") {
tapeParams = params[:len(params)-3]
}
f += ")"
numOut := method.Type.NumOut()
startCallSep := ", "
if inNum == 1 {
startCallSep = ""
}
outCall := "x := "
inCall := "x"
switch numOut {
case 0:
startCallSep = ""
outCall = ""
case 1:
f += " " + method.Type.Out(0).String()
default:
f += " ("
retOutputs := make([]string, numOut)
for j := 0; j < numOut; j++ {
if j > 0 {
f += ", "
}
f += method.Type.Out(j).String()
retOutputs[j] = letters[j+inNum]
}
inCall = strings.Join(retOutputs, ", ")
outCall = inCall + " := "
f += ")"
}
retCall := ""
if inCall != "" {
retCall = "return " + inCall
}
f += ` {
result := r.tape.write("` + method.Name + `", ` + strbool(method.Type.IsVariadic()) + startCallSep + tapeParams + `)
` + outCall + "r.rest." + method.Name + `(` + params + `)
result.end(` + inCall + `)
` + retCall + `
}`
funcs[i] = f
}
return start + strings.Join(funcs, "\n\n") + "\n"
}
func main() {
if err := ioutil.WriteFile("rest_tape_gen.go", []byte(generateRestFunctions()), 0666); err != nil {
panic(err)
}
}