forked from rsc/c2go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
syntax.go
668 lines (606 loc) · 15.4 KB
/
syntax.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
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"fmt"
"rsc.io/c2go/cc"
)
var numRewrite int
// Rewrite from C constructs to Go constructs.
func rewriteSyntax(cfg *Config, prog *cc.Prog) {
numRewrite++
cc.Preorder(prog, func(x cc.Syntax) {
switch x := x.(type) {
case *cc.Stmt:
rewriteStmt(x)
case *cc.Expr:
switch x.Op {
case cc.Name:
switch x.Text {
case "nil":
x.XDecl = nil // just nil, not main.Nil
case "nelem":
x.Text = "len"
x.XDecl = nil
}
case cc.Number:
// Rewrite char literal.
// In general we'd need to rewrite all string and char literals
// but these are the only forms that comes up.
switch x.Text {
case `'\0'`:
x.Text = `'\x00'`
case `'\"'`:
x.Text = `'"'`
}
case cc.Paren:
switch x.Left.Op {
case cc.Number, cc.Name:
fixMerge(x, x.Left)
}
case cc.OrEq, cc.AndEq, cc.Or, cc.Eq, cc.EqEq, cc.NotEq, cc.LtEq, cc.GtEq, cc.Lt, cc.Gt:
cutParen(x, cc.Or, cc.And, cc.Lsh, cc.Rsh)
}
case *cc.Type:
// Rewrite int f(void) to int f().
if x.Kind == cc.Func && len(x.Decls) == 1 && x.Decls[0].Name == "" && x.Decls[0].Type.Is(cc.Void) {
x.Decls = nil
}
}
})
// Apply changed struct tags to typedefs.
// Excise dead pieces.
cc.Postorder(prog, func(x cc.Syntax) {
switch x := x.(type) {
case *cc.Type:
if x.Kind == cc.TypedefType && x.Base != nil && x.Base.Tag != "" {
x.Name = x.Base.Tag
}
case *cc.Stmt:
if x.Op == cc.StmtExpr && x.Expr.Op == cc.Comma && len(x.Expr.List) == 0 {
x.Op = cc.Empty
}
x.Block = filterBlock(x.Block)
case *cc.Expr:
if x.Op == ExprBlock {
x.Block = filterBlock(x.Block)
}
switch x.Op {
case cc.Add, cc.Sub:
// Turn p + y - z, which is really (p + y) - z, into p + (y - z),
// so that there is only one pointer addition (which will turn into
// a slice operation using y-z as the index).
if x.XType != nil && x.XType.Kind == cc.Ptr {
switch x.Left.Op {
case cc.Add, cc.Sub:
if x.Left.XType != nil && x.Left.XType.Kind == cc.Ptr {
p, op1, y, op2, z := x.Left.Left, x.Left.Op, x.Left.Right, x.Op, x.Right
if op1 == cc.Sub {
y = &cc.Expr{Op: cc.Minus, Left: y, XType: y.XType}
}
x.Op = cc.Add
x.Left = p
x.Right = &cc.Expr{Op: op2, Left: y, Right: z, XType: x.XType}
}
}
}
}
// Turn c + p - q, which is really (c + p) - q, into c + (p - q),
// so that there is no int + ptr addition, only a ptr - ptr subtraction.
if x.Op == cc.Sub && x.Left.Op == cc.Add && !isPtrOrArray(x.XType) && isPtrOrArray(x.Left.XType) && !isPtrOrArray(x.Left.Left.XType) {
c, p, q := x.Left.Left, x.Left.Right, x.Right
expr := x.Left
expr.Left = p
expr.Right = q
expr.Op = cc.Sub
x.Op = cc.Add
x.Left = c
x.Right = expr
expr.XType = x.XType
}
}
})
}
func cutParen(x *cc.Expr, ops ...cc.ExprOp) {
if x.Left != nil && x.Left.Op == cc.Paren {
for _, op := range ops {
if x.Left.Left.Op == op {
fixMerge(x.Left, x.Left.Left)
break
}
}
}
if x.Right != nil && x.Right.Op == cc.Paren {
for _, op := range ops {
if x.Right.Left.Op == op {
fixMerge(x.Right, x.Right.Left)
break
}
}
}
}
func isPtrOrArray(t *cc.Type) bool {
return t != nil && (t.Kind == cc.Ptr || t.Kind == cc.Array)
}
func filterBlock(x []*cc.Stmt) []*cc.Stmt {
all := x[:0]
for _, stmt := range x {
if stmt.Op != cc.Empty || len(stmt.Comments.Before)+len(stmt.Comments.After)+len(stmt.Labels) > 0 {
all = append(all, stmt)
}
}
return all
}
func rewriteStmt(stmt *cc.Stmt) {
// TODO: Double-check stmt.Labels
switch stmt.Op {
case cc.ARGBEGIN:
panic(fmt.Sprintf("unexpected ARGBEGIN"))
case cc.Do:
// Rewrite do { ... } while(x)
// to for(;;) { ... if(!x) break }
// Since rewriteStmt is called in a preorder traversal,
// the recursion into the children will clean up x
// in the if condition as needed.
stmt.Op = cc.For
x := stmt.Expr
stmt.Expr = nil
stmt.Body = forceBlock(stmt.Body)
stmt.Body.Block = append(stmt.Body.Block, &cc.Stmt{
Op: cc.If,
Expr: &cc.Expr{Op: cc.Not, Left: x},
Body: &cc.Stmt{Op: cc.Break},
})
case cc.While:
stmt.Op = cc.For
fallthrough
case cc.For:
before1, _ := extractSideEffects(stmt.Pre, sideStmt|sideNoAfter)
before2, _ := extractSideEffects(stmt.Expr, sideNoAfter)
if len(before2) > 0 {
x := stmt.Expr
stmt.Expr = nil
stmt.Body = forceBlock(stmt.Body)
top := &cc.Stmt{
Op: cc.If,
Expr: &cc.Expr{Op: cc.Not, Left: x},
Body: &cc.Stmt{Op: cc.Break},
}
stmt.Body.Block = append(append(before2, top), stmt.Body.Block...)
}
if len(before1) > 0 {
old := copyStmt(stmt)
stmt.Pre = nil
stmt.Expr = nil
stmt.Post = nil
stmt.Body = nil
stmt.Op = BlockNoBrace
stmt.Block = append(before1, old)
}
before, after := extractSideEffects(stmt.Post, sideStmt)
if len(before)+len(after) > 0 {
all := append(append(before, &cc.Stmt{Op: cc.StmtExpr, Expr: stmt.Post}), after...)
stmt.Post = &cc.Expr{Op: ExprBlock, Block: all}
}
case cc.If, cc.Return:
if stmt.Op == cc.If && stmt.Else == nil {
fixAndAndAssign(stmt)
}
before, _ := extractSideEffects(stmt.Expr, sideNoAfter)
if len(before) > 0 {
old := copyStmt(stmt)
stmt.Expr = nil
stmt.Body = nil
stmt.Else = nil
stmt.Op = BlockNoBrace
stmt.Block = append(before, old)
}
case cc.StmtExpr:
before, after := extractSideEffects(stmt.Expr, sideStmt)
if len(before)+len(after) > 0 {
old := copyStmt(stmt)
stmt.Expr = nil
stmt.Op = BlockNoBrace
stmt.Block = append(append(before, old), after...)
}
case cc.Goto:
// TODO: Figure out where the goto goes and maybe rewrite
// to labeled break/continue.
// Otherwise move code or something.
case cc.Switch:
// TODO: Change default fallthrough to default break.
before, _ := extractSideEffects(stmt.Expr, sideNoAfter)
if len(before) > 0 {
old := copyStmt(stmt)
stmt.Expr = nil
stmt.Body = nil
stmt.Else = nil
stmt.Op = BlockNoBrace
stmt.Block = append(before, old)
break // recursion will rewrite new inner switch
}
rewriteSwitch(stmt)
}
}
// fixAndAndAssign rewrites if(x && (y = z) ...) ... to if(x) { y = z; if(...) ... }
func fixAndAndAssign(stmt *cc.Stmt) {
changed := false
clauses := splitExpr(stmt.Expr, cc.AndAnd)
for i := len(clauses) - 1; i > 0; i-- {
before, _ := extractSideEffects(clauses[i], sideNoAfter)
if len(before) == 0 {
continue
}
changed = true
stmt.Body = &cc.Stmt{
Op: BlockNoBrace,
Block: append(before, &cc.Stmt{
Op: cc.If,
Expr: joinExpr(clauses[i:], cc.AndAnd),
Body: stmt.Body,
}),
}
clauses = clauses[:i]
}
if changed {
stmt.Expr = joinExpr(clauses, cc.AndAnd)
}
}
func splitExpr(x *cc.Expr, op cc.ExprOp) []*cc.Expr {
if x == nil {
return nil
}
var list []*cc.Expr
for x.Op == op {
list = append(list, x.Right)
x = x.Left
}
list = append(list, x)
for i, j := 0, len(list)-1; i < j; i, j = i+1, j-1 {
list[i], list[j] = list[j], list[i]
}
return list
}
func joinExpr(list []*cc.Expr, op cc.ExprOp) *cc.Expr {
if len(list) == 0 {
return nil
}
x := list[0]
for _, y := range list[1:] {
x = &cc.Expr{Op: op, Left: x, Right: y}
}
return x
}
func rewriteSwitch(swt *cc.Stmt) {
if numRewrite != 1 {
return
}
var out []*cc.Stmt
for _, stmt := range swt.Body.Block {
// Put names after cases, so that they go to the same place.
var names, cases []*cc.Label
var def *cc.Label
for _, lab := range stmt.Labels {
if lab.Op == cc.LabelName {
names = append(names, lab)
} else if lab.Op == cc.Default {
def = lab
} else {
cases = append(cases, lab)
}
}
if def != nil {
cases = append(cases, def) // put default last for printing
}
if len(cases) > 0 && len(names) > 0 {
stmt.Labels = append(cases, names...)
}
if len(cases) > 0 {
// Remove break or add fallthrough if needed.
if len(out) > 0 {
last := out[len(out)-1]
if last.Op == cc.Break && len(last.Labels) == 0 {
last.Op = cc.Empty
} else if fallsThrough(last) {
out = append(out, &cc.Stmt{Op: cc.StmtExpr, Expr: &cc.Expr{Op: cc.Name, Text: "fallthrough"}})
}
}
}
out = append(out, stmt)
}
// Remove final break.
if len(out) > 0 {
last := out[len(out)-1]
if last.Op == cc.Break && len(last.Labels) == 0 {
last.Op = cc.Empty
}
}
swt.Body.Block = out
}
func fallsThrough(x *cc.Stmt) bool {
switch x.Op {
case cc.Break, cc.Continue, cc.Return, cc.Goto:
return false
case cc.StmtExpr:
if x.Expr.Op == cc.Call && x.Expr.Left.Op == cc.Name && (x.Expr.Left.Text == "sysfatal" || x.Expr.Left.Text == "fatal") {
return false
}
if x.Expr.Op == cc.Name && x.Expr.Text == "fallthrough" {
return false
}
}
return true
}
func forceBlock(x *cc.Stmt) *cc.Stmt {
if x.Op != cc.Block {
x = &cc.Stmt{Op: cc.Block, Block: []*cc.Stmt{x}}
}
return x
}
const (
sideStmt = 1 << iota
sideNoAfter
)
func extractSideEffects(x *cc.Expr, mode int) (before, after []*cc.Stmt) {
doSideEffects(x, &before, &after, mode)
return
}
var tmpGen = make(chan int)
func init() {
go func() {
for i := 1; ; i++ {
tmpGen <- i
}
}()
}
func doSideEffects(x *cc.Expr, before, after *[]*cc.Stmt, mode int) {
if x == nil {
return
}
// Cannot hoist side effects from conditionally evaluated expressions
// into unconditionally evaluated statement lists.
// For now, detect but do not handle.
switch x.Op {
case cc.Cond:
doSideEffects(x.List[0], before, after, mode&^sideStmt|sideNoAfter)
checkNoSideEffects(x.List[1], 0)
checkNoSideEffects(x.List[2], 0)
case cc.AndAnd, cc.OrOr:
doSideEffects(x.Left, before, after, mode&^sideStmt|sideNoAfter)
checkNoSideEffects(x.Right, 0)
case cc.Comma:
var leftover []*cc.Expr
for i, y := range x.List {
m := mode | sideNoAfter
if i+1 < len(x.List) {
m |= sideStmt
}
doSideEffects(y, before, after, m)
switch y.Op {
case cc.PostInc, cc.PostDec, cc.Eq, cc.AddEq, cc.SubEq, cc.MulEq, cc.DivEq, cc.ModEq, cc.XorEq, cc.OrEq, cc.AndEq, cc.LshEq, cc.RshEq:
*before = append(*before, &cc.Stmt{Op: cc.StmtExpr, Expr: y})
default:
leftover = append(leftover, y)
}
}
x.List = leftover
default:
doSideEffects(x.Left, before, after, mode&^sideStmt)
doSideEffects(x.Right, before, after, mode&^sideStmt)
for _, y := range x.List {
doSideEffects(y, before, after, mode&^sideStmt)
}
}
if mode&sideStmt != 0 {
// Expression as statement.
// Can leave x++ alone, can rewrite ++x to x++, can leave x [op]= y alone.
switch x.Op {
case cc.PreInc:
x.Op = cc.PostInc
return
case cc.PreDec:
x.Op = cc.PostDec
return
case cc.PostInc, cc.PostDec:
return
case cc.Eq, cc.AddEq, cc.SubEq, cc.MulEq, cc.DivEq, cc.ModEq, cc.XorEq, cc.OrEq, cc.AndEq, cc.LshEq, cc.RshEq:
return
case cc.Call:
return
}
}
switch x.Op {
case cc.Eq, cc.AddEq, cc.SubEq, cc.MulEq, cc.DivEq, cc.ModEq, cc.XorEq, cc.OrEq, cc.AndEq, cc.LshEq, cc.RshEq:
x.Left = forceCheap(before, x.Left)
old := copyExpr(x)
*before = append(*before, &cc.Stmt{Op: cc.StmtExpr, Expr: old})
fixMerge(x, x.Left)
case cc.PreInc, cc.PreDec:
x.Left = forceCheap(before, x.Left)
old := copyExpr(x)
old.SyntaxInfo = cc.SyntaxInfo{}
if old.Op == cc.PreInc {
old.Op = cc.PostInc
} else {
old.Op = cc.PostDec
}
*before = append(*before, &cc.Stmt{Op: cc.StmtExpr, Expr: old})
fixMerge(x, x.Left)
case cc.PostInc, cc.PostDec:
x.Left = forceCheap(before, x.Left)
if mode&sideNoAfter != 0 {
// Not allowed to generate fixups afterward.
d := &cc.Decl{
Name: fmt.Sprintf("tmp%d", <-tmpGen),
Type: x.Left.XType,
}
eq := &cc.Expr{
Op: ColonEq,
Left: &cc.Expr{Op: cc.Name, Text: d.Name, XDecl: d},
Right: x.Left,
}
old := copyExpr(x.Left)
old.SyntaxInfo = cc.SyntaxInfo{}
*before = append(*before,
&cc.Stmt{Op: cc.StmtExpr, Expr: eq},
&cc.Stmt{Op: cc.StmtExpr, Expr: &cc.Expr{Op: x.Op, Left: old}},
)
x.Op = cc.Name
x.Text = d.Name
x.XDecl = d
x.Left = nil
break
}
old := copyExpr(x)
old.SyntaxInfo = cc.SyntaxInfo{}
*after = append(*after, &cc.Stmt{Op: cc.StmtExpr, Expr: old})
fixMerge(x, x.Left)
case cc.Cond:
// Rewrite c ? y : z into tmp with initialization:
// var tmp typeof(c?y:z)
// if c {
// tmp = y
// } else {
// tmp = z
// }
d := &cc.Decl{
Name: "tmp",
Type: x.XType,
}
*before = append(*before,
&cc.Stmt{Op: cc.StmtDecl, Decl: d},
&cc.Stmt{Op: cc.If, Expr: x.List[0],
Body: &cc.Stmt{
Op: cc.StmtExpr,
Expr: &cc.Expr{
Op: cc.Eq,
Left: &cc.Expr{Op: cc.Name, Text: d.Name, XDecl: d},
Right: x.List[1],
},
},
Else: &cc.Stmt{
Op: cc.StmtExpr,
Expr: &cc.Expr{
Op: cc.Eq,
Left: &cc.Expr{Op: cc.Name, Text: d.Name, XDecl: d},
Right: x.List[2],
},
},
},
)
x.Op = cc.Name
x.Text = d.Name
x.XDecl = d
x.List = nil
case cc.Call:
if x.Left.Text == "fmtstrcpy" || x.Left.Text == "fmtprint" {
old := copyExpr(x)
old.SyntaxInfo = cc.SyntaxInfo{}
*before = append(*before, &cc.Stmt{Op: cc.StmtExpr, Expr: old})
x.Op = cc.Number
x.Text = "0"
x.XDecl = nil
x.Left = nil
x.List = nil
}
}
}
func copyExpr(x *cc.Expr) *cc.Expr {
old := *x
old.SyntaxInfo = cc.SyntaxInfo{}
return &old
}
func copyStmt(x *cc.Stmt) *cc.Stmt {
old := *x
old.SyntaxInfo = cc.SyntaxInfo{}
old.Labels = nil
return &old
}
func forceCheap(before *[]*cc.Stmt, x *cc.Expr) *cc.Expr {
// TODO
return x
}
func fixMerge(dst, src *cc.Expr) {
syn := dst.SyntaxInfo
syn.Comments.Before = append(syn.Comments.Before, src.Comments.Before...)
syn.Comments.After = append(syn.Comments.After, src.Comments.After...)
syn.Comments.Suffix = append(syn.Comments.Suffix, src.Comments.Suffix...)
*dst = *src
dst.SyntaxInfo = syn
}
func checkNoSideEffects(x *cc.Expr, mode int) {
var before, after []*cc.Stmt
old := x.String()
doSideEffects(x, &before, &after, mode)
if len(before)+len(after) > 0 {
fprintf(x.Span, "cannot handle side effects in %s", old)
}
}
// Apply DeMorgan's law and invert comparisons
// to simplify negation of boolean expressions.
func simplifyBool(cfg *Config, prog *cc.Prog) {
cc.Preorder(prog, func(x cc.Syntax) {
switch x := x.(type) {
case *cc.Expr:
switch x.Op {
case cc.Not:
y := x.Left
for y.Op == cc.Paren {
y = y.Left
}
switch y.Op {
case cc.AndAnd:
*x = *y
x.Left = &cc.Expr{Op: cc.Not, Left: x.Left}
x.Right = &cc.Expr{Op: cc.Not, Left: x.Right}
x.Op = cc.OrOr
case cc.OrOr:
*x = *y
x.Left = &cc.Expr{Op: cc.Not, Left: x.Left}
x.Right = &cc.Expr{Op: cc.Not, Left: x.Right}
x.Op = cc.AndAnd
case cc.EqEq:
if isfloat(x.Left.XType) {
break
}
*x = *y
x.Op = cc.NotEq
case cc.NotEq:
if isfloat(x.Left.XType) {
break
}
*x = *y
x.Op = cc.EqEq
case cc.Lt:
if isfloat(x.Left.XType) {
break
}
*x = *y
x.Op = cc.GtEq
case cc.LtEq:
if isfloat(x.Left.XType) {
break
}
*x = *y
x.Op = cc.Gt
case cc.Gt:
if isfloat(x.Left.XType) {
break
}
*x = *y
x.Op = cc.LtEq
case cc.GtEq:
if isfloat(x.Left.XType) {
break
}
*x = *y
x.Op = cc.Lt
}
}
}
})
}
func isfloat(t *cc.Type) bool {
return t != nil && (t.Kind == Float32 || t.Kind == Float64)
}