forked from elliotchance/c2go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
call.go
247 lines (209 loc) · 6.75 KB
/
call.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
// This file contains functions for transpiling function calls (invocations).
package transpiler
import (
"errors"
"fmt"
"strings"
"github.com/elliotchance/c2go/ast"
"github.com/elliotchance/c2go/program"
"github.com/elliotchance/c2go/types"
"github.com/elliotchance/c2go/util"
goast "go/ast"
"go/token"
)
func getName(firstChild ast.Node) string {
switch fc := firstChild.(type) {
case *ast.DeclRefExpr:
return fc.Name
case *ast.MemberExpr:
return fc.Name
case *ast.ParenExpr:
return getName(fc.Children()[0])
case *ast.UnaryOperator:
return getName(fc.Children()[0])
case *ast.ImplicitCastExpr:
return getName(fc.Children()[0])
case *ast.CStyleCastExpr:
return getName(fc.Children()[0])
default:
panic(fmt.Sprintf("cannot CallExpr on: %#v", fc))
}
}
func getNameOfFunctionFromCallExpr(n *ast.CallExpr) (string, error) {
// The first child will always contain the name of the function being
// called.
firstChild, ok := n.Children()[0].(*ast.ImplicitCastExpr)
if !ok {
err := fmt.Errorf("unable to use CallExpr: %#v", n.Children()[0])
return "", err
}
return getName(firstChild.Children()[0]), nil
}
// transpileCallExpr transpiles expressions that calls a function, for example:
//
// foo("bar")
//
// It returns three arguments; the Go AST expression, the C type (that is
// returned by the function) and any error. If there is an error returned you
// can assume the first two arguments will not contain any useful information.
func transpileCallExpr(n *ast.CallExpr, p *program.Program) (
*goast.CallExpr, string, []goast.Stmt, []goast.Stmt, error) {
preStmts := []goast.Stmt{}
postStmts := []goast.Stmt{}
functionName, err := getNameOfFunctionFromCallExpr(n)
if err != nil {
return nil, "", nil, nil, err
}
// Get the function definition from it's name. The case where it is not
// defined is handled below (we haven't seen the prototype yet).
functionDef := program.GetFunctionDefinition(functionName)
if functionDef == nil {
errorMessage := fmt.Sprintf("unknown function: %s", functionName)
p.AddMessage(p.GenerateWarningMessage(errors.New(errorMessage), n))
// We do not have a prototype for the function, but we should not exit
// here. Instead we will create a mock definition for it so that this
// transpile function will always return something and continue.
//
// The mock function definition is never actually saved to the program
// definitions, so each time we see the CallExpr it will run this every
// time. This is so if we come across the real prototype later it will
// be handled correctly. Or at least "more" correctly.
functionDef = &program.FunctionDefinition{
Name: functionName,
}
}
if functionDef.Substitution != "" {
parts := strings.Split(functionDef.Substitution, ".")
importName := strings.Join(parts[:len(parts)-1], ".")
p.AddImport(importName)
parts2 := strings.Split(functionDef.Substitution, "/")
functionName = parts2[len(parts2)-1]
}
args := []goast.Expr{}
argTypes := []string{}
i := 0
for _, arg := range n.Children()[1:] {
e, eType, newPre, newPost, err := transpileToExpr(arg, p, false)
if err != nil {
return nil, "unknown2", nil, nil, err
}
argTypes = append(argTypes, eType)
preStmts, postStmts = combinePreAndPostStmts(preStmts, postStmts, newPre, newPost)
_, arraySize := types.GetArrayTypeAndSize(eType)
// If we are using varargs with Printf we need to make sure that certain
// types are cast correctly.
if functionName == "fmt.Printf" {
// Make sure that any string parameters (const char*) are truncated
// to the NULL byte.
if arraySize != -1 {
p.AddImport("github.com/elliotchance/c2go/noarch")
e = util.NewCallExpr(
"noarch.CStringToString",
&goast.SliceExpr{X: e},
)
}
// Byte slices (char*) must also be truncated to the NULL byte.
//
// TODO: This would also apply to other formatting functions like
// fprintf, etc.
if i > len(functionDef.ArgumentTypes)-1 &&
(eType == "char *" || eType == "char*") {
p.AddImport("github.com/elliotchance/c2go/noarch")
e = util.NewCallExpr("noarch.CStringToString", e)
}
}
args = append(args, e)
i++
}
// These are the arguments once any transformations have taken place.
realArgs := []goast.Expr{}
// Apply transformation if needed. A transformation rearranges the return
// value(s) and parameters. It is also used to indicate when a variable must
// be passed by reference.
if functionDef.ReturnParameters != nil || functionDef.Parameters != nil {
for i, a := range functionDef.Parameters {
byReference := false
// Negative position means that it must be passed by reference.
if a < 0 {
byReference = true
a = -a
}
// Rearrange the arguments. The -1 is because 0 would be the return
// value.
realArg := args[a-1]
if byReference {
// We have to create a temporary variable to pass by reference.
// Then we can assign the real variable from it.
realArg = &goast.UnaryExpr{
Op: token.AND,
X: args[i],
}
} else {
realArg, err = types.CastExpr(p, realArg, argTypes[i],
functionDef.ArgumentTypes[i])
p.AddMessage(
p.GenerateWarningOrErrorMessage(err, n, realArg == nil),
)
if realArg == nil {
realArg = util.NewNil()
}
}
realArgs = append(realArgs, realArg)
}
} else {
// Keep all the arguments the same. But make sure we cast to the correct
// types.
for i, a := range args {
if i > len(functionDef.ArgumentTypes)-1 {
// This means the argument is one of the varargs so we don't
// know what type it needs to be cast to.
} else {
a, err = types.CastExpr(p, a, argTypes[i],
functionDef.ArgumentTypes[i])
if p.AddMessage(p.GenerateWarningMessage(err, n)) {
a = util.NewNil()
}
}
realArgs = append(realArgs, a)
}
}
// Added for support removing function `free` of <stdlib.h>
// Example of C code:
// free(i+=4,buffer)
// Example of result Go code:
// i += 4
// _ = buffer
if functionDef.Substitution == "_" {
var argName string
if v, ok := realArgs[0].(*goast.CallExpr); ok && len(realArgs) == 1 {
if vv, ok := v.Args[0].(*goast.Ident); ok && len(v.Args) == 1 {
argName = vv.Name
}
if vv, ok := v.Args[0].(*goast.ParenExpr); ok && len(v.Args) == 1 {
argName = vv.X.(*goast.Ident).Name
}
}
if v, ok := realArgs[0].(*goast.Ident); ok {
argName = v.Name
}
if argName != "" {
devNull := &goast.AssignStmt{
Lhs: []goast.Expr{
&goast.Ident{
Name: "_",
},
},
Tok: token.ASSIGN,
Rhs: []goast.Expr{
&goast.Ident{
Name: argName,
},
},
}
preStmts = append(preStmts, devNull)
return nil, "", preStmts, postStmts, nil
}
}
return util.NewCallExpr(functionName, realArgs...),
functionDef.ReturnType, preStmts, postStmts, nil
}