@@ -16,7 +16,6 @@ type templateContext struct {
16
16
Len int
17
17
TypeName string
18
18
TypeDecl string
19
- GenericTypesDecl string
20
19
GenericTypesForward string
21
20
}
22
21
@@ -27,6 +26,23 @@ var funcMap = template.FuncMap{
27
26
"quote" : func (value interface {}) string {
28
27
return fmt .Sprintf ("%q" , fmt .Sprint (value ))
29
28
},
29
+ "inc" : func (value int ) int {
30
+ return value + 1
31
+ },
32
+ "typeRef" : func (indexes []int , suffix ... string ) string {
33
+ if len (suffix ) > 1 {
34
+ panic (fmt .Errorf ("typeRef accepts at most 1 suffix argument" ))
35
+ }
36
+
37
+ var typeNameSuffix string
38
+ if len (suffix ) == 1 {
39
+ typeNameSuffix = suffix [0 ]
40
+ }
41
+
42
+ return fmt .Sprintf ("T%d%s[%s]" , len (indexes ), typeNameSuffix , genTypesForward (indexes ))
43
+ },
44
+ "genericTypesDecl" : genTypesDecl ,
45
+ "genericTypesDeclGenericConstraint" : genTypesDeclGenericConstraint ,
30
46
}
31
47
32
48
//go:embed tuple.tpl
@@ -55,15 +71,10 @@ func main() {
55
71
indexes [index ] = index + 1
56
72
}
57
73
58
- decl := genTypesDecl (indexes )
59
- forward := genTypesForward (indexes )
60
74
context := templateContext {
61
75
Indexes : indexes ,
62
76
Len : tupleLength ,
63
- TypeName : fmt .Sprintf ("T%d[%s]" , tupleLength , forward ),
64
- TypeDecl : fmt .Sprintf ("T%d[%s]" , tupleLength , decl ),
65
- GenericTypesDecl : decl ,
66
- GenericTypesForward : forward ,
77
+ GenericTypesForward : genTypesForward (indexes ),
67
78
}
68
79
69
80
filesToGenerate := []struct {
@@ -112,18 +123,25 @@ func generateFile(context templateContext, outputFilePath string, tpl *template.
112
123
}
113
124
}
114
125
126
+ func genTypesDeclGenericConstraint (indexes []int , constraint string ) string {
127
+ sep := make ([]string , len (indexes ))
128
+ for index , typeIndex := range indexes {
129
+ typ := fmt .Sprintf ("Ty%d" , typeIndex )
130
+ sep [index ] = fmt .Sprintf ("%s %s[%s]" , typ , constraint , typ )
131
+ }
132
+
133
+ return strings .Join (sep , ", " )
134
+ }
135
+
115
136
// genTypesDecl generates a "TypeParamDecl" (https://tip.golang.org/ref/spec#Type_parameter_lists) expression,
116
137
// used to declare generic types for a type or a function, according to the given element indexes.
117
- func genTypesDecl (indexes []int ) string {
138
+ func genTypesDecl (indexes []int , constraint string ) string {
118
139
sep := make ([]string , len (indexes ))
119
140
for index , typeIndex := range indexes {
120
141
sep [index ] = fmt .Sprintf ("Ty%d" , typeIndex )
121
142
}
122
143
123
- // Add constraint to last element.
124
- sep [len (indexes )- 1 ] += " any"
125
-
126
- return strings .Join (sep , ", " )
144
+ return strings .Join (sep , ", " ) + " " + constraint
127
145
}
128
146
129
147
// genTypesForward generates a "TypeParamList" (https://tip.golang.org/ref/spec#Type_parameter_lists) expression,
0 commit comments