File: gen-opcodes.go

package info (click to toggle)
delve 1.24.0-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 14,092 kB
  • sloc: ansic: 111,943; sh: 169; asm: 141; makefile: 43; python: 23
file content (106 lines) | stat: -rw-r--r-- 2,115 bytes parent folder | download
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
//go:build ignore

package main

import (
	"bufio"
	"bytes"
	"fmt"
	"go/format"
	"log"
	"os"
	"strings"
)

type Opcode struct {
	Name string
	Code string
	Args string
	Func string
}

func usage() {
	os.Stderr.WriteString("gen-opcodes <opcodes-table-path> <opcodes-destination-path>\n\n")
	os.Stderr.WriteString("Generates Go file <opcodes-destination-path> from the table file <opcodes-table-path>.\n\n")
	os.Exit(1)
}

func main() {
	if len(os.Args) != 3 {
		usage()
	}

	fh, err := os.Open(os.Args[1])
	if err != nil {
		log.Fatal(err)
	}
	defer fh.Close()

	outfh := os.Stdout
	if os.Args[2] != "-" {
		outfh, err = os.Create(os.Args[2])
		if err != nil {
			log.Fatal(err)
		}
		defer outfh.Close()
	}

	opcodes := []Opcode{}
	s := bufio.NewScanner(fh)
	for s.Scan() {
		line := strings.TrimSpace(s.Text())
		if line == "" || strings.HasPrefix(line, "//") {
			continue
		}
		fields := strings.Split(line, "\t")
		opcode := Opcode{Name: fields[0], Code: fields[1], Args: fields[2]}
		if len(fields) > 3 {
			opcode.Func = fields[3]
		}
		opcodes = append(opcodes, opcode)
	}

	var buf bytes.Buffer

	fmt.Fprintf(&buf, `// Code generated by gen-opcodes. DO NOT EDIT.
// Edit opcodes.table instead.

package op
`)

	// constants
	fmt.Fprintf(&buf, "const (\n")
	for _, opcode := range opcodes {
		fmt.Fprintf(&buf, "%s Opcode = %s\n", opcode.Name, opcode.Code)
	}
	fmt.Fprintf(&buf, ")\n\n")

	// name map
	fmt.Fprintf(&buf, "var opcodeName = map[Opcode]string{\n")
	for _, opcode := range opcodes {
		fmt.Fprintf(&buf, "%s: %q,\n", opcode.Name, opcode.Name)
	}
	fmt.Fprintf(&buf, "}\n")

	// arguments map
	fmt.Fprintf(&buf, "var opcodeArgs = map[Opcode]string{\n")
	for _, opcode := range opcodes {
		fmt.Fprintf(&buf, "%s: %s,\n", opcode.Name, opcode.Args)
	}
	fmt.Fprintf(&buf, "}\n")

	// function map
	fmt.Fprintf(&buf, "var oplut = map[Opcode]stackfn{\n")
	for _, opcode := range opcodes {
		if opcode.Func != "" {
			fmt.Fprintf(&buf, "%s: %s,\n", opcode.Name, opcode.Func)
		}
	}
	fmt.Fprintf(&buf, "}\n")

	src, err := format.Source(buf.Bytes())
	if err != nil {
		log.Fatal(err)
	}
	outfh.Write(src)
}