/
walk.go
264 lines (228 loc) · 6.01 KB
/
walk.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
package schema
import (
"fmt"
"reflect"
"strconv"
"strings"
"github.com/consensys/gnark/frontend/schema/internal/reflectwalk"
)
// Walk walks through the provided object and stops when it encounters objects of type tLeaf
//
// It returns the number of secret and public leafs encountered during the walk.
func Walk(circuit interface{}, tLeaf reflect.Type, handler LeafHandler) (count LeafCount, err error) {
w := walker{
target: tLeaf,
targetSlice: reflect.SliceOf(tLeaf),
handler: handler,
}
err = reflectwalk.Walk(circuit, &w)
if err == reflectwalk.ErrSkipEntry {
err = nil
}
count.Public = w.nbPublic
count.Secret = w.nbSecret
return
}
// walker implements the interfaces defined in internal/reflectwalk
//
// for example;
//
// StructWalker is an interface that has methods that are called for
// structs when a Walk is done.
// type StructWalker interface {
// Struct(reflect.Value) error
// StructField(reflect.StructField, reflect.Value) error
// }
type walker struct {
handler LeafHandler
target reflect.Type
targetSlice reflect.Type
path pathStack
nbPublic, nbSecret int
}
// Interface handles interface values as they are encountered during the walk.
// That's where we handle leaves.
func (w *walker) Interface(value reflect.Value) error {
if value.Type() != w.target {
// keep walking.
return nil
}
v := w.visibility()
if v == Unset {
v = Secret
}
// call the handler.
if w.handler != nil {
if err := w.handler(LeafInfo{Visibility: v, FullName: w.name, name: ""}, value); err != nil {
return err
}
}
if v == Secret {
w.nbSecret++
} else if v == Public {
w.nbPublic++
}
// we return SkipEntry here; the walk will not explore further this object (indirections, ...)
return reflectwalk.ErrSkipEntry
}
func (w *walker) Pointer(value reflect.Value) error {
return w.Interface(value)
}
// Slice handles slice elements found within complex structures.
func (w *walker) Slice(value reflect.Value) error {
if value.Type() == w.targetSlice {
if value.Len() == 0 {
fmt.Printf("ignoring uninitialized slice: %s %s\n", w.name(), reflect.SliceOf(w.target).String())
return nil
}
return w.handleLeaves(value)
}
return nil
}
func (w *walker) SliceElem(index int, _ reflect.Value) error {
w.path.push(LeafInfo{Visibility: w.visibility(), name: strconv.Itoa(index)})
return nil
}
// Array handles array elements found within complex structures.
func (w *walker) Array(value reflect.Value) error {
if value.Type() == reflect.ArrayOf(value.Len(), w.target) {
return w.handleLeaves(value)
}
return nil
}
func (w *walker) ArrayElem(index int, _ reflect.Value) error {
w.path.push(LeafInfo{Visibility: w.visibility(), name: strconv.Itoa(index)})
return nil
}
// process an array or slice of leaves; since it's quite common to have large array/slices
// of frontend.Variable, this speeds up considerably performance.
func (w *walker) handleLeaves(value reflect.Value) error {
v := w.visibility()
if v == Unset {
v = Secret
}
// call the handler.
if w.handler != nil {
n := w.name()
for i := 0; i < value.Len(); i++ {
fName := func() string {
return n + "_" + strconv.Itoa(i)
}
vv := value.Index(i)
if err := w.handler(LeafInfo{Visibility: v, FullName: fName, name: ""}, vv); err != nil {
return err
}
}
}
if v == Secret {
w.nbSecret += value.Len()
} else if v == Public {
w.nbPublic += value.Len()
}
return reflectwalk.ErrSkipEntry
}
func (w *walker) Struct(reflect.Value) error {
return nil
}
func (w *walker) StructField(sf reflect.StructField, v reflect.Value) error {
// check if the gnark tag is set
tag, ok := sf.Tag.Lookup(string(tagKey))
if ok && tag == string(TagOptOmit) {
return reflectwalk.ErrSkipEntry // skipping "-"
}
if v.CanAddr() && v.Addr().CanInterface() {
// TODO @gbotrel don't like that hook, undesirable side effects
// will be hard to detect; (for example calling Parse multiple times will init multiple times!)
value := v.Addr().Interface()
if ih, hasInitHook := value.(InitHook); hasInitHook {
ih.GnarkInitHook()
}
}
// default visibility: parent (or unset)
parentVisibility := w.visibility()
info := LeafInfo{
name: sf.Name,
Visibility: parentVisibility,
}
var nameInTag string
if ok && tag != "" {
// gnark tag is set
var opts tagOptions
nameInTag, opts = parseTag(tag)
if !isValidTag(nameInTag) {
nameInTag = ""
}
if nameInTag != "" {
info.name = nameInTag
}
opts = tagOptions(strings.TrimSpace(string(opts)))
switch {
case opts.contains(TagOptSecret):
info.Visibility = Secret
case opts.contains(TagOptPublic):
info.Visibility = Public
}
}
if parentVisibility != Unset && parentVisibility != info.Visibility {
parentName := w.name()
if parentName == "" {
parentName = info.name
} else {
parentName += "_" + info.name
}
return fmt.Errorf("conflicting visibility. %s (%s) has a parent with different visibility attribute", parentName, info.Visibility.String())
}
w.path.push(info)
return nil
}
func (w *walker) Enter(l reflectwalk.Location) error {
return nil
}
func (w *walker) Exit(l reflectwalk.Location) error {
if l == reflectwalk.StructField || l == reflectwalk.ArrayElem || l == reflectwalk.SliceElem {
w.path.pop()
}
return nil
}
// defaults to unset
func (w *walker) visibility() Visibility {
if !w.path.isEmpty() {
return w.path.top().Visibility
}
return Unset
}
func (w *walker) name() string {
if w.path.isEmpty() {
return ""
}
var sbb strings.Builder
sbb.Grow(w.path.len() * 10)
first := true
for i := 0; i < w.path.len(); i++ {
if !first {
sbb.WriteByte('_')
} else {
first = false
}
sbb.WriteString(w.path[i].name)
}
return sbb.String()
}
type pathStack []LeafInfo
func (s *pathStack) len() int {
return len(*s)
}
func (s *pathStack) isEmpty() bool {
return len(*s) == 0
}
func (s *pathStack) push(l LeafInfo) {
*s = append(*s, l)
}
func (s *pathStack) pop() {
if !s.isEmpty() {
*s = (*s)[:len(*s)-1]
}
}
func (s *pathStack) top() LeafInfo {
return (*s)[len(*s)-1]
}