-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcppgo.go
517 lines (451 loc) · 10.6 KB
/
cppgo.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
// Copyright 2017 Peter Mattis.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License. See the AUTHORS file
// for names of contributors.
// Note that this file is embedded in the cppgo binary using go-bindata. Use
// "go generate" whenever it is modified to rebuild the generated bindata.go
// file.
// +build ignore
package main
import (
"fmt"
"log"
"path"
"reflect"
"sort"
"unicode"
// IMPORTS
)
var types = make(map[reflect.Type]bool)
var declTypes = make(map[reflect.Type]bool)
var namespaces = make(map[string]*namespace)
type namespace struct {
name string
deps map[*namespace]bool
types []reflect.Type
seen map[reflect.Type]bool
}
func typeName(t reflect.Type) string {
switch t.Kind() {
case reflect.Bool:
return "bool"
case reflect.Int8:
return "int8_t"
case reflect.Int16:
return "int16_t"
case reflect.Int32:
return "int32_t"
case reflect.Int, reflect.Int64:
return "int64_t"
case reflect.Uint8:
return "uint8_t"
case reflect.Uint16:
return "uint16_t"
case reflect.Uint32:
return "uint32_t"
case reflect.Uint, reflect.Uint64:
return "uint64_t"
case reflect.Uintptr:
return "uintptr_t"
case reflect.Float32:
return "float"
case reflect.Float64:
return "double"
case reflect.String:
return "String"
case reflect.Array:
elemName := typeName(t.Elem())
if elemName == "" {
return ""
}
return fmt.Sprintf("Array<%s,%d>", elemName, t.Len())
case reflect.Slice:
elemName := typeName(t.Elem())
if elemName == "" {
return ""
}
return fmt.Sprintf("Slice<%s>", elemName)
case reflect.Ptr:
elemName := typeName(t.Elem())
if elemName == "" {
return ""
}
return fmt.Sprintf("Pointer<%s>", elemName)
case reflect.Struct:
pkgPath := t.PkgPath()
if pkgPath == "" {
return t.Name()
}
return path.Base(pkgPath) + "::" + t.Name()
default:
// TODO(peter): unsupported
// reflect.Complex64
// reflect.Complex128
// reflect.Chan
// reflect.Func
// reflect.Interface
// reflect.Map
// reflect.UnsafePointer
return ""
}
}
var cppKeywords = map[string]bool{
"delete": true,
"export": true,
"inline": true,
}
func sanitizeName(s string) string {
if cppKeywords[s] {
return s + "_"
}
return s
}
func accessorName(s string) string {
out := make([]rune, 0, len(s))
prevUpper := false
for i, r := range s {
if unicode.IsUpper(r) {
if i > 0 && !prevUpper {
out = append(out, '_')
}
r = unicode.ToLower(r)
prevUpper = true
} else {
prevUpper = false
}
out = append(out, r)
}
return sanitizeName(string(out))
}
func walk(t reflect.Type) *namespace {
switch t.Kind() {
case reflect.Ptr, reflect.Array, reflect.Slice:
return walk(t.Elem())
}
if t.Kind() != reflect.Struct {
return nil
}
name := path.Base(t.PkgPath())
n := namespaces[name]
if n == nil {
n = &namespace{
name: name,
deps: make(map[*namespace]bool),
seen: make(map[reflect.Type]bool),
}
namespaces[name] = n
}
if n.seen[t] {
return n
}
n.seen[t] = true
n.types = append(n.types, t)
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
if f.PkgPath != "" {
// Unexported field.
continue
}
switch f.Type.Kind() {
case reflect.Struct, reflect.Ptr, reflect.Array, reflect.Slice:
if d := walk(f.Type); d != nil && d != n {
n.deps[d] = true
}
}
}
return n
}
func gen() {
fmt.Printf(prologue)
sorted := make([]*namespace, 0, len(namespaces))
for _, n := range namespaces {
sorted = append(sorted, n)
}
sort.Slice(sorted, func(i, j int) bool {
return sorted[i].name < sorted[j].name
})
visited := make(map[*namespace]bool)
for _, n := range sorted {
n.gen(visited)
}
fmt.Printf(epilogue)
}
func (n *namespace) gen(visited map[*namespace]bool) {
if visited[n] {
return
}
visited[n] = true
deps := make([]*namespace, 0, len(n.deps))
for d := range n.deps {
deps = append(deps, d)
}
sort.Slice(deps, func(i, j int) bool {
return deps[i].name < deps[j].name
})
for _, d := range deps {
d.gen(visited)
}
fmt.Printf("namespace %s {\n", n.name)
for _, t := range n.types {
n.genType(t)
}
fmt.Printf("\n} // namespace %s\n\n", n.name)
}
func (n *namespace) genType(t reflect.Type) {
switch t.Kind() {
case reflect.Ptr, reflect.Array, reflect.Slice:
n.genType(t.Elem())
return
}
if t.Kind() != reflect.Struct {
return
}
if types[t] {
if !declTypes[t] {
declTypes[t] = true
fmt.Printf("\n")
if namespace := path.Base(t.PkgPath()); n.name != namespace {
log.Fatalf("unexpected namespace: %s != %s", n.name, namespace)
}
fmt.Printf("class %s;\n", t.Name())
}
return
}
types[t] = true
if namespace := path.Base(t.PkgPath()); n.name != namespace {
log.Fatalf("unexpected namespace: %s != %s", n.name, namespace)
}
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
if f.PkgPath != "" {
// Unexported field.
continue
}
switch f.Type.Kind() {
case reflect.Struct, reflect.Ptr, reflect.Array, reflect.Slice:
n.genType(f.Type)
}
}
declTypes[t] = true
fmt.Printf("\n")
fmt.Printf("class %s {\n", t.Name())
fmt.Printf(" public:\n")
fmt.Printf(" enum { Size = %d };\n", t.Size())
fmt.Printf("\n")
fmt.Printf(" public:\n")
var constructor bool
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
if f.PkgPath != "" {
// Unexported field.
fmt.Printf(" // UNEXPORTED: %s %s %d\n",
accessorName(f.Name), f.Type, f.Offset)
continue
}
tName := typeName(f.Type)
if tName == "" {
fmt.Printf(" // UNIMPLEMENTED: %s %s %d\n",
accessorName(f.Name), f.Type, f.Offset)
continue
}
if !constructor {
constructor = true
fmt.Printf(" %s()\n", t.Name())
fmt.Printf(" : data_(nullptr) {\n")
fmt.Printf(" }\n")
fmt.Printf(" %s(const %s &x)\n", t.Name(), t.Name())
fmt.Printf(" : data_(x.data_) {\n")
fmt.Printf(" }\n")
fmt.Printf(" %s(const void *data)\n", t.Name())
fmt.Printf(" : data_(reinterpret_cast<const uint8_t*>(data)) {\n")
fmt.Printf(" }\n")
fmt.Printf("\n")
}
fmt.Printf(" %s %s() const {\n", tName, accessorName(f.Name))
fmt.Printf(" return Type<%s>::get(data_ + %d);\n", tName, f.Offset)
fmt.Printf(" }\n")
}
if !constructor {
fmt.Printf(" %s(const void *data) {\n", t.Name())
fmt.Printf(" }\n")
} else {
fmt.Printf("\n private:\n")
fmt.Printf(" const uint8_t *data_;\n")
}
fmt.Printf("};\n")
}
var prologue = `// Code generated by cppgo
// DO NOT EDIT!
#ifndef CPPGO_H
#define CPPGO_H
#include <string>
#include <type_traits>
#include <stdint.h>
namespace go {
template <typename T, typename E = void>
struct Type;
template <typename T>
struct Type<T, typename std::enable_if<std::is_class<T>::value>::type> {
enum { Size = T::Size };
static T get(const void *data) {
return T(data);
}
};
template <typename T>
struct Type<T, typename std::enable_if<std::is_arithmetic<T>::value>::type> {
enum { Size = sizeof(T) };
static T get(const void *data) {
return *reinterpret_cast<const T*>(data);
}
};
class String {
struct Header {
const char *data;
int64_t size;
};
public:
enum { Size = sizeof(Header) };
public:
String(const void *data)
: hdr_(reinterpret_cast<const Header*>(data)) {
}
std::string as_string() const { return std::string(data(), size()); }
const char* data() const { return hdr_->data; }
int64_t size() const { return hdr_->size; }
private:
const Header* hdr_;
};
template <typename T>
class Pointer {
public:
enum { Size = sizeof(void*) };
public:
Pointer(const void *data)
: ptr_(*reinterpret_cast<const uint8_t* const*>(data)),
elem_(ptr_ != nullptr ? Type<T>::get(ptr_) : T()) {
}
const void* get() const {
return ptr_;
}
operator bool() const {
return get() != nullptr;
}
const T operator*() const {
return elem_;
}
const T* operator->() const {
return &elem_;
}
private:
const void *ptr_;
const T elem_;
};
template <typename C>
class Iterator {
public:
typedef typename C::value_type value_type;
typedef typename C::reference_type reference_type;
typedef Iterator<C> self_type;
public:
Iterator(const C *c, int index)
: container_(c),
index_(index) {
}
Iterator(const self_type& x)
: container_(x.container_),
index_(x.index_) {
}
value_type operator*() const {
return (*container_)[index_];
}
self_type operator++(int) {
self_type t = *this;
return ++t;
}
self_type& operator++() {
++index_;
return *this;
}
self_type operator--(int) {
self_type t = *this;
return --*t;
}
self_type& operator--() {
--index_;
return *this;
}
bool operator==(const self_type& other) const {
return container_ == other.container_ && index_ == other.index_;
}
bool operator!=(const self_type& other) const {
return !(*this == other);
}
private:
const C *container_;
int index_;
};
template <typename T>
class Slice {
struct Header {
const uint8_t *data;
int64_t size;
int64_t cap;
};
public:
enum { Size = sizeof(Header) };
typedef T value_type;
typedef value_type &reference_type;
typedef Iterator<Slice<T>> iterator;
typedef iterator const_iterator;
public:
Slice(const void *data)
: hdr_(reinterpret_cast<const Header*>(data)) {
}
value_type operator[](int i) const {
return Type<T>::get(hdr_->data + i * Type<T>::Size);
}
int64_t size() const { return hdr_->size; }
const_iterator begin() const { return const_iterator(this, 0); }
const_iterator end() const { return const_iterator(this, size()); }
private:
const Header* hdr_;
};
template <typename T, int N>
class Array {
public:
enum { Size = N * Type<T>::Size };
typedef T value_type;
typedef value_type &reference_type;
typedef Iterator<Array<T, N>> iterator;
typedef iterator const_iterator;
public:
Array(const void *data)
: data_(reinterpret_cast<const uint8_t*>(data)) {
}
value_type operator[](int i) const {
return Type<T>::get(data_ + i * Type<T>::Size);
}
int64_t size() const { return N; }
const_iterator begin() const { return const_iterator(this, 0); }
const_iterator end() const { return const_iterator(this, size()); }
private:
const uint8_t *data_;
};
`
var epilogue = `} // namespace go
#endif // CPPGO_H
`
func main() {
// WALK
gen()
}