-
Notifications
You must be signed in to change notification settings - Fork 8
/
generator.go
1475 lines (1311 loc) · 40.1 KB
/
generator.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package cuetsy
import (
"fmt"
"math/bits"
"sort"
"strings"
"cuelang.org/go/cue"
"cuelang.org/go/cue/ast"
"cuelang.org/go/cue/errors"
"github.com/grafana/cuetsy/ts"
tsast "github.com/grafana/cuetsy/ts/ast"
)
const (
attrname = "cuetsy"
attrEnumMembers = "memberNames"
attrKind = "kind"
)
// TSType strings indicate the kind of TypeScript declaration to which a CUE
// value should be translated. They are used in both @cuetsy attributes, and in
// calls to certain methods.
type TSType string
const (
// TypeAlias targets conversion of a CUE value to a TypeScript `type`
// declaration, which are called type aliases:
// https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-aliases
TypeAlias TSType = "type"
// TypeInterface targets conversion of a CUE value to a TypeScript `interface`
// declaration:
// https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#interfaces
TypeInterface TSType = "interface"
// TypeEnum targets conversion of a CUE value to a TypeScript `enum`
// declaration:
// https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#enums
TypeEnum TSType = "enum"
)
var allKinds = [...]TSType{
TypeAlias,
TypeInterface,
TypeEnum,
}
// Config governs certain variable behaviors when converting CUE to Typescript.
type Config struct {
// ImportMapper determines how CUE imports are mapped to Typescript imports. If
// nil, any non-stdlib import in the input CUE source will result in a fatal
// error.
//
// Import conversions are only run if the input [cue.Value] or its top-level
// conjuncts if [cue.Value.Source] returns an [*ast.File]. This eliminates
// computed values, and values representing nodes other than a root file
// node.
ImportMapper
// Export determines whether generated TypeScript symbols are exported.
Export bool
}
// Generate takes a cue.Value and generates the corresponding TypeScript for all
// top-level members of that value that have appropriate @cuetsy attributes.
//
// Hidden fields are ignored.
func Generate(val cue.Value, c Config) (b []byte, err error) {
file, err := GenerateAST(val, c)
if err != nil {
return nil, err
}
return []byte("\n" + file.String()), nil
}
func GenerateAST(val cue.Value, c Config) (*ts.File, error) {
if err := val.Validate(); err != nil {
return nil, err
}
if c.ImportMapper == nil {
c.ImportMapper = nilImportMapper
}
g := &generator{
c: c,
val: &val,
}
var file ts.File
var err error
file.Imports, err = mapImports(val, c.ImportMapper)
if err != nil {
return nil, err
}
iter, err := val.Fields(
cue.Definitions(true),
cue.Optional(true),
)
if err != nil {
return nil, err
}
for iter.Next() {
n := g.decl(iter.Selector().String(), iter.Value())
file.Nodes = append(file.Nodes, n...)
}
return &file, g.err
}
func GenerateSingleAST(name string, v cue.Value, t TSType) (*DeclPair, error) {
g := &generator{
c: Config{Export: true},
val: &v,
}
switch t {
case TypeEnum:
return fromDeclSlice(g.genEnum(name, v), g.err)
case TypeInterface:
return fromDeclSlice(g.genInterface(name, v), g.err)
case TypeAlias:
return fromDeclSlice(g.genType(name, v), g.err)
default:
return nil, fmt.Errorf("unrecognized TSType %q", string(t))
}
}
// DeclPair represents a generated type declaration, with its corresponding default declaration.
type DeclPair struct {
// The generated type declaration.
T ts.Decl
// The default declaration corresponding to T.
D ts.Decl
}
func fromDeclSlice(decl []ts.Decl, err error) (*DeclPair, error) {
if err != nil {
return nil, err
}
switch len(decl) {
case 0:
return nil, errors.New("no decls returned")
case 1:
return &DeclPair{
T: decl[0],
}, nil
case 2:
return &DeclPair{
T: decl[0],
D: decl[1],
}, nil
default:
return nil, fmt.Errorf("expected 1 or 2 decls in slice, got %v", len(decl))
}
}
type generator struct {
val *cue.Value
c Config
err errors.Error
}
func (g *generator) addErr(err error) {
if err != nil {
g.err = errors.Append(g.err, errors.Promote(err, "generate failed"))
}
}
func (g *generator) decl(name string, v cue.Value) []ts.Decl {
tst, err := getKindFor(v)
if err != nil {
// Ignore values without attributes
return nil
}
switch tst {
case TypeEnum:
return g.genEnum(name, v)
case TypeInterface:
return g.genInterface(name, v)
case TypeAlias:
return g.genType(name, v)
default:
return nil // TODO error out
}
}
func (g *generator) genType(name string, v cue.Value) []ts.Decl {
var tokens []tsast.Expr
// If there's an AndOp first, pass through it.
op, dvals := v.Expr()
if op == cue.AndOp {
op, dvals = dvals[0].Expr()
}
switch op {
case cue.OrOp:
for _, dv := range dvals {
tok, err := g.tsprintField(dv, true, false)
if err != nil {
g.addErr(err)
return nil
}
tokens = append(tokens, tok)
}
case cue.NoOp, cue.RegexMatchOp:
tok, err := g.tsprintField(v, true, false)
if err != nil {
g.addErr(err)
return nil
}
tokens = append(tokens, tok)
default:
g.addErr(valError(v, "typescript types may only be generated from a single value or disjunction of values"))
}
ret := make([]ts.Decl, 2)
ret[0] = tsast.TypeDecl{
Name: ts.Ident(name),
Type: tsast.BasicType{Expr: ts.Union(tokens...)},
CommentList: commentsFor(v, true),
Export: g.c.Export,
}
d, ok := v.Default()
if !ok {
return ret[:1]
}
val, err := g.tsprintField(d, false, false)
g.addErr(err)
def := tsast.VarDecl{
Names: ts.Names("default" + name),
Type: ts.Ident(name),
Value: val,
Export: g.c.Export,
}
// Only make struct-kinded types into partials
if v.IncompleteKind() == cue.StructKind {
def.Type = tsast.TypeTransformExpr{
Transform: "Partial",
Expr: def.Type,
}
}
ret[1] = def
return ret
}
type KV struct {
K, V string
}
// genEnum turns the following cue values into typescript enums:
// - value disjunction (a | b | c): values are taken as attribute memberNames,
// if memberNames is absent, then keys implicitly generated as CamelCase
// - string struct: struct keys get enum keys, struct values enum values
func (g *generator) genEnum(name string, v cue.Value) []ts.Decl {
// FIXME compensate for attribute-applying call to Unify() on incoming Value
op, dvals := v.Expr()
if op == cue.AndOp {
v = dvals[0]
op, _ = v.Expr()
}
// We restrict the expression of TS enums to ints or strings.
allowed := cue.StringKind | cue.IntKind
ik := v.IncompleteKind()
if ik&allowed != ik {
g.addErr(valError(v, "typescript enums may only be generated from concrete strings, or ints with memberNames attribute"))
return nil
}
exprs, err := orEnum(v)
if err != nil {
g.addErr(err)
}
ret := make([]ts.Decl, 2)
ret[0] = tsast.TypeDecl{
Name: ts.Ident(name),
Type: tsast.EnumType{Elems: exprs},
CommentList: commentsFor(v, true),
Export: g.c.Export,
}
defaultIdent, err := enumDefault(v)
g.addErr(err)
if defaultIdent == nil {
return ret[:1]
}
ret[1] = tsast.VarDecl{
Names: ts.Names("default" + name),
Type: ts.Ident(name),
Value: tsast.SelectorExpr{Expr: ts.Ident(name), Sel: *defaultIdent},
Export: g.c.Export,
}
return ret
}
func enumDefault(v cue.Value) (*tsast.Ident, error) {
def, ok := v.Default()
if !ok {
return nil, def.Err()
}
if v.IncompleteKind() == cue.StringKind {
s, _ := def.String()
return &tsast.Ident{Name: strings.Title(s)}, nil
}
// For Int, Float, Numeric we need to find the default value and its corresponding memberName value
a := v.Attribute(attrname)
val, found, err := a.Lookup(0, attrEnumMembers)
if err != nil || !found {
panic(fmt.Sprintf("looking up memberNames: found=%t err=%s", found, err))
}
evals := strings.Split(val, "|")
_, dvals := v.Expr()
for i, val := range dvals {
valLab, _ := val.Label()
defLab, _ := def.Label()
if valLab == defLab {
return &tsast.Ident{Name: evals[i]}, nil
}
}
// should never reach here tho
return nil, valError(v, "unable to find memberName corresponding to the default")
}
// List the pairs of values and member names in an enum. Err if input is not an enum
func enumPairs(v cue.Value) ([]enumPair, error) {
// TODO should validate here. Or really, this is just evidence of how building these needs its own types
op, dvals := v.Expr()
if !targetsKind(v, TypeEnum) || op != cue.OrOp {
return nil, fmt.Errorf("not an enum: %v (%s)", v, v.Path())
}
a := v.Attribute(attrname)
val, found, err := a.Lookup(0, attrEnumMembers)
if err != nil {
panic(fmt.Sprintf("looking up memberNames: found=%t err=%s", found, err))
}
var evals []string
if found {
evals = strings.Split(val, "|")
} else if v.IncompleteKind() == cue.StringKind {
for _, part := range dvals {
s, _ := part.String()
evals = append(evals, strings.Title(s))
}
} else {
return nil, fmt.Errorf("must provide memberNames attribute for non-string enums")
}
var pairs []enumPair
for i, eval := range evals {
pairs = append(pairs, enumPair{
name: eval,
val: dvals[i],
})
}
return pairs, nil
}
type enumPair struct {
name string
val cue.Value
}
func orEnum(v cue.Value) ([]ts.Expr, error) {
_, dvals := v.Expr()
a := v.Attribute(attrname)
var attrMemberNameExist bool
var evals []string
if a.Err() == nil {
val, found, err := a.Lookup(0, attrEnumMembers)
if err == nil && found {
attrMemberNameExist = true
evals = strings.Split(val, "|")
if len(evals) != len(dvals) {
return nil, valError(v, "typescript enums and %s attributes size doesn't match", attrEnumMembers)
}
}
}
// We only allowed String Enum to be generated without memberName attribute
if v.IncompleteKind() != cue.StringKind && !attrMemberNameExist {
return nil, valError(v, "typescript numeric enums may only be generated from memberNames attribute")
}
var fields []ts.Expr
for idx, dv := range dvals {
var text string
var id tsast.Ident
if attrMemberNameExist {
text = evals[idx]
id = ts.Ident(text)
} else {
text, _ = dv.String()
id = ts.Ident(strings.Title(text))
}
if !dv.IsConcrete() {
return nil, valError(v, "typescript enums may only be generated from a disjunction of concrete strings or numbers")
}
if id.Validate() != nil {
return nil, valError(v, "title casing of enum member %q produces an invalid typescript identifier; memberNames must be explicitly given in @cuetsy attribute", text)
}
fields = append(fields, tsast.AssignExpr{
// Simple mapping of all enum values (which we are assuming are in
// lowerCamelCase) to corresponding CamelCase
Name: id,
Value: tsprintConcrete(dv),
})
}
sort.Slice(fields, func(i, j int) bool {
return fields[i].String() < fields[j].String()
})
return fields, nil
}
func (g *generator) genInterface(name string, v cue.Value) []ts.Decl {
// We restrict the derivation of Typescript interfaces to struct kinds.
// (More than just a struct literal match this, though.)
if v.IncompleteKind() != cue.StructKind {
// FIXME check for bottom here, give different error
g.addErr(valError(v, "typescript interfaces may only be generated from structs"))
return nil
}
extends, nolit, err := findExtends(v)
if err != nil {
g.addErr(err)
return nil
}
var elems []tsast.KeyValueExpr
var defs []tsast.KeyValueExpr
iter, _ := v.Fields(cue.Optional(true))
for iter != nil && iter.Next() {
if iter.Selector().PkgPath() != "" {
g.addErr(valError(iter.Value(), "cannot generate hidden fields; typescript has no corresponding concept"))
return nil
}
// Skip fields that are subsumed by the Value representing the
// unification of all refs that will be represented using an "extends"
// keyword.
//
// This does introduce the possibility that even some fields which are
// literally declared on the struct will not end up written out in
// Typescript (though the semantics will still be correct). That's
// likely to be a bit confusing for users, but we have no choice. The
// (preferable) alternative would rely on Unify() calls to build a Value
// containing only those fields that we want, then iterating over that
// in this loop.
//
// Unfortunately, as of v0.4.0, Unify() appears to not preserve
// attributes on the Values it generates, which makes it impossible to
// rely on, as the tsprintField() func later also needs to check these
// attributes in order to decide whether to render a field as a
// reference or a literal.
//
// There's _probably_ a way around this, especially when we move to an
// AST rather than dumb string templates. But i'm tired of looking.
if len(extends) > 0 {
// Look up the path of the current field within the nolit value,
// then check it for subsumption.
sel := iter.Selector()
if iter.IsOptional() {
sel = sel.Optional()
}
sub := nolit.LookupPath(cue.MakePath(sel))
// Theoretically, lattice equality can be defined as bijective
// subsumption. In practice, Subsume() seems to ignore optional
// fields, and Equals() doesn't. So, use Equals().
// We need to check if the child overrides the parent. In that case, we have an AndOp that
// tell us that it is setting a value.
op, _ := iter.Value().Expr()
// Also we need to check if the sub operator to discard the one that have validators and if it has a default
subOp, _ := sub.Expr()
_, def := iter.Value().Default()
if sub.Exists() && sub.Equals(iter.Value()) && (subOp == cue.AndOp || op != cue.AndOp || !def) {
continue
}
}
k := iter.Selector().String()
if iter.IsOptional() {
k += "?"
}
tref, err := g.genInterfaceField(iter.Value())
if err != nil || tref == nil {
return nil
}
elems = append(elems, tsast.KeyValueExpr{
Key: ts.Ident(k),
Value: tref.T,
CommentList: commentsFor(iter.Value(), true),
})
if tref.D != nil {
defs = append(defs, tsast.KeyValueExpr{
Key: ts.Ident(strings.TrimSuffix(k, "?")),
Value: tref.D,
})
}
}
sort.Slice(elems, func(i, j int) bool {
return elems[i].Key.String() < elems[j].Key.String()
})
sort.Slice(defs, func(i, j int) bool {
return defs[i].Key.String() < defs[j].Key.String()
})
ret := make([]ts.Decl, 2)
ret[0] = tsast.TypeDecl{
Name: ts.Ident(name),
Type: tsast.InterfaceType{
Elems: elems,
Extends: extends,
},
CommentList: commentsFor(v, true),
Export: g.c.Export,
}
if len(defs) == 0 {
return ret[:1]
}
ret[1] = tsast.VarDecl{
Names: ts.Names("default" + name),
Type: tsast.TypeTransformExpr{
Transform: "Partial",
Expr: ts.Ident(name),
},
Value: tsast.ObjectLit{Elems: defs},
Export: g.c.Export,
}
return ret
}
// Recursively walk down Values returned from Expr() and separate
// unified/embedded structs from a struct literal, so that we can make the
// former (if they are also marked with @cuetsy(kind="interface")) show up
// as "extends" instead of inlining their fields.
func findExtends(v cue.Value) ([]ts.Expr, cue.Value, error) {
var extends []ts.Expr
// Create an empty value, onto which we'll unify fields that need not be
// generated as literals.
baseNolit := v.Context().CompileString("")
nolit := v.Context().CompileString("")
var walkExpr func(v cue.Value) error
walkExpr = func(v cue.Value) error {
op, dvals := v.Expr()
switch op {
case cue.NoOp:
// Simple path - when the field is a plain struct literal decl, the walk function
// will take this branch and return immediately.
// FIXME this does the struct literal path correctly, but it also
// catches this case, for some reason:
//
// Thing: {
// other.Thing
// }
//
// The saner form - `Thing: other.Thing` - does not go through this path.
return nil
case cue.OrOp:
return valError(v, "typescript interfaces cannot be constructed from disjunctions")
case cue.SelectorOp:
expr, err := refAsInterface(v)
if err != nil {
return err
}
// If we have a string to add to the list of "extends", then also
// add the ref to the list of fields to exclude if subsumed.
if expr != nil {
extends = append(extends, expr)
nolit = baseNolit.Unify(nolit.Unify(cue.Dereference(v)))
}
return nil
case cue.AndOp:
// First, search the dvals for StructLits. Having more than one is possible,
// but weird, as writing >1 literal and unifying them is the same as just writing
// one containing the unified result - more complicated with no obvious benefit.
for _, dv := range dvals {
if dv.IncompleteKind() != cue.StructKind && dv.IncompleteKind() != cue.TopKind {
panic("impossible? seems like it should be. if this pops, clearly not!")
}
if err := walkExpr(dv); err != nil {
return err
}
}
return nil
default:
panic(fmt.Sprintf("unhandled op type %s", op.String()))
}
}
if err := walkExpr(v); err != nil {
return nil, nolit, err
}
return extends, nolit, nil
}
// Generate a typeRef for the cue.Value
func (g *generator) genInterfaceField(v cue.Value) (*typeRef, error) {
if hasEnumReference(v) {
return g.genEnumReference(v)
}
tref := &typeRef{}
var err error
tref.T, err = g.tsprintField(v, true, false)
if err != nil {
if !containsCuetsyReference(v) {
g.addErr(valError(v, "could not generate field: %w", err))
return nil, err
}
g.addErr(err)
return nil, nil
}
exists, defExpr, err := g.tsPrintDefault(v)
if exists {
tref.D = defExpr
}
g.addErr(err)
return tref, err
}
func hasEnumReference(v cue.Value) bool {
// Check if we've got an enum reference at top depth or one down. If we do, it
// changes how we generate.
hasPred := containsPred(v, 1,
isReference,
func(v cue.Value) bool { return targetsKind(cue.Dereference(v), TypeEnum) },
)
// Check if it's setting an enum value [Enum & "value"]
op, args := v.Expr()
if op == cue.AndOp {
return hasPred
}
// Check if it has default value [Enum & (*"defaultValue" | _)]
for _, a := range args {
if a.IncompleteKind() == cue.TopKind {
return hasPred
}
}
isUnion := true
allEnums := true
for _, a := range args {
// Check if it is a union [(Enum & "a") | (Enum & "b")]
if a.Kind() != a.IncompleteKind() {
isUnion = false
}
// Check if all elements are enums
_, exprs := a.Expr()
for _, e := range exprs {
if t, err := getKindFor(cue.Dereference(e)); err == nil && t != TypeEnum {
allEnums = false
}
}
}
return hasPred && isUnion && allEnums
}
func hasTypeReference(v cue.Value) bool {
hasTypeRef := containsCuetsyReference(v, TypeAlias)
// Check if it's setting an enum value [Type & "value"]
op, args := v.Expr()
if op == cue.AndOp || op == cue.SelectorOp {
return hasTypeRef
}
// Check if it has default value [Type & (*"defaultValue" | _)]
for _, a := range args {
if a.IncompleteKind() == cue.TopKind {
return hasTypeRef
}
}
return false
}
// Generate a typeref for a value that refers to a field
func (g *generator) genEnumReference(v cue.Value) (*typeRef, error) {
var lit *cue.Value
conjuncts := appendSplit(nil, cue.AndOp, v)
var enumUnions map[cue.Value]cue.Value
switch len(conjuncts) {
case 0:
panic("unreachable")
case 1:
// This case is when we have a union of enums which we need to iterate them to get their values or has a default value.
// It retrieves a list of literals with their references.
enumUnions = g.findEnumUnions(v)
case 2:
var err error
conjuncts[1] = getDefaultEnumValue(conjuncts[1])
lit, err = getEnumLiteral(conjuncts)
if err != nil {
ve := valError(v, err.Error())
g.addErr(ve)
return nil, ve
}
case 3:
if conjuncts[1].IncompleteKind() == cue.TopKind {
conjuncts[1] = conjuncts[0]
}
if !conjuncts[0].Equals(conjuncts[1]) && conjuncts[0].Subsume(conjuncts[1]) != nil {
ve := valError(v, "complex unifications containing references to enums without overriding parent are not currently supported")
g.addErr(ve)
return nil, ve
}
var err error
lit, err = getEnumLiteral(conjuncts[1:])
if err != nil {
ve := valError(v, err.Error())
g.addErr(ve)
return nil, ve
}
default:
ve := valError(v, "complex unifications containing references to enums are not currently supported")
g.addErr(ve)
return nil, ve
}
// Search the expr tree for the actual enum. This approach is uncomfortable
// without having the assurance that there aren't more than one possible match/a
// guarantee from the CUE API of a stable, deterministic search order, etc.
enumValues, referrer, has := findRefWithKind(v, TypeEnum)
if !has {
ve := valError(v, "does not reference a field with a cuetsy enum attribute")
g.addErr(ve)
return nil, fmt.Errorf("no enum attr in %s", v)
}
var err error
decls := g.genEnum("foo", enumValues)
ref := &typeRef{}
// Construct the type component of the reference
switch len(decls) {
default:
ve := valError(v, "unsupported number of expression args (%v) in reference, expected 1 or 2", len(decls))
g.addErr(ve)
return nil, ve
case 1, 2:
ref.T, err = referenceValueAs(referrer, TypeEnum)
if err != nil {
panic(err)
}
}
// Either specify a default if one exists (one conjunct), or rewrite the type to
// reference one of the members of the enum (two conjuncts).
switch len(conjuncts) {
case 1:
if defv, hasdef := v.Default(); hasdef {
err = g.findIdent(v, enumValues, defv, func(expr tsast.Ident) {
ref.D = tsast.SelectorExpr{Expr: ref.T, Sel: expr}
})
}
if len(enumUnions) == 0 {
break
}
var elements []tsast.Expr
for lit, enumValues := range enumUnions {
err = g.findIdent(v, enumValues, lit, func(ident tsast.Ident) {
elements = append(elements, tsast.SelectorExpr{
Expr: ref.T,
Sel: ident,
})
})
}
// To avoid to change the order of the elements everytime that we generate the code.
sort.Slice(elements, func(i, j int) bool {
return elements[i].String() < elements[j].String()
})
ref.T = ts.Union(elements...)
case 2, 3:
var rr tsast.Expr
err = g.findIdent(v, enumValues, *lit, func(ident tsast.Ident) {
rr = tsast.SelectorExpr{Expr: ref.T, Sel: ident}
})
op, args := v.Expr()
hasInnerDefault := false
if len(args) == 2 && op == cue.AndOp {
_, hasInnerDefault = args[1].Default()
}
if _, has := v.Default(); has || hasInnerDefault {
ref.D = rr
} else {
ref.T = rr
}
}
return ref, err
}
// findEnumUnions find the unions between enums like (#Enum & "a") | (#Enum & "b")
func (g generator) findEnumUnions(v cue.Value) map[cue.Value]cue.Value {
op, values := v.Expr()
if op != cue.OrOp {
return nil
}
enumsWithUnions := make(map[cue.Value]cue.Value, len(values))
for _, val := range values {
conjuncts := appendSplit(nil, cue.AndOp, val)
if len(conjuncts) != 2 {
return nil
}
cr, lit := conjuncts[0], conjuncts[1]
if cr.Subsume(lit) != nil {
return nil
}
switch val.Kind() {
case cue.StringKind, cue.IntKind:
enumValues, _, has := findRefWithKind(v, TypeEnum)
if !has {
return nil
}
enumsWithUnions[lit] = enumValues
default:
_, vals := val.Expr()
if len(vals) > 1 {
panic(fmt.Sprintf("%s.%s isn't a valid enum value", val.Path().String(), vals[1]))
}
panic(fmt.Sprintf("Invalid value in path %s", val.Path().String()))
}
}
return enumsWithUnions
}
func (g generator) findIdent(v, ev, tv cue.Value, fn func(tsast.Ident)) error {
if ev.Subsume(tv) != nil {
err := valError(v, "may only apply values to an enum that are members of that enum; %#v is not a member of %#v", tv, ev)
g.addErr(err)
return err
}
pairs, err := enumPairs(ev)
if err != nil {
return err
}
for _, pair := range pairs {
if veq(pair.val, tv) {
fn(tsast.Ident{Name: pair.name})
return nil
}
}
panic(fmt.Sprintf("unreachable - %#v not equal to any member of %#v, but should have been caught by subsume check", tv, ev))
}
func getEnumLiteral(conjuncts []cue.Value) (*cue.Value, error) {
var lit *cue.Value
// The only case we actually want to support, at least for now, is this:
//
// enum: "foo" | "bar" @cuetsy(kind="enum")
// enumref: enum & "foo" @cuetsy(kind="type")
//
// Where we render enumref to TS as `Enumref: Enum.Foo`.
// For that case, we allow at most two conjuncts, and make sure they
// fit the pattern of the two operands above.
aref, bref := isReference(conjuncts[0]), isReference(conjuncts[1])
aconc, bconc := conjuncts[0].IsConcrete(), conjuncts[1].IsConcrete()
var cr cue.Value
if aref {
cr, lit = conjuncts[0], &(conjuncts[1])
} else {
cr, lit = conjuncts[1], &(conjuncts[0])
}
if aref == bref || aconc == bconc || cr.Subsume(*lit) != nil {
return nil, errors.New(fmt.Sprintf("may only unify a referenced enum with a concrete literal member of that enum. Path: %s", conjuncts[0].Path()))
}
return lit, nil
}
// getDefaultEnumValue is looking for default values like #Enum & (*"default" | _) struct
func getDefaultEnumValue(v cue.Value) cue.Value {
if v.IncompleteKind() != cue.TopKind {
return v
}
op, args := v.Expr()
if op != cue.OrOp {
return v
}
for _, a := range args {
if a.IncompleteKind() == cue.TopKind {
if def, has := a.Default(); has {
return def
}
}
}
return v
}
// typeRef is a pair of expressions for referring to another type - the reference
// to the type, and the default value for the referrer. The default value
// may be the one provided by either the referent, or by the field doing the referring
// (in the case of a superseding mark).
type typeRef struct {
T ts.Expr
D ts.Expr
}
func (g generator) tsPrintDefault(v cue.Value) (bool, ts.Expr, error) {
d, ok := v.Default()
// [...number] results in [], which is a fake default, we need to correct it here.
// if ok && d.Kind() == cue.ListKind {
// len, err := d.Len().Int64()
// if err != nil {
// return false, nil, err
// }
// var defaultExist bool
// if len <= 0 {
// op, vals := v.Expr()
// if op == cue.OrOp {
// for _, val := range vals {
// vallen, _ := d.Len().Int64()
// if val.Kind() == cue.ListKind && vallen <= 0 {
// defaultExist = true
// break
// }
// }
// if !defaultExist {
// ok = false
// }
// } else {
// ok = false
// }
// }
// }
if ok {
expr, err := g.tsprintField(d, false, true)
if err != nil {
return false, nil, err
}
if isReference(d) && (hasEnumReference(v) || hasTypeReference(v)) {
switch t := expr.(type) {
case tsast.SelectorExpr:
t.Sel.Name = "default" + t.Sel.Name
expr = t
case tsast.Ident:
t.Name = "default" + t.Name
expr = t
default:
panic(fmt.Sprintf("unexpected type %T", expr))