-
Notifications
You must be signed in to change notification settings - Fork 159
/
transpiler.go
424 lines (353 loc) · 10.4 KB
/
transpiler.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
// Package transpiler handles the conversion between the Clang AST and the Go
// AST.
package transpiler
import (
"errors"
"fmt"
goast "go/ast"
"go/parser"
"go/token"
"strings"
"github.com/elliotchance/c2go/ast"
"github.com/elliotchance/c2go/program"
"github.com/elliotchance/c2go/types"
"github.com/elliotchance/c2go/util"
)
// TranspileAST iterates through the Clang AST and builds a Go AST
func TranspileAST(fileName, packageName string, p *program.Program, root ast.Node) error {
// Start by parsing an empty file.
p.FileSet = token.NewFileSet()
packageSignature := fmt.Sprintf("package %v", packageName)
f, err := parser.ParseFile(p.FileSet, fileName, packageSignature, 0)
p.File = f
if err != nil {
return err
}
// Now begin building the Go AST.
err = transpileToNode(root, p)
if p.OutputAsTest {
p.AddImport("testing")
p.AddImport("io/ioutil")
p.AddImport("os")
// TODO: There should be a cleaner way to add a function to the program.
// This code was taken from the end of transpileFunctionDecl.
p.File.Decls = append(p.File.Decls, &goast.FuncDecl{
Name: util.NewIdent("TestApp"),
Type: &goast.FuncType{
Params: &goast.FieldList{
List: []*goast.Field{
&goast.Field{
Names: []*goast.Ident{util.NewIdent("t")},
Type: util.NewTypeIdent("*testing.T"),
},
},
},
},
Body: &goast.BlockStmt{
List: []goast.Stmt{
util.NewExprStmt(&goast.Ident{Name: "os.Chdir(\"../../..\")"}),
// "go test" does not redirect stdin to the executable
// running the test so we need to override them in the test
// itself. See documentation for noarch.Stdin.
util.NewExprStmt(&goast.Ident{Name: "ioutil.WriteFile(\"build/stdin\", []byte{'7'}, 0777)"}),
util.NewExprStmt(
&goast.Ident{Name: "stdin, _ := os.Open(\"build/stdin\")"},
),
util.NewExprStmt(util.NewBinaryExpr(
&goast.Ident{Name: "noarch.Stdin"},
token.ASSIGN,
&goast.Ident{Name: "noarch.NewFile(stdin)"},
"*noarch.File",
true,
)),
util.NewExprStmt(util.NewCallExpr("main")),
},
},
})
}
// Now we need to build the __init() function. This sets up certain state
// and variables that the runtime expects to be ready.
p.File.Decls = append(p.File.Decls, &goast.FuncDecl{
Name: util.NewIdent("__init"),
Type: util.NewFuncType(&goast.FieldList{}, ""),
Body: &goast.BlockStmt{
List: p.StartupStatements(),
},
})
// Add the imports after everything else so we can ensure that they are all
// placed at the top.
for _, quotedImportPath := range p.Imports() {
importSpec := &goast.ImportSpec{
Path: &goast.BasicLit{
Kind: token.IMPORT,
Value: quotedImportPath,
},
}
importDecl := &goast.GenDecl{
Tok: token.IMPORT,
}
importDecl.Specs = append(importDecl.Specs, importSpec)
p.File.Decls = append([]goast.Decl{importDecl}, p.File.Decls...)
}
return err
}
func transpileToExpr(node ast.Node, p *program.Program, exprIsStmt bool) (
expr goast.Expr,
exprType string,
preStmts []goast.Stmt,
postStmts []goast.Stmt,
err error) {
if node == nil {
panic(node)
}
switch n := node.(type) {
case *ast.StringLiteral:
expr = transpileStringLiteral(n)
exprType = "const char *"
case *ast.FloatingLiteral:
expr = transpileFloatingLiteral(n)
exprType = "double"
case *ast.PredefinedExpr:
expr, exprType, err = transpilePredefinedExpr(n, p)
case *ast.ConditionalOperator:
expr, exprType, preStmts, postStmts, err = transpileConditionalOperator(n, p)
case *ast.ArraySubscriptExpr:
expr, exprType, preStmts, postStmts, err = transpileArraySubscriptExpr(n, p)
case *ast.BinaryOperator:
expr, exprType, preStmts, postStmts, err = transpileBinaryOperator(n, p, exprIsStmt)
case *ast.UnaryOperator:
expr, exprType, preStmts, postStmts, err = transpileUnaryOperator(n, p)
case *ast.MemberExpr:
expr, exprType, preStmts, postStmts, err = transpileMemberExpr(n, p)
case *ast.ImplicitCastExpr:
if strings.Contains(n.Type, "enum") {
if d, ok := n.Children()[0].(*ast.DeclRefExpr); ok {
expr, exprType, err = util.NewIdent(d.Name), n.Type, nil
return
}
}
expr, exprType, preStmts, postStmts, err = transpileToExpr(n.Children()[0], p, exprIsStmt)
case *ast.DeclRefExpr:
if n.For == "EnumConstant" {
// clang don`t show enum constant with enum type,
// so we have to use hack for repair the type
if v, ok := p.EnumConstantToEnum[n.Name]; ok {
expr, exprType, err = util.NewIdent(n.Name), v, nil
return
}
}
expr, exprType, err = transpileDeclRefExpr(n, p)
case *ast.IntegerLiteral:
expr, exprType, err = transpileIntegerLiteral(n), "int", nil
case *ast.ParenExpr:
expr, exprType, preStmts, postStmts, err = transpileParenExpr(n, p)
case *ast.CStyleCastExpr:
expr, exprType, preStmts, postStmts, err = transpileToExpr(n.Children()[0], p, exprIsStmt)
if err == nil {
expr, err = types.CastExpr(p, expr, exprType, n.Type)
}
case *ast.CharacterLiteral:
expr, exprType, err = transpileCharacterLiteral(n), "char", nil
case *ast.CallExpr:
expr, exprType, preStmts, postStmts, err = transpileCallExpr(n, p)
case *ast.CompoundAssignOperator:
return transpileCompoundAssignOperator(n, p, exprIsStmt)
case *ast.UnaryExprOrTypeTraitExpr:
return transpileUnaryExprOrTypeTraitExpr(n, p)
case *ast.InitListExpr:
expr, exprType, err = transpileInitListExpr(n, p)
case *ast.CompoundLiteralExpr:
expr, exprType, err = transpileCompoundLiteralExpr(n, p)
case *ast.StmtExpr:
return transpileStmtExpr(n, p)
default:
p.AddMessage(p.GenerateWarningMessage(errors.New("cannot transpile to expr"), node))
expr = util.NewNil()
}
// Real return is through named arguments.
return
}
func transpileToStmts(node ast.Node, p *program.Program) (stmts []goast.Stmt, err error) {
if node == nil {
return nil, nil
}
var (
stmt goast.Stmt
preStmts []goast.Stmt
postStmts []goast.Stmt
)
switch n := node.(type) {
case *ast.DeclStmt:
var s []goast.Stmt
s, preStmts, postStmts, err = transpileDeclStmt(n, p)
preStmts = append(preStmts, s...)
default:
stmt, preStmts, postStmts, err = transpileToStmt(node, p)
}
if err != nil {
return
}
stmts = append(stmts, combineStmts(stmt, preStmts, postStmts)...)
return
}
func transpileToStmt(node ast.Node, p *program.Program) (
stmt goast.Stmt, preStmts []goast.Stmt, postStmts []goast.Stmt, err error) {
if node == nil {
return
}
var expr goast.Expr
switch n := node.(type) {
case *ast.DefaultStmt:
stmt, err = transpileDefaultStmt(n, p)
return
case *ast.CaseStmt:
stmt, preStmts, postStmts, err = transpileCaseStmt(n, p)
return
case *ast.SwitchStmt:
stmt, preStmts, postStmts, err = transpileSwitchStmt(n, p)
return
case *ast.BreakStmt:
stmt = &goast.BranchStmt{
Tok: token.BREAK,
}
return
case *ast.WhileStmt:
return transpileWhileStmt(n, p)
case *ast.DoStmt:
return transpileDoStmt(n, p)
case *ast.ContinueStmt:
stmt, err = transpileContinueStmt(n, p)
return
case *ast.IfStmt:
return transpileIfStmt(n, p)
case *ast.ForStmt:
return transpileForStmt(n, p)
case *ast.ReturnStmt:
return transpileReturnStmt(n, p)
case *ast.CompoundStmt:
stmt, preStmts, postStmts, err = transpileCompoundStmt(n, p)
return
case *ast.BinaryOperator:
if n.Operator == "," {
stmt, preStmts, err = transpileBinaryOperatorComma(n, p)
return
}
case *ast.LabelStmt:
stmt, preStmts, postStmts, err = transpileLabelStmt(n, p)
return
case *ast.GotoStmt:
stmt, err = transpileGotoStmt(n, p)
return
case *ast.GCCAsmStmt:
// Go does not support inline assembly. See:
// https://github.com/elliotchance/c2go/issues/228
p.AddMessage(p.GenerateWarningMessage(
errors.New("cannot transpile asm, will be ignored"), n))
stmt = &goast.EmptyStmt{}
return
}
// We do not care about the return type.
expr, _, preStmts, postStmts, err = transpileToExpr(node, p, true)
if err != nil {
return
}
// nil is happen, when we remove function `free` of <stdlib.h>
// see function CallExpr in transpiler
if expr != (*goast.CallExpr)(nil) {
stmt = util.NewExprStmt(expr)
}
return
}
func transpileToNode(node ast.Node, p *program.Program) error {
switch n := node.(type) {
case *ast.TranslationUnitDecl:
for i := 0; i < len(n.Children()); i++ {
switch v := n.Children()[i].(type) {
case *ast.RecordDecl:
// specific for `typedef struct` without name
if v.Name != "" || i == len(n.Children())-1 {
err := transpileRecordDecl(p, v)
if err != nil {
return err
}
}
for counter := 1; i+counter < len(n.Children()); counter++ {
if vv, ok := n.Children()[i+counter].(*ast.TypedefDecl); ok {
nameTypedefStruct := vv.Name
fields := v.Children()
// create a struct in according to
// name and fields
var recordDecl ast.RecordDecl
recordDecl.Name = nameTypedefStruct
recordDecl.ChildNodes = fields
err := transpileRecordDecl(p, &recordDecl)
if err != nil {
return err
}
} else {
counter--
i = i + counter
break
}
}
default:
transpileToNode(n.Children()[i], p)
}
}
case *ast.FunctionDecl:
err := transpileFunctionDecl(n, p)
if err != nil {
return err
}
case *ast.TypedefDecl:
return transpileTypedefDecl(p, n)
case *ast.RecordDecl:
return transpileRecordDecl(p, n)
case *ast.VarDecl:
transpileVarDecl(p, n)
return nil
case *ast.EnumDecl:
transpileEnumDecl(p, n)
return nil
case *ast.EmptyDecl:
p.AddMessage(p.GenerateWarningMessage(fmt.Errorf("EmptyDecl is not transpiled"), n))
return nil
default:
panic(fmt.Sprintf("cannot transpile to node: %#v", node))
}
return nil
}
func transpileStmts(nodes []ast.Node, p *program.Program) (stmts []goast.Stmt, err error) {
for _, s := range nodes {
if s != nil {
var (
stmt goast.Stmt
preStmts []goast.Stmt
postStmts []goast.Stmt
)
stmt, preStmts, postStmts, err = transpileToStmt(s, p)
if err != nil {
return
}
stmts = append(stmts, combineStmts(stmt, preStmts, postStmts)...)
}
}
return stmts, nil
}
// combineStmts - combine elements to slice
func combineStmts(stmt goast.Stmt, preStmts, postStmts []goast.Stmt) (stmts []goast.Stmt) {
for i := range preStmts {
if preStmts[i] != nil {
stmts = append(stmts, preStmts[i])
}
}
if stmt != nil {
stmts = append(stmts, stmt)
}
for i := range postStmts {
if postStmts[i] != nil {
stmts = append(stmts, postStmts[i])
}
}
return
}