| 1 |
|
| 2 |
|
| 3 |
package main |
| 4 |
|
| 5 |
import ( |
| 6 |
"bytes" |
| 7 |
"flag" |
| 8 |
"fmt" |
| 9 |
"go/format" |
| 10 |
"io" |
| 11 |
"log" |
| 12 |
"os" |
| 13 |
"path/filepath" |
| 14 |
"runtime" |
| 15 |
"strconv" |
| 16 |
) |
| 17 |
|
| 18 |
var output = flag.String("output", "", "path to output file (default stdout)") |
| 19 |
|
| 20 |
func PrintConstType(w io.Writer, name, typ, format string, size int, doc string) { |
| 21 |
r := typ[0] |
| 22 |
fmt.Fprintf(w, "// %s\n", doc) |
| 23 |
fmt.Fprintf(w, "type %s %s\n", name, typ) |
| 24 |
fmt.Fprintf(w, "\n") |
| 25 |
fmt.Fprintf(w, "func (%c %s) Asm() string { return fmt.Sprintf(\"$%s\", %c) }\n", r, name, format, r) |
| 26 |
fmt.Fprintf(w, "func (%c %s) Bytes() int { return %d }\n", r, name, size) |
| 27 |
fmt.Fprintf(w, "func (%c %s) constant() {}\n", r, name) |
| 28 |
fmt.Fprintf(w, "\n") |
| 29 |
} |
| 30 |
|
| 31 |
func PrintConstTypes(w io.Writer) { |
| 32 |
_, self, _, _ := runtime.Caller(0) |
| 33 |
fmt.Fprintf(w, "// Code generated by %s. DO NOT EDIT.\n\n", filepath.Base(self)) |
| 34 |
fmt.Fprintf(w, "package operand\n\n") |
| 35 |
fmt.Fprintf(w, "import \"fmt\"\n\n") |
| 36 |
for n := 1; n <= 8; n *= 2 { |
| 37 |
bits := n * 8 |
| 38 |
bs := strconv.Itoa(bits) |
| 39 |
|
| 40 |
if n >= 4 { |
| 41 |
|
| 42 |
PrintConstType(w, "F"+bs, "float"+bs, "(%s)", n, fmt.Sprintf("F%d is a %d-bit floating point constant.", bits, bits)) |
| 43 |
} |
| 44 |
PrintConstType(w, "I"+bs, "int"+bs, "%+d", n, fmt.Sprintf("I%d is a %d-bit signed integer constant.", bits, bits)) |
| 45 |
PrintConstType(w, "U"+bs, "uint"+bs, "%#0"+strconv.Itoa(2*n)+"x", n, fmt.Sprintf("U%d is a %d-bit unsigned integer constant.", bits, bits)) |
| 46 |
} |
| 47 |
} |
| 48 |
|
| 49 |
func main() { |
| 50 |
flag.Parse() |
| 51 |
|
| 52 |
w := os.Stdout |
| 53 |
if *output != "" { |
| 54 |
f, err := os.Create(*output) |
| 55 |
if err != nil { |
| 56 |
log.Fatal(err) |
| 57 |
} |
| 58 |
defer f.Close() |
| 59 |
w = f |
| 60 |
} |
| 61 |
|
| 62 |
buf := bytes.NewBuffer(nil) |
| 63 |
PrintConstTypes(buf) |
| 64 |
|
| 65 |
src, err := format.Source(buf.Bytes()) |
| 66 |
if err != nil { |
| 67 |
log.Fatal(err) |
| 68 |
} |
| 69 |
|
| 70 |
_, err = w.Write(src) |
| 71 |
if err != nil { |
| 72 |
log.Fatal(err) |
| 73 |
} |
| 74 |
} |