generate.go 2.13 KB
Newer Older
Eric Myhre's avatar
Eric Myhre committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
package gengo

import (
	"io"
	"os"
	"path/filepath"

	"github.com/ipld/go-ipld-prime/schema"
)

func Generate(pth string, pkgName string, ts schema.TypeSystem, adjCfg *AdjunctCfg) {
	// Emit fixed bits.
	withFile(filepath.Join(pth, "minima.go"), func(f io.Writer) {
		EmitInternalEnums(pkgName, f)
	})

	// Emit a file for each type.
	for _, typ := range ts.GetTypes() {
		withFile(filepath.Join(pth, "t"+typ.Name().String()+".go"), func(f io.Writer) {
			EmitFileHeader(pkgName, f)
			switch t2 := typ.(type) {
Eric Myhre's avatar
Eric Myhre committed
22 23
			case schema.TypeBool:
				EmitEntireType(NewBoolReprBoolGenerator(pkgName, t2, adjCfg), f)
Eric Myhre's avatar
Eric Myhre committed
24 25
			case schema.TypeInt:
				EmitEntireType(NewIntReprIntGenerator(pkgName, t2, adjCfg), f)
Eric Myhre's avatar
Eric Myhre committed
26 27
			case schema.TypeFloat:
				EmitEntireType(NewFloatReprFloatGenerator(pkgName, t2, adjCfg), f)
Eric Myhre's avatar
Eric Myhre committed
28 29
			case schema.TypeString:
				EmitEntireType(NewStringReprStringGenerator(pkgName, t2, adjCfg), f)
Eric Myhre's avatar
Eric Myhre committed
30 31 32 33
			case schema.TypeBytes:
				EmitEntireType(NewBytesReprBytesGenerator(pkgName, t2, adjCfg), f)
			case schema.TypeLink:
				EmitEntireType(NewLinkReprLinkGenerator(pkgName, t2, adjCfg), f)
Eric Myhre's avatar
Eric Myhre committed
34 35 36 37
			case schema.TypeStruct:
				switch t2.RepresentationStrategy().(type) {
				case schema.StructRepresentation_Map:
					EmitEntireType(NewStructReprMapGenerator(pkgName, t2, adjCfg), f)
38 39
				case schema.StructRepresentation_Stringjoin:
					EmitEntireType(NewStructReprStringjoinGenerator(pkgName, t2, adjCfg), f)
Eric Myhre's avatar
Eric Myhre committed
40 41 42
				default:
					panic("unrecognized struct representation strategy")
				}
43 44
			case schema.TypeMap:
				EmitEntireType(NewMapReprMapGenerator(pkgName, t2, adjCfg), f)
Eric Myhre's avatar
Eric Myhre committed
45 46
			case schema.TypeList:
				EmitEntireType(NewListReprListGenerator(pkgName, t2, adjCfg), f)
Eric Myhre's avatar
Eric Myhre committed
47 48
			case schema.TypeUnion:
				panic("this ain't done yet :) you can't do the synthesis until the end, sadly")
Eric Myhre's avatar
Eric Myhre committed
49 50 51 52 53
			default:
				panic("add more type switches here :)")
			}
		})
	}
54 55 56 57 58

	// Emit the unified type table.
	withFile(filepath.Join(pth, "typeTable.go"), func(f io.Writer) {
		EmitTypeTable(pkgName, ts, adjCfg, f)
	})
Eric Myhre's avatar
Eric Myhre committed
59 60 61 62 63 64 65 66 67 68
}

func withFile(filename string, fn func(io.Writer)) {
	f, err := os.OpenFile(filename, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
	if err != nil {
		panic(err)
	}
	defer f.Close()
	fn(f)
}