-
-
Notifications
You must be signed in to change notification settings - Fork 23
/
convert.go
1399 lines (1347 loc) · 35.2 KB
/
convert.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 cxgo
import (
"fmt"
"strings"
"modernc.org/cc/v3"
"modernc.org/token"
"github.com/gotranspile/cxgo/types"
)
func (g *translator) newIdent(name string, t types.Type) *types.Ident {
if id, ok := g.env.IdentByName(name); ok {
if it := id.CType(nil); it.Kind().Major() == t.Kind().Major() || (it.Kind().IsBool() && t.Kind().IsInt()) {
return id // FIXME: this is invalid, we should consult scopes instead
}
}
return types.NewIdent(name, t)
}
func (g *translator) convMacro(name string, fnc func() Expr) Expr {
if g.env.ForceMacro(name) {
return fnc()
}
id, ok := g.macros[name]
if ok {
return IdentExpr{id}
}
x := fnc()
typ := x.CType(nil)
id = g.newIdent(name, typ)
g.macros[name] = id
return IdentExpr{id}
}
func (g *translator) convertIdent(scope cc.Scope, tok cc.Token, t types.Type) IdentExpr {
var decl []cc.Node
for len(scope) != 0 {
if nodes, ok := scope[tok.Value]; ok {
decl = nodes
break
}
scope = scope.Parent()
}
if len(decl) == 0 {
panic(fmt.Errorf("unresolved identifier: %s (%s)", tok, tok.Position()))
}
return g.convertIdentWith(tok.String(), t, decl...)
}
func (g *translator) convertIdentWith(name string, t types.Type, decls ...cc.Node) IdentExpr {
for _, d := range decls {
if id, ok := g.decls[d]; ok && id.Name == name {
return IdentExpr{id}
}
}
id := g.newIdent(name, t)
if to, ok := g.idents[name]; ok && to.Rename != "" {
id.GoName = to.Rename
}
for _, d := range decls {
g.decls[d] = id
}
return IdentExpr{id}
}
func (g *translator) replaceIdentWith(id *types.Ident, decls ...cc.Node) {
for _, d := range decls {
g.decls[d] = id
}
}
func (g *translator) tryConvertIdentOn(t types.Type, tok cc.Token) (*types.Ident, bool) {
loop:
for {
switch s := t.(type) {
case types.PtrType:
t = s.Elem()
case types.ArrayType:
t = s.Elem()
case types.Named:
t = s.Underlying()
default:
break loop
}
}
switch t := t.(type) {
case *types.StructType:
name := tok.Value.String()
for _, f := range t.Fields() {
if name == f.Name.Name {
return f.Name, true
}
if f.Name.Name == "" {
if id, ok := g.tryConvertIdentOn(f.Type(), tok); ok {
return id, true
}
}
}
}
return nil, false
}
func (g *translator) convertIdentOn(t types.Type, tok cc.Token) *types.Ident {
id, ok := g.tryConvertIdentOn(t, tok)
if ok {
return id
}
panic(fmt.Errorf("%#v.%q (%s)", t, tok.Value.String(), tok.Position()))
}
func (g *translator) convertFuncDef(d *cc.FunctionDefinition) []CDecl {
decl := d.Declarator
switch dd := decl.DirectDeclarator; dd.Case {
case cc.DirectDeclaratorFuncParam, cc.DirectDeclaratorFuncIdent:
sname := decl.Name().String()
conf := g.idents[sname]
ft := g.convertFuncType(conf, decl, decl.Type(), decl.Position())
if !g.inCurFile(d) {
return nil
}
name := g.convertIdentWith(sname, ft, decl)
return []CDecl{
&CFuncDecl{
Name: name.Ident,
Type: ft,
Body: g.convertCompBlockStmt(d.CompoundStatement).In(ft),
Range: &Range{
Start: d.Position().Offset,
StartLine: d.Position().Line,
},
},
}
default:
panic(dd.Case.String() + " " + dd.Position().String())
}
}
type positioner interface {
Position() token.Position
}
func (g *translator) inCurFile(p positioner) bool {
name := strings.TrimLeft(p.Position().Filename, "./")
if g.cur == name {
return true
} else if !strings.HasSuffix(g.cur, ".c") {
return false
}
return g.cur[:len(g.cur)-2]+".h" == name
}
func (g *translator) convertInitList(typ types.Type, list *cc.InitializerList) Expr {
var items []*CompLitField
var (
prev int64 = -1 // previous array init index
pi int64 = 0 // relative index added to the last seen item; see below
)
for it := list; it != nil; it = it.InitializerList {
val := g.convertInitExpr(it.Initializer)
var f *CompLitField
if it.Designation == nil {
// no index in the initializer - assign automatically
pi++
f = &CompLitField{Index: cIntLit(prev+pi, 10), Value: val}
items = append(items, f)
continue
}
f = g.convertOneDesignator(typ, it.Designation.DesignatorList, val)
if lit, ok := f.Index.(IntLit); ok {
if prev == -1 {
// first item - note that we started initializing indexes
prev = 0
} else if prev == lit.Int() {
// this was an old bug in CC where it returned stale indexes
// for items without any index designators
// it looks like it is fixed now, but we keep the workaround just in case
pi++
f.Index = cIntLit(prev+pi, 10)
} else {
// valid index - set previous and reset relative index
prev = lit.Int()
pi = 0
}
}
items = append(items, f)
}
return g.NewCCompLitExpr(
typ,
items,
)
}
func (g *translator) convertInitExpr(d *cc.Initializer) Expr {
switch d.Case {
case cc.InitializerExpr:
return g.convertAssignExpr(d.AssignmentExpression)
case cc.InitializerInitList:
return g.convertInitList(
g.convertTypeRoot(IdentConfig{}, d.Type(), d.Position()),
d.InitializerList,
)
default:
panic(d.Case.String() + " " + d.Position().String())
}
}
func (g *translator) convertEnum(b *cc.Declaration, typ types.Type, d *cc.EnumSpecifier) []CDecl {
if d.EnumeratorList == nil {
return nil
}
if typ == nil {
typ = types.UntypedIntT(g.env.IntSize())
}
vd := &CVarDecl{
Const: true,
Single: false,
CVarSpec: CVarSpec{g: g, Type: typ},
}
var (
autos = 0 // number of implicit inits
values = 0 // number of explicit inits
)
for it := d.EnumeratorList; it != nil; it = it.EnumeratorList {
e := it.Enumerator
if e.Case == cc.EnumeratorExpr {
init := g.convertConstExpr(e.ConstantExpression)
vd.Inits = append(vd.Inits, init)
values++
continue
}
vd.Inits = append(vd.Inits, nil)
autos++
}
if autos == 1 && vd.Inits[0] == nil {
autos--
values++
vd.Inits[0] = cIntLit(0, 10)
}
// use iota if there is only one explicit init (the first one), or no explicit values are set
isIota := (vd.Inits[0] == nil && autos == 1) || autos == len(vd.Inits)
if len(vd.Inits) > 1 && vd.Inits[0] != nil && values == 1 {
if _, ok := cUnwrap(vd.Inits[0]).(IntLit); ok {
isIota = true
values--
autos++
}
}
if len(vd.Inits) != 0 && isIota && values != 0 {
panic("TODO: mixed enums")
}
var next int64
for it, i := d.EnumeratorList, 0; it != nil; it, i = it.EnumeratorList, i+1 {
e := it.Enumerator
if isIota {
if i == 0 {
iot := g.Iota()
if val := vd.Inits[0]; val != nil {
if l, ok := cUnwrap(val).(IntLit); !ok || !l.IsZero() {
iot = &CBinaryExpr{Left: iot, Op: BinOpAdd, Right: val}
}
}
if !typ.Kind().IsUntypedInt() {
iot = &CCastExpr{Type: typ, Expr: iot}
}
vd.Inits[0] = iot
}
} else {
if vd.Inits[i] == nil {
vd.Inits[i] = cIntLit(next, 10)
next++
} else if l, ok := cUnwrap(vd.Inits[i]).(IntLit); ok {
next = l.Int() + 1
}
}
vd.Names = append(vd.Names, g.convertIdentWith(e.Token.Value.String(), typ, e).Ident)
}
if len(vd.Names) == 0 {
return nil
}
if isIota {
vd.Type = nil
}
return []CDecl{vd}
}
func (g *translator) convertTypedefName(d *cc.Declaration) (cc.Token, *cc.Declarator) {
if d.InitDeclaratorList == nil || d.InitDeclaratorList.InitDeclarator == nil {
panic("no decl")
}
if d.InitDeclaratorList.InitDeclaratorList != nil {
panic("should have one decl")
}
id := d.InitDeclaratorList.InitDeclarator
if id.Case != cc.InitDeclaratorDecl {
panic(id.Case.String())
}
dd := id.Declarator
if dd.DirectDeclarator.Case != cc.DirectDeclaratorIdent {
panic(dd.DirectDeclarator.Case)
}
return dd.DirectDeclarator.Token, dd
}
func (g *translator) convertDecl(d *cc.Declaration) []CDecl {
inCur := g.inCurFile(d)
var (
isConst bool
isVolatile bool
isTypedef bool
isStatic bool
isExtern bool
isForward bool
isFunc bool
isPrim bool
isAuto bool
typeSpec types.Type
enumSpec *cc.EnumSpecifier
names []string // used only for the hooks
)
for il := d.InitDeclaratorList; il != nil; il = il.InitDeclaratorList {
id := il.InitDeclarator
switch id.Case {
case cc.InitDeclaratorDecl, cc.InitDeclaratorInit:
dd := id.Declarator
if name := dd.Name().String(); name != "" {
names = append(names, name)
}
}
}
spec := d.DeclarationSpecifiers
if spec != nil && spec.Case == cc.DeclarationSpecifiersStorage &&
spec.StorageClassSpecifier.Case == cc.StorageClassSpecifierTypedef {
isTypedef = true
spec = spec.DeclarationSpecifiers
}
for sp := spec; sp != nil; sp = sp.DeclarationSpecifiers {
switch sp.Case {
case cc.DeclarationSpecifiersTypeQual:
ds := sp.TypeQualifier
switch ds.Case {
case cc.TypeQualifierConst:
isConst = true
case cc.TypeQualifierVolatile:
isVolatile = true
default:
panic(ds.Case.String())
}
case cc.DeclarationSpecifiersStorage:
ds := sp.StorageClassSpecifier
switch ds.Case {
case cc.StorageClassSpecifierStatic:
isStatic = true
case cc.StorageClassSpecifierExtern:
isExtern = true
case cc.StorageClassSpecifierAuto:
isAuto = true
case cc.StorageClassSpecifierRegister:
// ignore
default:
panic(ds.Case.String())
}
if isTypedef {
panic("wrong type")
}
case cc.DeclarationSpecifiersTypeSpec:
ds := sp.TypeSpecifier
switch ds.Case {
case cc.TypeSpecifierStructOrUnion:
su := ds.StructOrUnionSpecifier
var conf IdentConfig
for _, name := range names {
if c, ok := g.idents[name]; ok {
conf = c
break
}
}
switch su.Case {
case cc.StructOrUnionSpecifierTag:
// struct/union forward declaration
isForward = true
typeSpec = g.convertType(conf, su.Type(), d.Position()).(types.Named)
case cc.StructOrUnionSpecifierDef:
// struct/union declaration
if isForward {
panic("already marked as a forward decl")
}
typeSpec = g.convertType(conf, su.Type(), d.Position())
default:
panic(su.Case.String())
}
case cc.TypeSpecifierEnum:
enumSpec = ds.EnumSpecifier
case cc.TypeSpecifierVoid:
isFunc = true
default:
isPrim = true
}
case cc.DeclarationSpecifiersFunc:
isFunc = true
// TODO: use specifiers
default:
panic(sp.Case.String() + " " + sp.Position().String())
}
}
_ = isStatic // FIXME: static
_ = isVolatile
_ = isAuto // FIXME: auto
var decls []CDecl
if enumSpec != nil {
if isForward {
panic("TODO")
}
if isPrim || isFunc {
panic("wrong type")
}
if typeSpec != nil {
panic("should have no type")
}
if !inCur {
return nil
}
var (
typ types.Type
hasOtherDecls = false
)
if isTypedef {
name, dd := g.convertTypedefName(d)
und := g.convertType(IdentConfig{}, dd.Type(), name.Position())
nt := g.newOrFindNamedType(name.Value.String(), func() types.Type {
return und
})
typ = nt
decls = append(decls, &CTypeDef{nt})
} else if d.InitDeclaratorList != nil {
hasOtherDecls = true
} else if name := enumSpec.Token2; name.Value != 0 {
nt := g.newOrFindNamedType(name.Value.String(), func() types.Type {
return g.env.DefIntT()
})
typ = nt
decls = append(decls, &CTypeDef{nt})
}
if !hasOtherDecls {
decls = append(decls, g.convertEnum(d, typ, enumSpec)...)
}
}
if d.InitDeclaratorList == nil || d.InitDeclaratorList.InitDeclarator == nil {
if typeSpec == nil && enumSpec != nil {
return decls
}
if isTypedef && isForward {
panic("wrong type")
}
if isPrim || isFunc {
panic("wrong type")
}
if isForward {
if typeSpec == nil {
panic("no type for forward decl")
}
if !inCur || !g.conf.ForwardDecl {
return nil
}
} else {
if !inCur {
return nil
}
if isTypedef {
panic("TODO")
}
}
nt, ok := typeSpec.(types.Named)
if !ok {
if isForward {
panic("forward declaration of unnamed type")
} else {
panic(fmt.Errorf("declaration of unnamed type: %T", typeSpec))
}
}
decls = append(decls, &CTypeDef{nt})
return decls
}
var (
added = 0
skipped = 0
)
for il := d.InitDeclaratorList; il != nil; il = il.InitDeclaratorList {
id := il.InitDeclarator
switch id.Case {
case cc.InitDeclaratorDecl, cc.InitDeclaratorInit:
dd := id.Declarator
dname := dd.Name().String()
conf := g.idents[dname]
vt := g.convertTypeRootOpt(conf, dd.Type(), id.Position())
if isTypedef && vt == nil {
vt = types.StructT(nil)
}
var init Expr
if id.Initializer != nil && inCur {
if isTypedef {
panic("init in typedef: " + id.Position().String())
}
init = g.convertInitExpr(id.Initializer)
}
if isConst && propagateConst(vt) {
isConst = false
}
if isTypedef {
if enumSpec != nil {
continue
}
nt, ok := vt.(types.Named)
// TODO: this case is "too smart", we already handle those kind of double typedefs on a lower level
if !ok || nt.Name().Name != dd.Name().String() {
// we don't call a *From version of the method here because dd.Type() is an underlying type,
// not a typedef type
if ok && !strings.HasPrefix(nt.Name().Name, "_cxgo_") {
decls = append(decls, &CTypeDef{nt})
}
if vt == nil {
panic("TODO: typedef of void? " + id.Position().String())
}
nt = g.newOrFindNamedTypedef(dd.Name().String(), func() types.Type {
return vt
})
if nt == nil {
// typedef suppressed
skipped++
continue
}
}
decls = append(decls, &CTypeDef{nt})
continue
}
name := g.convertIdentWith(dd.NameTok().String(), vt, dd)
isDecl := false
for di := dd.DirectDeclarator; di != nil; di = di.DirectDeclarator {
if di.Case == cc.DirectDeclaratorDecl {
isDecl = true
break
}
}
if !isDecl && !isForward {
if nt, ok := typeSpec.(types.Named); ok {
decls = append(decls, &CTypeDef{nt})
}
}
if ft, ok := vt.(*types.FuncType); ok && !isDecl {
// forward declaration
if l, id, ok := g.tenv.LibIdentByName(name.Name); ok && id.CType(nil).Kind().IsFunc() {
// forward declaration of stdlib function
// we must first load the corresponding library to the real env
l, ok = g.env.GetLibrary(l.Name)
if !ok {
panic("cannot load stdlib")
}
id, ok = l.Idents[name.Name]
if !ok {
panic("cannot find stdlib ident")
}
g.replaceIdentWith(id, dd)
skipped++
} else if g.conf.ForwardDecl {
decls = append(decls, &CFuncDecl{
Name: name.Ident,
Type: ft,
Body: nil,
})
} else {
skipped++
}
} else {
decls = decls[:len(decls)-added]
if !isExtern {
var inits []Expr
if init != nil {
inits = []Expr{init}
}
decls = append(decls, &CVarDecl{
// There is no real const in C
Const: false, // Const: isConst,
CVarSpec: CVarSpec{
g: g,
Type: vt,
Names: []*types.Ident{name.Ident},
Inits: inits,
},
})
} else {
skipped++
}
}
default:
panic(id.Case.String())
}
}
if !inCur {
return nil
}
if len(decls) == 0 && skipped == 0 {
panic("no declarations converted: " + d.Position().String())
}
return decls
}
func (g *translator) convertCompStmt(d *cc.CompoundStatement) []CStmt {
var stmts []CStmt
for it := d.BlockItemList; it != nil; it = it.BlockItemList {
st := it.BlockItem
switch st.Case {
case cc.BlockItemDecl:
for _, dec := range g.convertDecl(st.Declaration) {
stmts = append(stmts, g.NewCDeclStmt(dec)...)
}
case cc.BlockItemStmt:
stmts = append(stmts, g.convertStmt(st.Statement)...)
default:
panic(st.Case.String())
}
}
// TODO: shouldn't it return statements without a block? or call an optimizing version of block constructor?
return []CStmt{g.newBlockStmt(stmts...)}
}
func (g *translator) convertCompBlockStmt(d *cc.CompoundStatement) *BlockStmt {
stmts := g.convertCompStmt(d)
if len(stmts) == 1 {
if b, ok := stmts[0].(*BlockStmt); ok {
return b
}
}
// TODO: shouldn't it call a version that applies optimizations?
return g.newBlockStmt(stmts...)
}
func (g *translator) convertExpr(d *cc.Expression) Expr {
if d.Expression == nil {
return g.convertAssignExpr(d.AssignmentExpression)
}
var exprs []*cc.AssignmentExpression
for ; d != nil; d = d.Expression {
exprs = append(exprs, d.AssignmentExpression)
}
var m []Expr
for i := len(exprs) - 1; i >= 0; i-- {
m = append(m, g.convertAssignExpr(exprs[i]))
}
return g.NewCMultiExpr(m...)
}
func (g *translator) convertExprOpt(d *cc.Expression) Expr {
if d == nil {
return nil
}
return g.convertExpr(d)
}
func (g *translator) convertMulExpr(d *cc.MultiplicativeExpression) Expr {
switch d.Case {
case cc.MultiplicativeExpressionCast:
return g.convertCastExpr(d.CastExpression)
}
x := g.convertMulExpr(d.MultiplicativeExpression)
y := g.convertCastExpr(d.CastExpression)
var op BinaryOp
switch d.Case {
case cc.MultiplicativeExpressionMul:
op = BinOpMult
case cc.MultiplicativeExpressionDiv:
op = BinOpDiv
case cc.MultiplicativeExpressionMod:
op = BinOpMod
default:
panic(d.Case.String())
}
return g.NewCBinaryExprT(
x, op, y,
g.convertTypeOper(d.Operand, d.Position()),
)
}
func (g *translator) convertAddExpr(d *cc.AdditiveExpression) Expr {
switch d.Case {
case cc.AdditiveExpressionMul:
return g.convertMulExpr(d.MultiplicativeExpression)
}
x := g.convertAddExpr(d.AdditiveExpression)
y := g.convertMulExpr(d.MultiplicativeExpression)
var op BinaryOp
switch d.Case {
case cc.AdditiveExpressionAdd:
op = BinOpAdd
case cc.AdditiveExpressionSub:
op = BinOpSub
default:
panic(d.Case.String())
}
return g.NewCBinaryExprT(
x, op, y,
g.convertTypeOper(d.Operand, d.Position()),
)
}
func (g *translator) convertShiftExpr(d *cc.ShiftExpression) Expr {
switch d.Case {
case cc.ShiftExpressionAdd:
return g.convertAddExpr(d.AdditiveExpression)
}
x := g.convertShiftExpr(d.ShiftExpression)
y := g.convertAddExpr(d.AdditiveExpression)
var op BinaryOp
switch d.Case {
case cc.ShiftExpressionLsh:
op = BinOpLsh
case cc.ShiftExpressionRsh:
op = BinOpRsh
default:
panic(d.Case.String())
}
return g.NewCBinaryExprT(
x, op, y,
g.convertTypeOper(d.Operand, d.Position()),
)
}
func (g *translator) convertRelExpr(d *cc.RelationalExpression) Expr {
switch d.Case {
case cc.RelationalExpressionShift:
return g.convertShiftExpr(d.ShiftExpression)
}
x := g.convertRelExpr(d.RelationalExpression)
y := g.convertShiftExpr(d.ShiftExpression)
var op ComparisonOp
switch d.Case {
case cc.RelationalExpressionLt:
op = BinOpLt
case cc.RelationalExpressionGt:
op = BinOpGt
case cc.RelationalExpressionLeq:
op = BinOpLte
case cc.RelationalExpressionGeq:
op = BinOpGte
default:
panic(d.Case.String())
}
return g.Compare(x, op, y)
}
func (g *translator) convertEqExpr(d *cc.EqualityExpression) Expr {
switch d.Case {
case cc.EqualityExpressionRel:
return g.convertRelExpr(d.RelationalExpression)
}
x := g.convertEqExpr(d.EqualityExpression)
y := g.convertRelExpr(d.RelationalExpression)
var op ComparisonOp
switch d.Case {
case cc.EqualityExpressionEq:
op = BinOpEq
case cc.EqualityExpressionNeq:
op = BinOpNeq
default:
panic(d.Case.String())
}
return g.Compare(x, op, y)
}
func (g *translator) convertAndExpr(d *cc.AndExpression) Expr {
switch d.Case {
case cc.AndExpressionEq:
return g.convertEqExpr(d.EqualityExpression)
case cc.AndExpressionAnd:
x := g.convertAndExpr(d.AndExpression)
y := g.convertEqExpr(d.EqualityExpression)
return g.NewCBinaryExprT(
x, BinOpBitAnd, y,
g.convertTypeOper(d.Operand, d.Position()),
)
default:
panic(d.Case.String())
}
}
func (g *translator) convertLOrExcExpr(d *cc.ExclusiveOrExpression) Expr {
switch d.Case {
case cc.ExclusiveOrExpressionAnd:
return g.convertAndExpr(d.AndExpression)
case cc.ExclusiveOrExpressionXor:
x := g.convertLOrExcExpr(d.ExclusiveOrExpression)
y := g.convertAndExpr(d.AndExpression)
return g.NewCBinaryExprT(
x, BinOpBitXor, y,
g.convertTypeOper(d.Operand, d.Position()),
)
default:
panic(d.Case.String())
}
}
func (g *translator) convertLOrIncExpr(d *cc.InclusiveOrExpression) Expr {
switch d.Case {
case cc.InclusiveOrExpressionXor:
return g.convertLOrExcExpr(d.ExclusiveOrExpression)
case cc.InclusiveOrExpressionOr:
x := g.convertLOrIncExpr(d.InclusiveOrExpression)
y := g.convertLOrExcExpr(d.ExclusiveOrExpression)
return g.NewCBinaryExprT(
x, BinOpBitOr, y,
g.convertTypeOper(d.Operand, d.Position()),
)
default:
panic(d.Case.String())
}
}
func (g *translator) convertLAndExpr(d *cc.LogicalAndExpression) Expr {
switch d.Case {
case cc.LogicalAndExpressionOr:
return g.convertLOrIncExpr(d.InclusiveOrExpression)
case cc.LogicalAndExpressionLAnd:
x := g.convertLAndExpr(d.LogicalAndExpression)
y := g.convertLOrIncExpr(d.InclusiveOrExpression)
return And(g.ToBool(x), g.ToBool(y))
default:
panic(d.Case.String())
}
}
func (g *translator) convertLOrExpr(d *cc.LogicalOrExpression) Expr {
switch d.Case {
case cc.LogicalOrExpressionLAnd:
return g.convertLAndExpr(d.LogicalAndExpression)
case cc.LogicalOrExpressionLOr:
x := g.convertLOrExpr(d.LogicalOrExpression)
y := g.convertLAndExpr(d.LogicalAndExpression)
return Or(g.ToBool(x), g.ToBool(y))
default:
panic(d.Case.String())
}
}
func (g *translator) convertCondExpr(d *cc.ConditionalExpression) Expr {
switch d.Case {
case cc.ConditionalExpressionLOr:
return g.convertLOrExpr(d.LogicalOrExpression)
case cc.ConditionalExpressionCond:
cond := g.convertLOrExpr(d.LogicalOrExpression)
return g.NewCTernaryExpr(
g.ToBool(cond),
g.convertExpr(d.Expression),
g.convertCondExpr(d.ConditionalExpression),
)
default:
panic(d.Case.String())
}
}
func (g *translator) convertPriExpr(d *cc.PrimaryExpression) Expr {
switch d.Case {
case cc.PrimaryExpressionIdent: // x
if d.Token.String() == "asm" {
return &CAsmExpr{e: g.env.Env}
}
if d.Operand == nil {
panic(ErrorfWithPos(d.Position(), "empty operand for %q", d.Token.String()))
}
return g.convertIdent(d.ResolvedIn(), d.Token, g.convertTypeOper(d.Operand, d.Position()))
case cc.PrimaryExpressionEnum: // X
return g.convertIdent(d.ResolvedIn(), d.Token, g.convertTypeOper(d.Operand, d.Position()))
case cc.PrimaryExpressionInt: // 1
fnc := func() Expr {
v, err := parseCIntLit(d.Token.String(), g.conf.IntReformat)
if err != nil {
panic(err)
}
return v
}
if m := d.Token.Macro(); m != 0 {
return g.convMacro(m.String(), fnc)
}
return fnc()
case cc.PrimaryExpressionFloat: // 0.0
fnc := func() Expr {
v, err := parseCFloatLit(d.Token.String())
if err != nil {
panic(err)
}
if d.Operand == nil {
return v
}
return g.cCast(
g.convertTypeOper(d.Operand, d.Position()),
v,
)
}
if m := d.Token.Macro(); m != 0 {
return g.convMacro(m.String(), fnc)
}
return fnc()
case cc.PrimaryExpressionChar: // 'x'
fnc := func() Expr {
return cLitT(
d.Token.String(), CLitChar,
g.convertTypeOper(d.Operand, d.Position()),
)
}
if m := d.Token.Macro(); m != 0 {
return g.convMacro(m.String(), fnc)
}
return fnc()
case cc.PrimaryExpressionLChar: // 'x'
fnc := func() Expr {
return cLitT(
d.Token.String(), CLitWChar,
g.convertTypeOper(d.Operand, d.Position()),
)
}
if m := d.Token.Macro(); m != 0 {
return g.convMacro(m.String(), fnc)
}
return fnc()
case cc.PrimaryExpressionString: // "x"
fnc := func() Expr {
v, err := g.parseCStringLit(d.Token.String())
if err != nil {
panic(err)
}
return v
}
if m := d.Token.Macro(); m != 0 {
return g.convMacro(m.String(), fnc)
}
return fnc()
case cc.PrimaryExpressionLString: // L"x"
fnc := func() Expr {
v, err := g.parseCWStringLit(d.Token.String())
if err != nil {
panic(err)
}
return v
}
if m := d.Token.Macro(); m != 0 {
return g.convMacro(m.String(), fnc)
}
return fnc()
case cc.PrimaryExpressionExpr: // "(x)"
e := g.convertExpr(d.Expression)
return cParen(e)
case cc.PrimaryExpressionStmt: // "({...; x})"
stmt := g.convertCompStmt(d.CompoundStatement)
if len(stmt) != 1 {
panic("TODO")
}
stmt = stmt[0].(*BlockStmt).Stmts
last, ok := stmt[len(stmt)-1].(*CExprStmt)
if !ok {
// let it cause a compilation error in Go
return &CallExpr{
Fun: g.NewFuncLit(g.env.FuncTT(g.env.DefIntT()), stmt...),
}
}
typ := last.Expr.CType(nil)
stmt = append(stmt[:len(stmt)-1], g.NewReturnStmt(last.Expr, typ)...)
return &CallExpr{
Fun: g.NewFuncLit(g.env.FuncTT(typ), stmt...),
}
default:
panic(fmt.Errorf("%v (%v)", d.Case, d.Position()))
}
}
func (g *translator) convertOneDesignator(typ types.Type, list *cc.DesignatorList, val Expr) *CompLitField {
d := list.Designator
var (
f *CompLitField
sub types.Type
)
switch d.Case {
case cc.DesignatorIndex:
f = &CompLitField{Index: g.convertConstExpr(d.ConstantExpression)}
sub = typ.(types.ArrayType).Elem()
case cc.DesignatorField:
f = &CompLitField{Field: g.convertIdentOn(typ, d.Token2)}
sub = f.Field.CType(nil)
case cc.DesignatorField2:
f = &CompLitField{Field: g.convertIdentOn(typ, d.Token)}
sub = f.Field.CType(nil)
default:
panic(d.Case.String() + " " + d.Position().String())
}
if list.DesignatorList == nil {
f.Value = val
return f
}
f2 := g.convertOneDesignator(sub, list.DesignatorList, val)
f.Value = g.NewCCompLitExpr(sub, []*CompLitField{f2})