-
Notifications
You must be signed in to change notification settings - Fork 38
/
resolve.go
533 lines (488 loc) · 12.3 KB
/
resolve.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
package types
import (
"errors"
"fmt"
"strconv"
"strings"
"github.com/Konstantin8105/c4go/program"
"github.com/Konstantin8105/c4go/util"
)
// cIntegerType - slice of C integer type
var cIntegerType = []string{
"int",
"long long",
"long long int",
"long long unsigned int",
"long unsigned int",
"long",
"short",
"unsigned int",
"unsigned long long",
"unsigned long",
"unsigned short",
"unsigned short int",
"size_t",
"ptrdiff_t",
}
var goBaseTypes = [...]string{
"string",
"bool",
"int8", "uint8", "byte",
"int16", "uint16",
"int32", "rune", "uint32",
"int64", "uint64", "int",
"uint", "uintptr",
"float32", "float64",
"complex64", "complex128",
}
func IsGoBaseType(ctype string) bool {
for _, t := range goBaseTypes {
if ctype == t {
return true
}
}
return false
}
func IsSigned(p *program.Program, cType string) bool {
if !strings.Contains(cType, "unsigned") {
return true
}
if rt, ok := p.TypedefType[cType]; ok {
return IsSigned(p, rt)
}
return false
}
// IsCInteger - return true is C type integer
func IsCInteger(p *program.Program, cType string) bool {
for i := range cIntegerType {
if cType == cIntegerType[i] {
return true
}
}
if rt, ok := p.TypedefType[cType]; ok {
return IsCInteger(p, rt)
}
return false
}
var cFloatType = []string{
"double",
"float",
"long double",
}
// IsCInteger - return true is C type integer
func IsCFloat(p *program.Program, cType string) bool {
for i := range cFloatType {
if cType == cFloatType[i] {
return true
}
}
if rt, ok := p.TypedefType[cType]; ok {
return IsCFloat(p, rt)
}
return false
}
// NullPointer - is look : (double *)(nil) or (FILE *)(nil)
// created only for transpiler.CStyleCastExpr
var NullPointer = "NullPointerType *"
// ToVoid - specific type for ignore the cast
var ToVoid = "ToVoid"
// ResolveType determines the Go type from a C type.
//
// Some basic examples are obvious, such as "float" in C would be "float32" in
// Go. But there are also much more complicated examples, such as compound types
// (structs and unions) and function pointers.
//
// Some general rules:
//
// 1. The Go type must be deterministic. The same C type will ALWAYS return the
// same Go type, in any condition. This is extremely important since the
// nature of C is that is may not have certain information available about the
// rest of the program or libraries when it is being compiled.
//
// 2. Many C type modifiers and properties are lost as they have no sensible or
// valid translation to Go. Some example of those would be "const" and
// "volatile". It is left be up to the clang (or other compiler) to warn if
// types are being abused against the standards in which they are being
// compiled under. Go will make no assumptions about how you expect it act,
// only how it is used.
//
// 3. New types are registered (discovered) throughout the transpiling of the
// program, so not all types are know at any given time. This works exactly
// the same way in a C compiler that will not let you use a type before it
// has been defined.
//
// 4. If all else fails an error is returned. However, a type (which is almost
// certainly incorrect) "interface{}" is also returned. This is to allow the
// transpiler to step over type errors and put something as a placeholder
// until a more suitable solution is found for those cases.
func ResolveType(p *program.Program, s string) (resolveResult string, err error) {
{
input := s
defer func() {
resolveResult = strings.TrimSpace(resolveResult)
if err != nil {
err = fmt.Errorf("cannot resolve type '%s' : %v", input, err)
}
}()
}
if strings.Contains(s, ":") {
return "interface{}", errors.New("probably an incorrect type translation 0")
}
s = util.CleanCType(s)
// FIXME: This is a hack to avoid casting in some situations.
if s == "" {
return "interface{}", errors.New("probably an incorrect type translation 1")
}
// FIXME: I have no idea, how to solve.
// See : /issues/628
if strings.Contains(s, "__locale_data") {
s = strings.Replace(s, "struct __locale_data", "int", -1)
s = strings.Replace(s, "__locale_data", "int", -1)
}
if strings.Contains(s, "__locale_struct") {
return "int", nil
}
if strings.Contains(s, "__sFILEX") {
s = strings.Replace(s, "__sFILEX", "int", -1)
}
// Specific for va_list
if strings.Contains(s, "struct __va_list_tag") {
return "* va_list", nil
}
if strings.Contains(s, "va_list") {
return "* va_list", nil
}
if strings.Contains(s, "__builtin_va_list") {
return "* va_list", nil
}
// The simple resolve types are the types that we know there is an exact Go
// equivalent. For example float, int, etc.
if v, ok := program.DefinitionType[s]; ok {
return p.ImportType(v), nil
}
// function type is pointer in Go by default
if len(s) > 2 {
base := s[:len(s)-2]
if ff, ok := p.TypedefType[base]; ok {
if util.IsFunction(ff) {
return base, nil
}
}
}
// No need resolve typedef types
if _, ok := p.TypedefType[s]; ok {
if tt, ok := program.DefinitionType[s]; ok {
// "div_t": "github.com/Konstantin8105/c4go/noarch.DivT",
ii := p.ImportType(tt)
return ii, nil
}
return s, nil
}
if tt, ok := program.DefinitionType[s]; ok {
// "div_t": "github.com/Konstantin8105/c4go/noarch.DivT",
ii := p.ImportType(tt)
return ii, nil
}
// For function
if util.IsFunction(s) {
g, e := resolveFunction(p, s)
return g, e
}
// Example of cases:
// "int []"
// "int [6]"
// "struct s [2]"
// "int [2][3]"
// "unsigned short [512]"
//
// Example of resolving:
// int [2][3] -> [][]int
// int [2][3][4] -> [][][]int
if s[len(s)-1] == ']' {
index := strings.LastIndex(s, "[")
if index < 0 {
err = fmt.Errorf("cannot found [ in type : %v", s)
return
}
r := strings.TrimSpace(s[:index])
r, err = ResolveType(p, r)
if err != nil {
err = fmt.Errorf("cannot []: %v", err)
return
}
return "[]" + r, nil
}
// Example :
// "int (*)"
if strings.Contains(s, "(*)") {
return ResolveType(p, strings.Replace(s, "(*)", "*", -1))
}
// Check is it typedef enum
if _, ok := p.EnumTypedefName[s]; ok {
return ResolveType(p, "int")
}
if v, ok := p.TypedefType[s]; ok {
if util.IsFunction(v) {
// typedef function
return s, nil
}
return ResolveType(p, v)
}
// If the type is already defined we can proceed with the same name.
if p.IsTypeAlreadyDefined(s) {
if strings.HasPrefix(s, "struct ") {
s = s[len("struct "):]
}
if strings.HasPrefix(s, "union ") {
s = s[len("union "):]
}
if strings.HasPrefix(s, "class ") {
s = s[len("class "):]
}
// TODO : Why here ImportType???
return p.ImportType(s), nil
}
// It may be a pointer of a simple type. For example, float *, int *,
// etc.
if s[len(s)-1] == '*' {
r := strings.TrimSpace(s[:len(s)-1])
r, err = ResolveType(p, r)
prefix := "[]"
if strings.Contains(r, "noarch.File") {
prefix = "*"
}
if err != nil {
err = fmt.Errorf("cannot resolve star `*` for %v : %v", s, err)
}
return prefix + r, err
}
// Structures are by name.
var isUnion bool
{
isUnion = strings.HasPrefix(s, "struct ") ||
strings.HasPrefix(s, "class ") ||
strings.HasPrefix(s, "union ")
if str := p.GetStruct(s); str != nil {
isUnion = true
}
}
if isUnion {
if str := p.GetStruct("c4go_" + s); str != nil {
s = str.Name
} else {
if strings.HasPrefix(s, "struct ") {
s = s[len("struct "):]
}
if strings.HasPrefix(s, "union ") {
s = s[len("union "):]
}
if strings.HasPrefix(s, "class ") {
s = s[len("class "):]
}
}
return p.ImportType(s), nil
}
// Enums are by name.
if strings.HasPrefix(s, "enum ") {
s = s[len("enum "):]
return s, nil
}
// I have no idea how to handle this yet.
if strings.Contains(s, "anonymous union") {
return "interface{}", errors.New("probably an incorrect type translation 3")
}
// Function pointers are not yet supported. In the mean time they will be
// replaced with a type that certainly wont work until we can fix this
// properly.
search := util.GetRegex("[\\w ]+\\(\\*.*?\\)\\(.*\\)").MatchString(s)
if search {
return "interface{}",
fmt.Errorf("function pointers are not supported [1] : '%s'", s)
}
search = util.GetRegex("[\\w ]+ \\(.*\\)").MatchString(s)
if search {
return "interface{}",
fmt.Errorf("function pointers are not supported [2] : '%s'", s)
}
errMsg := fmt.Sprintf(
"I couldn't find an appropriate Go type for the C type '%s'.", s)
return s, errors.New(errMsg)
}
// resolveType determines the Go type from a C type.
func resolveFunction(p *program.Program, s string) (goType string, err error) {
defer func() {
if err != nil {
err = fmt.Errorf("resolveFunction error for `%s` : %v", s, err)
}
}()
var prefix string
var f, r []string
prefix, f, r, err = SeparateFunction(p, s)
if err != nil {
return
}
goType = strings.Replace(prefix, "*", "[]", -1)
goType += "func("
for i := range f {
goType += fmt.Sprintf("%s", f[i])
if i < len(f)-1 {
goType += " , "
}
}
goType += ")("
for i := range r {
goType += fmt.Sprintf("%s", r[i])
if i < len(r)-1 {
goType += " , "
}
}
goType += ")"
return
}
// SeparateFunction separate a function C type to Go types parts.
func SeparateFunction(p *program.Program, s string) (
prefix string, fields []string, returns []string, err error) {
defer func() {
if err != nil {
err = fmt.Errorf("cannot separate function '%s' : %v", s, err)
}
}()
pr, _, f, r, err := util.ParseFunction(s)
if err != nil {
return
}
for i := range f {
if f[i] == "" {
continue
}
var t string
t, err = ResolveType(p, f[i])
if err != nil {
err = fmt.Errorf("error in field %s. err = %v", t, err)
return
}
fields = append(fields, t)
}
for i := range r {
var t string
t, err = ResolveType(p, r[i])
if err != nil {
err = fmt.Errorf("error in return field %s. err = %v", t, err)
return
}
returns = append(returns, t)
}
prefix = util.CleanCType(pr)
return
}
// IsTypedefFunction - return true if that type is typedef of function.
func IsTypedefFunction(p *program.Program, s string) bool {
if v, ok := p.TypedefType[s]; ok && util.IsFunction(v) {
return true
}
s = GetBaseType(s)
if v, ok := p.TypedefType[s]; ok && util.IsFunction(v) {
return true
}
return false
}
// GetAmountArraySize - return amount array size
// Example :
// In : 'char [40]'
// Out : 40
func GetAmountArraySize(cType string, p *program.Program) (size int, err error) {
if !IsCArray(cType, p) {
err = fmt.Errorf("is not array: `%s`", cType)
return
}
reg := util.GetRegex("\\[(?P<size>\\d+)\\]")
match := reg.FindStringSubmatch(cType)
if reg.NumSubexp() != 1 {
err = fmt.Errorf("cannot found size of array in type : %s", cType)
return
}
result := make(map[string]string)
for i, name := range reg.SubexpNames() {
if i != 0 {
result[name] = match[i]
}
}
return strconv.Atoi(result["size"])
}
// GetBaseType - return base type without pointera, array symbols
// Input:
// s = struct BSstructSatSShomeSlepriconSgoSsrcSgithubPcomSD260D18E [7]
func GetBaseType(s string) string {
s = strings.TrimSpace(s)
s = util.CleanCType(s)
if len(s) < 1 {
return s
}
if s[len(s)-1] == ']' {
for i := len(s) - 1; i >= 0; i-- {
if s[i] == '[' {
s = s[:i]
return GetBaseType(s)
}
}
}
if s[len(s)-1] == '*' {
return GetBaseType(s[:len(s)-1])
}
if strings.Contains(s, "(*)") {
return GetBaseType(strings.TrimSpace(
strings.Replace(s, "(*)", "*", -1)))
}
return s
}
// IsCArray - check C type is array
func IsCArray(s string, p *program.Program) bool {
if len(s) == 0 {
return false
}
for i := len(s) - 1; i >= 0; i-- {
switch s[i] {
case ' ':
continue
case ']':
return true
default:
break
}
}
if p != nil {
if t, ok := p.TypedefType[s]; ok {
return IsCArray(t, p)
}
}
return false
}
func IsCUnsignedType(s string) bool {
return strings.Contains(s, "unsigned ")
}
// IsPointer - check type is pointer
func IsPointer(s string, p *program.Program) bool {
return IsCPointer(s, p) || IsCArray(s, p)
}
// IsCPointer - check C type is pointer
func IsCPointer(s string, p *program.Program) bool {
if len(s) == 0 {
return false
}
for i := len(s) - 1; i >= 0; i-- {
switch s[i] {
case ' ':
continue
case '*':
return true
default:
break
}
}
if p != nil {
if t, ok := p.TypedefType[s]; ok {
return IsCPointer(t, p)
}
}
return false
}