forked from elliotchance/c2go
/
union.go
119 lines (102 loc) · 2.38 KB
/
union.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
package transpiler
import (
"bytes"
"fmt"
"html/template"
goast "go/ast"
"go/format"
"go/parser"
"go/token"
"github.com/elliotchance/c2go/ast"
"github.com/elliotchance/c2go/program"
)
func transpileUnion(name string, size int, fields []*goast.Field) (
_ []goast.Decl, err error) {
type field struct {
Name string
TypeField string
}
type union struct {
Name string
Size int
Fields []field
}
src := `package main
import(
"unsafe"
"reflect"
)
type {{ .Name }} struct{
memory unsafe.Pointer
}
func (unionVar * {{ .Name }}) copy() ( {{ .Name }}){
var buffer [{{ .Size }}]byte
for i := range buffer{
buffer[i] = (*((*[{{ .Size }}]byte)(unionVar.memory)))[i]
}
var newUnion {{ .Name }}
newUnion.memory = unsafe.Pointer(&buffer)
return newUnion
}
{{ range .Fields }}
func (unionVar * {{ $.Name }}) {{ .Name }}() (*{{ .TypeField }}){
if unionVar.memory == nil{
var buffer [{{ $.Size }}]byte
unionVar.memory = unsafe.Pointer(&buffer)
}
return (*{{ .TypeField }})(unionVar.memory)
}
{{ end }}
`
// Generate structure of union
var un union
un.Name = name
un.Size = size
for i := range fields {
var f field
f.Name = fields[i].Names[0].Name
var buf bytes.Buffer
err = format.Node(&buf, token.NewFileSet(), fields[i].Type)
if err != nil {
err = fmt.Errorf("cannot parse type '%s' : %v", fields[i].Type, err)
return
}
f.TypeField = buf.String()
un.Fields = append(un.Fields, f)
}
tmpl := template.Must(template.New("").Parse(src))
var source bytes.Buffer
err = tmpl.Execute(&source, un)
if err != nil {
err = fmt.Errorf("cannot execute template \"%s\" for data %v : %v", source.String(), un, err)
return
}
// Create the AST by parsing src.
fset := token.NewFileSet() // positions are relative to fset
f, err := parser.ParseFile(fset, "", source.String(), 0)
if err != nil {
err = fmt.Errorf("cannot parse source \"%s\" : %v", source.String(), err)
return
}
return f.Decls[1:], nil
}
func isUnionMemberExpr(p *program.Program, n *ast.MemberExpr) (IsUnion bool) {
if len(n.Children()) > 0 {
if v, ok := n.Children()[0].(*ast.MemberExpr); ok {
if p.IsUnion(v.Type) {
IsUnion = true
}
}
if v, ok := n.Children()[0].(*ast.DeclRefExpr); ok {
if p.IsUnion(v.Type) {
IsUnion = true
}
}
if v, ok := n.Children()[0].(*ast.ImplicitCastExpr); ok {
if p.IsUnion(v.Type) {
IsUnion = true
}
}
}
return
}