-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
simplePredicates_generate.go
140 lines (123 loc) · 2.37 KB
/
simplePredicates_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
// +build ignore
package main
import (
"bytes"
"go/format"
"io"
"log"
"os"
"text/template"
)
type types struct {
BasicKinds []string
BasicProps []string
Types []string
}
func main() {
typesList := types{
BasicKinds: []string{
"Bool",
"Int",
"Int8",
"Int16",
"Int32",
"Int64",
"Uint",
"Uint8",
"Uint16",
"Uint32",
"Uint64",
"Uintptr",
"Float32",
"Float64",
"Complex64",
"Complex128",
"String",
"UnsafePointer",
"UntypedBool",
"UntypedInt",
"UntypedRune",
"UntypedFloat",
"UntypedComplex",
"UntypedString",
"UntypedNil",
},
BasicProps: []string{
"Boolean",
"Integer",
"Unsigned",
"Float",
"Complex",
"String",
"Untyped",
"Ordered",
"Numeric",
"ConstType",
},
Types: []string{
"Basic",
"Array",
"Slice",
"Struct",
"Pointer",
"Tuple",
"Signature",
"Interface",
"Map",
"Chan",
"Named",
},
}
simplePredicateFile, err := os.Create("simplePredicates.go")
if err != nil {
log.Fatal(err)
}
writeCode(simplePredicateFile, typesList)
}
func generateCode(tmplText string, typeList types) []byte {
tmpl := template.Must(template.New("code").Parse(tmplText))
var code bytes.Buffer
tmpl.Execute(&code, typeList)
prettyCode, err := format.Source(code.Bytes())
if err != nil {
panic(err)
}
return prettyCode
}
func writeCode(output io.Writer, typeList types) {
code := generateCode(`// Code generated by simplePredicates_generate.go; DO NOT EDIT
package typep
import (
"go/types"
)
// Simple 1-to-1 type predicates via type assertion.
{{ range .Types }}
// Is{{.}} reports whether a given type has *types.{{.}} type.
func Is{{.}}(typ types.Type) bool {
_, ok := typ.(*types.{{.}})
return ok
}
{{ end }}
// *types.Basic predicates for the info field.
{{ range .BasicProps }}
// Has{{.}}Prop reports whether typ is a *types.Basic has Is{{.}} property.
func Has{{.}}Prop(typ types.Type) bool {
if typ, ok := typ.(*types.Basic); ok {
return typ.Info()&types.Is{{.}} != 0
}
return false
}
{{ end }}
// *types.Basic predicates for the kind field.
{{ range .BasicKinds }}
// Has{{.}}Kind reports whether typ is a *types.Basic with its kind set to types.{{.}}.
func Has{{.}}Kind(typ types.Type) bool {
if typ, ok := typ.(*types.Basic); ok {
return typ.Kind() == types.{{.}}
}
return false
}
{{ end }}
`, typeList)
output.Write(code)
}