...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package gocode
16
17 import (
18 "text/template"
19 )
20
21
22
23 var headerCode = template.Must(template.New("header").Parse(
24 `// Code generated by gocode.Generate; DO NOT EDIT.
25
26 package {{.pkgName}}
27
28 import (
29 "fmt"
30
31 "cuelang.org/go/cue"
32 "cuelang.org/go/encoding/gocode/gocodec"
33 _ "cuelang.org/go/pkg"
34 )
35
36 `))
37
38
39
40
41
42
43
44
45 var stubCode = template.Must(template.New("type").Parse(`
46 var {{.prefix}}val{{.cueName}} = {{.prefix}}Make("{{.cueName}}", {{.zero}})
47
48 {{ $sig := .goType | printf "(x %s)" -}}
49 {{if .validate}}
50 // {{.validate}}{{if .func}}{{.cueName}}{{end}} validates x.
51 func {{if .func}}{{.validate}}{{.cueName}}{{$sig}}
52 {{- else -}}{{$sig}} {{.validate}}(){{end}} error {
53 return {{.prefix}}Codec.Validate({{.prefix}}val{{.cueName}}, x)
54 }
55 {{end}}
56 {{if .complete}}
57 // {{.complete}}{{if .func}}{{.cueName}}{{end}} completes x.
58 func {{if .func}}{{.complete}}{{.cueName}}{{$sig}}
59 {{- else -}}{{$sig}} {{.complete}}(){{end}} error {
60 return {{.prefix}}Codec.Complete({{.prefix}}val{{.cueName}}, x)
61 }
62 {{end}}
63 `))
64
65
66
67
68
69 var loadCode = template.Must(template.New("load").Parse(`
70 var {{.prefix}}Codec, {{.prefix}}Instance_, {{.prefix}}Value = func() (*gocodec.Codec, *cue.Instance, cue.Value) {
71 var r *cue.Runtime
72 r = {{if .runtime}}{{.runtime}}{{else}}&cue.Runtime{}{{end}}
73 instances, err := r.Unmarshal({{.prefix}}InstanceData)
74 if err != nil {
75 panic(err)
76 }
77 if len(instances) != 1 {
78 panic("expected encoding of exactly one instance")
79 }
80 return gocodec.New(r, nil), instances[0], instances[0].Value()
81 }()
82
83 // Deprecated: cue.Instance is deprecated. Use {{.prefix}}Value instead.
84 var {{.prefix}}Instance = {{.prefix}}Instance_
85
86 // {{.prefix}}Make is called in the init phase to initialize CUE values for
87 // validation functions.
88 func {{.prefix}}Make(name string, x interface{}) cue.Value {
89 f, err := {{.prefix}}Value.FieldByName(name, true)
90 if err != nil {
91 panic(fmt.Errorf("could not find type %q in instance", name))
92 }
93 v := f.Value
94 if x != nil {
95 w, err := {{.prefix}}Codec.ExtractType(x)
96 if err != nil {
97 panic(err)
98 }
99 v = v.Unify(w)
100 }
101 return v
102 }
103
104 // Data size: {{len .data}} bytes.
105 var {{.prefix}}InstanceData = []byte({{printf "%+q" .data }})
106 `))
107
View as plain text