Exemplo n.º 1
0
Arquivo: structs.go Projeto: kego/ke
func printExportFunction(ctx context.Context, env *envctx.Env, g *builder.Builder, export *sysctx.SysExportInfo) error {
	g.Println("func ", system.GoName(export.Name), "() *", g.SprintRef(export.TypePackage, system.GoName(export.TypeName)), " {")
	{
		g.Print("ctx := ")
		g.PrintFunctionCall("kego.io/system", "NewContext",
			g.SprintFunctionCall("context", "Background"),
			strconv.Quote(env.Path),
			fmt.Sprintf("%#v", env.Aliases),
		)
		g.Println()

		g.Println("o := new(", g.SprintRef(export.TypePackage, system.GoName(export.TypeName)), ")")

		g.Print("err := ")
		g.PrintMethodCall("o", "Unpack",
			"ctx",
			g.SprintFunctionCall("kego.io/system", "MustPackString", strconv.Quote(string(export.JsonContents))),
			"false",
		)
		g.Println()
		g.Println("if err != nil {")
		{
			g.Println("panic(err.Error())")
		}
		g.Println("}")
		g.Println("return o")
	}
	g.Println("}")
	return nil
}
Exemplo n.º 2
0
Arquivo: structs.go Projeto: kego/ke
func printInitFunction(ctx context.Context, env *envctx.Env, g *builder.Builder, types *sysctx.SysTypes) {
	g.Println("func init() {")
	{
		g.Print("pkg := ")
		g.PrintFunctionCall(
			"kego.io/context/jsonctx",
			"InitPackage",
			strconv.Quote(env.Path),
		)
		g.Println("")
		g.PrintMethodCall("pkg", "SetHash", env.Hash)
		g.Println("")
		for _, name := range types.Keys() {
			t, ok := types.Get(name)
			if !ok {
				// ke: {"block": {"notest": true}}
				continue
			}
			typ := t.Type.(*system.Type)
			isRule := typ.Id.IsRule()

			if isRule {
				continue
			}

			interfaceFunc := "nil"
			isNativeCollection := typ.IsNativeCollection() && typ.Alias == nil
			if !isNativeCollection {
				var ifaceName string
				if typ.Interface {
					ifaceName = system.GoName(typ.Id.Name)
				} else {
					ifaceName = system.GoInterfaceName(typ.Id.Name)
				}
				reflectTypeof := g.SprintFunctionCall(
					"reflect",
					"TypeOf",
					fmt.Sprintf("(*%s)(nil)", ifaceName),
				) + ".Elem()"
				reflectType := builder.Reference("reflect", "Type", env.Path, g.Imports.Add)
				interfaceFunc = "func() " + reflectType + " { return " + reflectTypeof + " }"
			}

			newFunc := "nil"
			derefFunc := "nil"
			if typ.Interface {
				newFunc = "func() interface{} { return (*" + system.GoName(typ.Id.Name) + ")(nil) }"
			} else if !typ.IsNativeCollection() || typ.Alias != nil {
				newFunc = "func() interface{} { return new(" + system.GoName(typ.Id.Name) + ")}"
				if !typ.PassedAsPointer(ctx) {
					derefFunc = "func(in interface{}) interface{} {return *in.(*" + system.GoName(typ.Id.Name) + ")}"
				}
			}
			g.Println("pkg.Init(")
			{
				g.Println(strconv.Quote(typ.Id.Name), ",")
				g.Println(newFunc, ",")
				g.Println(derefFunc, ",")
				g.Println("func() interface{} { return new("+system.GoName(typ.Id.ChangeToRule().Name)+")}", ",")
				g.Println(interfaceFunc, ",")
			}
			g.Println(")")

			g.Println("")
		}
	}
	g.Println("}")
}