~moody/ninep

ref: d394458419b1bc3ea43eb8426ccecfc427352ab9 ninep/genproto.go -rw-r--r-- 10.8 KiB
d3944584 — Jacob Moody Rework api 3 months ago
                                                                                
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
// +build ignore

package main

import (
	"bytes"
	"fmt"
	"go/format"
	"log"
	"os"
	"strconv"
	"strings"
	"text/template"
)

var proto = []string{
	"Tversion msize[4] version[s]",
	"Rversion msize[4] version[s]",
	"Tauth afid[4] uname[s] aname[s]",
	"Rauth Qid",
	"Tflush oldtag[2]",
	"Rflush",
	"Tattach fid[4] afid[4] uname[s] aname[s]",
	"Rattach Qid",
	"Twalk fid[4] newfid[4] names{2}",
	"Rwalk qid{2}",
	"Topen fid[4] mode[1]",
	"Ropen Qid iounit[4]",
	"Tcreate fid[4] name[s] perm[4] mode[1]",
	"Rcreate Qid iounit[4]",
	"Tread fid[4] offset[8] count[4]",
	"Rread data{4}",
	"Twrite fid[4] offset[8] data{4}",
	"Rwrite count[4]",
	"Tclunk fid[4]",
	"Rclunk",
	"Tremove fid[4]",
	"Rremove",
	"Tstat fid[4]",
	"Rstat Dir",
	"Twstat fid[4] Dir",
	"Rwstat",
	"Rerror ename[s]",
}

const (
	strT = iota
	intT
	sliceT
	dirT
	qidT
	byteT
)

type mem struct {
	t    byte
	Name string
	size int
}

func newMem(s string) mem {
	switch s {
	case "Dir":
		return mem{dirT, "Dir", 0}
	case "Qid":
		return mem{qidT, "Qid", 13}
	}
	if !strings.Contains(s, "fid") {
		s = strings.Title(s)
	}
	if s := strings.Split(s, "["); len(s) != 1 {
		switch s[1][0] {
		case 's', 'S':
			return mem{strT, s[0], 0}
		case '2', '4', '8':
			n, err := strconv.Atoi(s[1][:1])
			if err != nil {
				panic(err)
			}
			return mem{intT, s[0], n}
		case '1':
			return mem{byteT, s[0], 1}
		default:
			panic(s[1])
		}
	}
	if s := strings.Split(s, "{"); len(s) != 1 {
		n, err := strconv.Atoi(s[1][:1])
		if err != nil {
			panic(err)
		}
		return mem{sliceT, s[0], n}
	}
	panic("??")
}

func (m *mem) Size(recv string) string {
	switch m.t {
	case byteT:
		return "1"
	case intT:
		return fmt.Sprintf("%d", m.size)
	case strT:
		return fmt.Sprintf("2 + len(%s.%s)", recv, m.Name)
	case sliceT:
		switch m.Name {
		case "data", "Data":
			return fmt.Sprintf("%d + len(%s.%s)", m.size, recv, m.Name)
		case "qid", "Qid":
			return fmt.Sprintf("%d + len(%s.%s)*13", m.size, recv, m.Name)
		}
	case dirT:
		return fmt.Sprintf("2 + %s.Dir.size()", recv)
	case qidT:
		return fmt.Sprintf("%s.Qid.size()", recv)
	}
	panic("missing case")
}

func (m *mem) Encode(recv string, off int) (string, int) {
	switch m.t {
	case strT:
		return fmt.Sprintf("n = putStr(b, %s.%s)\nb = b[n:]", recv, m.Name), -1
	case byteT:
		return fmt.Sprintf("b[%d] = %s.%s", off, recv, m.Name), 1
	case intT:
		switch m.size {
		case 2:
			return fmt.Sprintf("binary.LittleEndian.PutUint16(b[%d:], %s.%s)", off, recv, m.Name), 2
		case 4:
			return fmt.Sprintf("binary.LittleEndian.PutUint32(b[%d:], %s.%s)", off, recv, m.Name), 4
		case 8:
			return fmt.Sprintf("binary.LittleEndian.PutUint64(b[%d:], %s.%s)", off, recv, m.Name), 8
		}
	case dirT:
		s := &strings.Builder{}
		s.WriteString(fmt.Sprintf("binary.LittleEndian.PutUint16(b[%d:], uint16(%s.Dir.size()))\n", off, recv))
		s.WriteString(fmt.Sprintf("%s.Dir.encode(b[%d:])", recv, off+2))
		return s.String(), -1
	case qidT:
		return fmt.Sprintf("%s.Qid.encode(b[%d:])", recv, off), 13
	case sliceT:
		s := &strings.Builder{}
		switch m.size {
		case 2:
			s.WriteString(fmt.Sprintf("binary.LittleEndian.PutUint16(b[%d:], uint16(len(%s.%s)))", off, recv, m.Name))
		case 4:
			s.WriteString(fmt.Sprintf("binary.LittleEndian.PutUint32(b[%d:], uint32(len(%s.%s)))", off, recv, m.Name))
		}
		switch m.Name {
		case "data", "Data":
			s.WriteString(fmt.Sprintf("\ncopy(b[%d:], %s.%s)", off+m.size, recv, m.Name))
			return s.String(), -1
		case "qid", "Qid":
			s.WriteString(fmt.Sprintf("\noff := %d\n", off+m.size))
			s.WriteString(fmt.Sprintf("for i := range %s.%s {\n %s.%s[i].encode(b[off:])\n off += 13\n }", recv, m.Name, recv, m.Name))
			return s.String(), -1
		case "names", "Names":
			s.WriteString(fmt.Sprintf("\noff := %d\n", off+m.size))
			s.WriteString(fmt.Sprintf("for i := range %s.%s {\n off += putStr(b[off:], %s.%s[i])\n }", recv, m.Name, recv, m.Name))
			return s.String(), -1
		}
	}
	panic("missing case")
}

func (m *mem) Decode(recv string, off int) (string, int) {
	switch m.t {
	case strT:
		return fmt.Sprintf("n, %s.%s = getStr(b)\nb = b[n:]", recv, m.Name), -1
	case byteT:
		return fmt.Sprintf("%s.%s = b[%d]", recv, m.Name, off), 1
	case intT:
		switch m.size {
		case 2:
			return fmt.Sprintf("%s.%s = binary.LittleEndian.Uint16(b[%d:])", recv, m.Name, off), 2
		case 4:
			return fmt.Sprintf("%s.%s = binary.LittleEndian.Uint32(b[%d:])", recv, m.Name, off), 4
		case 8:
			return fmt.Sprintf("%s.%s = binary.LittleEndian.Uint64(b[%d:])", recv, m.Name, off), 8
		}
	case dirT:
		return fmt.Sprintf("%s.Dir.decode(b[%d:])", recv, off+2), -1
	case qidT:
		return fmt.Sprintf("%s.Qid.decode(b[%d:])", recv, off), -1
	case sliceT:
		if m.Name == "Data" {
			return fmt.Sprintf("%s.%s = b[%d:]", recv, m.Name, off+m.size), -1
		}
		s := &strings.Builder{}
		switch m.size {
		case 2:
			s.WriteString(fmt.Sprintf("s := binary.LittleEndian.Uint16(b[%d:])\n", off))
		case 4:
			s.WriteString(fmt.Sprintf("s := binary.LittleEndian.Uint16(b[%d:])\n", off))
		}
		switch m.Name {
		case "qid", "Qid":
			s.WriteString(fmt.Sprintf("\n%s.%s = make([]Qid, s)\noff := %d\n", recv, m.Name, off+m.size))
			s.WriteString(fmt.Sprintf("for i := range %s.%s {\n %s.%s[i].decode(b[off:])\n off += 13\n }", recv, m.Name, recv, m.Name))
			return s.String(), -1
		case "names", "Names":
			s.WriteString(fmt.Sprintf("\n%s.%s = make([]string, s)\n n := 0\noff := %d\n", recv, m.Name, off+m.size))
			s.WriteString(fmt.Sprintf("for i := range %s.%s {\n n, %s.%s[i] = getStr(b[off:])\noff += n\n }", recv, m.Name, recv, m.Name))
			return s.String(), -1
		}
	}
	panic("missing case")
}

func (m *mem) Decl() string {
	out := m.Name
	switch m.t {
	case byteT:
		return out + " byte"
	case intT:
		switch m.size {
		case 2:
			return out + " uint16"
		case 4:
			return out + " uint32"
		case 8:
			return out + " uint64"
		}
	case strT:
		return out + " string"
	case sliceT:
		switch m.Name {
		case "qid", "Qid":
			return out + " []Qid"
		case "names", "Names":
			return out + " []string"
		}
		return out + " []byte"
	case dirT:
		return "*Dir"
	case qidT:
		return "*Qid"
	}
	panic("missing case")
}

type msg struct {
	Name     string
	Typ      string
	Recv     string
	Mems     []mem
	RespMems []mem
}

func (m *msg) IsT() bool {
	return m.Recv == "t"
}

func (m *msg) Resp() string {
	switch m.Name[0] {
	case 'T':
		return "_R" + m.Name[1:]
	case '_':
		return "_R" + m.Name[2:]
	}
	panic("missing case")
}

func (m *msg) ParseResp(mem []string) {
	for _, e := range mem {
		me := newMem(e)
		me.Name = strings.ToLower(me.Name)
		m.RespMems = append(m.RespMems, me)
	}
}

func (m *msg) RespArgs() string {
	s := &strings.Builder{}
	for _, e := range m.RespMems {
		decl := e.Decl()
		switch decl {
		case "*Qid":
			decl = "qid *Qid"
		case "*Dir":
			decl = "dir *Dir"
		}
		s.WriteString(fmt.Sprintf("%s,", decl))
	}
	ss := s.String()
	if len(m.RespMems) > 1 {
		ss = ss[:len(ss)-1]
	}
	return ss
}

func (m *msg) NewResp() string {
	s := strings.Builder{}
	s.WriteString("&")
	s.WriteString(m.Resp())
	s.WriteString("{")
	s.WriteString("t.tg,")
	for i, e := range m.RespMems {
		s.WriteString(e.Name)
		if i != len(m.RespMems)-1 {
			s.WriteString(", ")
		}
	}
	s.WriteString("}")
	return s.String()
}

func newMsg(s string, mem []string) *msg {
	typ := strings.ToLower(s)
	if s[0] == 'R' || strings.Contains(s, "walk") || strings.Contains(s, "flush") || strings.Contains(s, "version") {
		s = "_" + s
	}
	m := &msg{Name: s, Typ: typ, Recv: typ[:1]}
	for _, e := range mem {
		m.Mems = append(m.Mems, newMem(e))
	}
	return m
}

func (m *msg) Encode() string {
	s := &strings.Builder{}
	off := 0
	haveNDecl := false
	for _, e := range m.Mems {
		if e.t == strT && !haveNDecl {
			s.WriteString(fmt.Sprintf("var n int\n b = b[%d:]\n", off))
			haveNDecl = true
		}
		en, n := e.Encode(m.Recv, off)
		if n != -1 {
			off += n
		}
		s.WriteString(en + "\n")
		if e.t == strT {
			off = 0
		}
	}
	return s.String()
}

func (m *msg) Decode() string {
	s := &strings.Builder{}
	off := 0
	haveNDecl := false
	for _, e := range m.Mems {
		if e.t == strT && !haveNDecl {
			s.WriteString(fmt.Sprintf("var n int\n b = b[%d:]\n", off))
			haveNDecl = true
		}
		en, n := e.Decode(m.Recv, off)
		if n != -1 {
			off += n
		}
		s.WriteString(en + "\n")
		if e.t == strT {
			off = 0
		}
	}
	return s.String()
}

func (m *msg) Size() string {
	//one off edge case for complex size calculations
	if m.Typ == "twalk" {
		return `
s := 4 + 4 + 2
for i := range t.Names {
	s += 2 + len(t.Names[i])
}
return s`
	}
	s := &strings.Builder{}
	s.WriteString("return ")
	if len(m.Mems) == 0 {
		s.WriteString("0")
		return s.String()
	}
	for _, e := range m.Mems {
		s.WriteString(e.Size(m.Recv))
		s.WriteRune('+')
	}
	ss := s.String()
	return ss[:len(ss)-1]
}

func (m *msg) Print() string {
	s := &strings.Builder{}
	name := m.Name
	if name[0] == '_' {
		name = name[1:]
	}
	s.WriteString(`return fmt.Sprintf("`)
	if len(m.Mems) == 0 {
		s.WriteString(fmt.Sprintf(`%s{tag: %%v}", %s.tg)`, name, m.Recv))
		return s.String()
	}
	s.WriteString(name + "{tag: %v, ")
	for i, e := range m.Mems {
		if i == len(m.Mems)-1 {
			s.WriteString(fmt.Sprintf("%s: %%v}\"", e.Name))
			break
		}
		s.WriteString(fmt.Sprintf("%s: %%v, ", e.Name))
	}
	s.WriteString(fmt.Sprintf(", %s.tg", m.Recv))
	for _, e := range m.Mems {
		s.WriteString(fmt.Sprintf(", %s.%s", m.Recv, e.Name))
	}
	s.WriteString(")")
	return s.String()
}

const structempl = `
type {{.Name}} struct {
	tg uint16
	{{if .IsT}}rf respFunc{{end}}
	{{range .Mems}}
	{{.Decl}}{{end}}
}
{{if .IsT}}
func ({{.Recv}} *{{.Name}}) Respond({{.RespArgs}}) {
	t.rf(t, {{.NewResp}}, "")
}

func ({{.Recv}} *{{.Name}}) Err(err error) {
	t.rf(t, nil, err.Error())
}

func ({{.Recv}} *{{.Name}}) StrErr(err string) {
	t.rf(t, nil, err)
}
{{end}}
func ({{.Recv}} *{{.Name}}) size() int { {{.Size}} }
func ({{.Recv}} *{{.Name}}) typ() byte { return {{.Typ}} }
func ({{.Recv}} *{{.Name}}) tag() uint16 { return {{.Recv}}.tg }

func ({{.Recv}} *{{.Name}}) encode(b []byte) {
	{{.Encode}}}
func ({{.Recv}} *{{.Name}}) decode(b []byte) {
	{{.Decode}}}

func ({{.Recv}} *{{.Name}}) String() string {
	{{.Print}}
}
`

var tmpl = template.Must(template.New("struct").Parse(structempl))

func main() {
	b := &bytes.Buffer{}
	fmt.Fprintln(b, "package ninep\n")
	fmt.Fprintln(b, "//This file is autogenerated by genproto.go -- DO NOT EDIT\n")
	fmt.Fprintln(b, `import "encoding/binary"`)
	fmt.Fprintln(b, `import "fmt"`+"\n")
	var lastMesg *msg
	for _, m := range proto {
		s := strings.Fields(m)
		me := newMsg(s[0], s[1:])
		if me.Typ == "rerror" {
			goto gen
		}
		if me.Typ[0] == 'r' {
			lastMesg.ParseResp(s[1:])
			err := tmpl.Execute(b, lastMesg)
			if err != nil {
				log.Fatal(err)
			}
		} else if me.Typ[0] == 't' {
			lastMesg = me
			continue
		}
	gen:
		err := tmpl.Execute(b, me)
		if err != nil {
			log.Fatal(err)
		}
	}
	buf, err := format.Source(b.Bytes())
	if err != nil {
		fmt.Println(string(b.Bytes()))
		log.Fatal(err)
	}
	f, err := os.Create("proto.go")
	if err != nil {
		log.Fatal(err)
	}
	f.Write(buf)
	f.Close()
}