-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunction.go
125 lines (105 loc) · 2.32 KB
/
function.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
package jot
import (
"fmt"
"io"
"strings"
)
type FunctionSpec struct {
Doc string
Name string
Code []string
ReturnTypes []TypeSpec
Parameters []*ParameterSpec
}
type ParameterSpec struct {
Name string
Typ TypeSpec
}
func (s *ParameterSpec) Write(w io.Writer) error {
io.WriteString(w, fmt.Sprintf("%s ", s.Name))
s.Typ.Write(w)
return nil
}
func Function(name string) *FunctionSpec {
return &FunctionSpec{Name: name}
}
func (s *FunctionSpec) SetDoc(doc string) *FunctionSpec {
s.Doc = doc
return s
}
func (s *FunctionSpec) AddCode(code string) *FunctionSpec {
s.Code = append(s.Code, code)
return s
}
func (s *FunctionSpec) AddCodeFmt(code string, args ...interface{}) *FunctionSpec {
for i, arg := range args {
code = strings.Replace(code, fmt.Sprintf("{%d}", i), fmt.Sprint(arg), -1)
}
s.AddCode(code)
return s
}
func (s *FunctionSpec) AddParameter(name string, typ TypeSpec) *FunctionSpec {
s.Parameters = append(s.Parameters, &ParameterSpec{Name: name, Typ: typ})
return s
}
func (s *FunctionSpec) AddReturnType(typ TypeSpec) *FunctionSpec {
if typ == nil {
panic("nil typ")
}
s.ReturnTypes = append(s.ReturnTypes, typ)
return s
}
func (s *FunctionSpec) Write(w io.Writer) error {
WriteDoc(w, s.Doc)
io.WriteString(w, fmt.Sprintf("func %s(", s.Name))
s.writeParameters(w)
io.WriteString(w, ")")
s.writeReturnTypes(w)
io.WriteString(w, " {")
io.WriteString(w, "\n")
s.writeCode(w)
io.WriteString(w, "}")
io.WriteString(w, "\n")
return nil
}
func (s *FunctionSpec) writeCode(w io.Writer) error {
for _, c := range s.Code {
io.WriteString(w, c)
io.WriteString(w, "\n")
}
return nil
}
func (s *FunctionSpec) writeSignature(w io.Writer) error {
io.WriteString(w, fmt.Sprintf("%s(", s.Name))
s.writeParameters(w)
io.WriteString(w, ")")
s.writeReturnTypes(w)
return nil
}
func (s *FunctionSpec) writeParameters(w io.Writer) error {
for i, p := range s.Parameters {
if i > 0 {
io.WriteString(w, ", ")
}
p.Write(w)
}
return nil
}
func (g *FunctionSpec) writeReturnTypes(w io.Writer) error {
if len(g.ReturnTypes) > 0 {
io.WriteString(w, " ")
}
if len(g.ReturnTypes) > 1 {
io.WriteString(w, "(")
}
for i, r := range g.ReturnTypes {
if i > 0 {
io.WriteString(w, ", ")
}
r.Write(w)
}
if len(g.ReturnTypes) > 1 {
io.WriteString(w, ")")
}
return nil
}