| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "fmt" |
| 6 | "go/format" |
| 7 | "io/ioutil" |
| 8 | "log" |
| 9 | "os" |
| 10 | "strings" |
| 11 | "text/template" |
| 12 | |
| 13 | "git.sr.ht/~sircmpwn/getopt" |
| 14 | |
| 15 | "git.sr.ht/~sircmpwn/go-bare/schema" |
| 16 | ) |
| 17 | |
| 18 | const templateString = ` |
| 19 | package {{.package}} |
| 20 | |
| 21 | // Code generated by go-bare/cmd/gen, DO NOT EDIT. |
| 22 | |
| 23 | import ( |
| 24 | {{- if .schema.NeedErrors }} |
| 25 | "errors" |
| 26 | {{- end }} |
| 27 | "git.sr.ht/~sircmpwn/go-bare" |
| 28 | ) |
| 29 | |
| 30 | {{ define "type" }} |
| 31 | {{- if eq (typeKind .) "PrimitiveType" -}} |
| 32 | {{ primitiveType .Kind }} |
| 33 | {{- else if eq (typeKind .) "DataType" -}} |
| 34 | [{{if gt .Length 0 }}{{.Length}}{{end}}]byte |
| 35 | {{- else if eq (typeKind .) "ArrayType" -}} |
| 36 | [{{if gt .Length 0 }}{{.Length}}{{end}}]{{template "type" .Member}} |
| 37 | {{- else if eq (typeKind .) "StructType" -}} |
| 38 | struct { |
| 39 | {{- range .Fields }} |
| 40 | {{ capitalize .Name }} {{ template "type" .Type }} {{ structTag .Name }} |
| 41 | {{- end -}} |
| 42 | } |
| 43 | {{- else if eq (typeKind .) "NamedUserType" -}} |
| 44 | {{.Name}} |
| 45 | {{- else if eq (typeKind .) "MapType" -}} |
| 46 | map[{{template "type" .Key}}]{{template "type" .Value}} |
| 47 | {{- else if eq (typeKind .) "OptionalType" -}} |
| 48 | *{{template "type" .Subtype}} |
| 49 | {{- end -}} |
| 50 | {{ end }} |
| 51 | |
| 52 | {{with .schema}} |
| 53 | |
| 54 | {{range .UserTypes}} |
| 55 | type {{ .Name }} {{ template "type" .Type }} |
| 56 | |
| 57 | func (t *{{ .Name }}) Decode(data []byte) error { |
| 58 | return bare.Unmarshal(data, t) |
| 59 | } |
| 60 | |
| 61 | func (t *{{ .Name }}) Encode() ([]byte, error) { |
| 62 | return bare.Marshal(t) |
| 63 | } |
| 64 | {{end}} |
| 65 | |
| 66 | {{range .Enums}} |
| 67 | type {{ .Name }} {{ primitiveType .Kind }} |
| 68 | |
| 69 | {{ $name := .Name }} |
| 70 | |
| 71 | const ( |
| 72 | {{- range $i, $el := .Values }} |
| 73 | {{ .Name }} {{ $name }} = {{ .Value }} |
| 74 | {{- end -}} |
| 75 | ) |
| 76 | |
| 77 | func (t {{ .Name }}) String() string { |
| 78 | switch (t) { |
| 79 | {{- range .Values }} |
| 80 | case {{ .Name }}: |
| 81 | return "{{ .Name }}" |
| 82 | {{- end -}} |
| 83 | } |
| 84 | panic(errors.New("Invalid {{.Name}} value")) |
| 85 | } |
| 86 | {{end}} |
| 87 | |
| 88 | {{ if gt (len .Unions) 0 }} |
| 89 | {{range .Unions}} |
| 90 | type {{ .Name }} interface { |
| 91 | bare.Union |
| 92 | } |
| 93 | {{end}} |
| 94 | |
| 95 | {{range .UnionMembers}} |
| 96 | func (_ {{.}}) IsUnion() {} |
| 97 | {{end}} |
| 98 | |
| 99 | func init() { |
| 100 | {{- range .Unions}} |
| 101 | bare.RegisterUnion((*{{.Name}})(nil)). |
| 102 | {{ $len := len .Type.Types }} |
| 103 | {{range $i, $el := .Type.Types}} |
| 104 | Member(*new({{ template "type" $el.Type}}), {{$el.Tag}}){{- if not (last $len $i) -}}.{{end}} |
| 105 | {{end}} |
| 106 | {{ end }} |
| 107 | } |
| 108 | {{ end}} |
| 109 | |
| 110 | {{end}} |
| 111 | ` |
| 112 | |
| 113 | var funcs = template.FuncMap{ |
| 114 | "typeKind": func(ty interface{}) string { |
| 115 | switch ty := ty.(type) { |
| 116 | case *schema.PrimitiveType: |
| 117 | return "PrimitiveType" |
| 118 | case *schema.DataType: |
| 119 | return "DataType" |
| 120 | case *schema.StructType: |
| 121 | return "StructType" |
| 122 | case *schema.NamedUserType: |
| 123 | return "NamedUserType" |
| 124 | case *schema.MapType: |
| 125 | return "MapType" |
| 126 | case *schema.ArrayType: |
| 127 | return "ArrayType" |
| 128 | case *schema.OptionalType: |
| 129 | return "OptionalType" |
| 130 | default: |
| 131 | panic(fmt.Sprintf("Unimplemented schema type: %T", ty)) |
| 132 | } |
| 133 | }, |
| 134 | "primitiveType": func(t schema.TypeKind) string { |
| 135 | switch t { |
| 136 | case schema.U8: |
| 137 | return "uint8" |
| 138 | case schema.U16: |
| 139 | return "uint16" |
| 140 | case schema.U32: |
| 141 | return "uint32" |
| 142 | case schema.U64: |
| 143 | return "uint64" |
| 144 | case schema.UINT: |
| 145 | return "uint" |
| 146 | case schema.I8: |
| 147 | return "int8" |
| 148 | case schema.I16: |
| 149 | return "int16" |
| 150 | case schema.I32: |
| 151 | return "int32" |
| 152 | case schema.I64: |
| 153 | return "int64" |
| 154 | case schema.INT: |
| 155 | return "int" |
| 156 | case schema.F32: |
| 157 | return "float32" |
| 158 | case schema.F64: |
| 159 | return "float64" |
| 160 | case schema.Bool: |
| 161 | return "bool" |
| 162 | case schema.String: |
| 163 | return "string" |
| 164 | case schema.Void: |
| 165 | return "struct{}" |
| 166 | } |
| 167 | panic(fmt.Errorf("Invalid primitive type %d", t)) |
| 168 | }, |
| 169 | "structTag": func(name string) string { |
| 170 | return fmt.Sprintf("`bare:\"%s\"`", name) |
| 171 | }, |
| 172 | "capitalize": func(s string) string { |
| 173 | return strings.ToUpper(s[:1]) + s[1:] |
| 174 | }, |
| 175 | "last": func(len, i int) bool { |
| 176 | return i+1 == len |
| 177 | }, |
| 178 | } |
| 179 | |
| 180 | func main() { |
| 181 | cfg := parseArgs() |
| 182 | out := &bytes.Buffer{} |
| 183 | |
| 184 | tmpl, err := template.New("").Funcs(funcs).Parse(templateString) |
| 185 | if err != nil { |
| 186 | log.Fatalf("error parsing template: %v", err) |
| 187 | } |
| 188 | |
| 189 | types := parseSchema(cfg.In, cfg.Skip) |
| 190 | |
| 191 | data := make(map[string]interface{}) |
| 192 | |
| 193 | data["package"] = cfg.PackageName |
| 194 | data["schema"] = types |
| 195 | |
| 196 | err = tmpl.Execute(out, data) |
| 197 | if err != nil { |
| 198 | log.Fatalf("error executing template: %v", err) |
| 199 | } |
| 200 | |
| 201 | // Format generated code |
| 202 | formatted, err := format.Source(out.Bytes()) |
| 203 | if err != nil { |
| 204 | log.Println(out.String()) |
| 205 | log.Fatalf("--- error formatting source code: %v", err) |
| 206 | } |
| 207 | |
| 208 | err = ioutil.WriteFile(cfg.Out, formatted, 0644) |
| 209 | if err != nil { |
| 210 | log.Fatalf("error writing output to %s: %e", cfg.Out, err) |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | type Config struct { |
| 215 | PackageName string |
| 216 | In string |
| 217 | Out string |
| 218 | Skip map[string]bool |
| 219 | } |
| 220 | |
| 221 | func parseArgs() *Config { |
| 222 | cfg := &Config{} |
| 223 | |
| 224 | log.SetFlags(0) |
| 225 | opts, optind, err := getopt.Getopts(os.Args, "hs:p:") |
| 226 | if err != nil { |
| 227 | log.Fatalf("error: %e", err) |
| 228 | } |
| 229 | |
| 230 | cfg.PackageName = "gen" |
| 231 | cfg.Skip = make(map[string]bool) |
| 232 | |
| 233 | for _, opt := range opts { |
| 234 | switch opt.Option { |
| 235 | case 'p': |
| 236 | cfg.PackageName = opt.Value |
| 237 | case 's': |
| 238 | cfg.Skip[opt.Value] = true |
| 239 | case 'h': |
| 240 | log.Println("Usage: gen [-p <package>] [-s <skip type>] <input.bare> <output.go>") |
| 241 | os.Exit(0) |
| 242 | } |
| 243 | } |
| 244 | |
| 245 | args := os.Args[optind:] |
| 246 | if len(args) != 2 { |
| 247 | log.Fatal("Usage: gen [-p <package>] <input.bare> <output.go>") |
| 248 | } |
| 249 | |
| 250 | cfg.In = args[0] |
| 251 | cfg.Out = args[1] |
| 252 | |
| 253 | return cfg |
| 254 | } |
| 255 | |
| 256 | type Types struct { |
| 257 | UserTypes []*schema.UserDefinedType |
| 258 | Enums []*schema.UserDefinedEnum |
| 259 | Unions []*schema.UserDefinedType |
| 260 | UnionMembers []string |
| 261 | NeedErrors bool |
| 262 | } |
| 263 | |
| 264 | func parseSchema(path string, skip map[string]bool) Types { |
| 265 | inf, err := os.Open(path) |
| 266 | if err != nil { |
| 267 | log.Fatalf("error opening %s: %e", path, err) |
| 268 | } |
| 269 | defer inf.Close() |
| 270 | |
| 271 | schemaTypes, err := schema.Parse(inf) |
| 272 | if err != nil { |
| 273 | log.Fatalf("error parsing %s: %e", path, err) |
| 274 | } |
| 275 | |
| 276 | types := Types{} |
| 277 | |
| 278 | for _, ty := range schemaTypes { |
| 279 | if skip[ty.Name()] { |
| 280 | continue |
| 281 | } |
| 282 | |
| 283 | switch ty := ty.(type) { |
| 284 | case *schema.UserDefinedType: |
| 285 | if ty.Type().Kind() == schema.Union { |
| 286 | types.Unions = append(types.Unions, ty) |
| 287 | continue |
| 288 | } |
| 289 | types.UserTypes = append(types.UserTypes, ty) |
| 290 | |
| 291 | case *schema.UserDefinedEnum: |
| 292 | types.Enums = append(types.Enums, ty) |
| 293 | |
| 294 | } |
| 295 | } |
| 296 | |
| 297 | if len(types.Enums) > 0 { |
| 298 | types.NeedErrors = true |
| 299 | } |
| 300 | |
| 301 | seen := map[string]bool{} |
| 302 | for _, u := range types.Unions { |
| 303 | for _, sub := range u.Type().(*schema.UnionType).Types() { |
| 304 | name := sub.Type().(*schema.NamedUserType).Name() |
| 305 | if !seen[name] { |
| 306 | seen[name] = true |
| 307 | types.UnionMembers = append(types.UnionMembers, name) |
| 308 | } |
| 309 | } |
| 310 | } |
| 311 | |
| 312 | return types |
| 313 | } |