forked from golang/mobile
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenjava.go
1731 lines (1622 loc) · 47 KB
/
genjava.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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package bind
import (
"fmt"
"go/constant"
"go/types"
"html"
"math"
"reflect"
"regexp"
"strings"
"golang.org/x/mobile/internal/importers/java"
)
// TODO(crawshaw): disallow basic android java type names in exported symbols.
// TODO(crawshaw): consider introducing Java functions for casting to and from interfaces at runtime.
type JavaGen struct {
// JavaPkg is the Java package prefix for the generated classes. The prefix is prepended to the Go
// package name to create the full Java package name.
JavaPkg string
*Generator
jstructs map[*types.TypeName]*javaClassInfo
clsMap map[string]*java.Class
// Constructors is a map from Go struct types to a list
// of exported constructor functions for the type, on the form
// func New<Type>(...) *Type
constructors map[*types.TypeName][]*types.Func
}
type javaClassInfo struct {
// The Java class this class extends.
extends *java.Class
// All Java classes and interfaces this class extends and implements.
supers []*java.Class
methods map[string]*java.FuncSet
// Does the class need a default no-arg constructor
genNoargCon bool
}
// Init intializes the embedded Generator and initializes the Java class information
// needed to generate structs that extend Java classes and interfaces.
func (g *JavaGen) Init(classes []*java.Class) {
g.Generator.Init()
g.clsMap = make(map[string]*java.Class)
for _, cls := range classes {
g.clsMap[cls.Name] = cls
}
g.jstructs = make(map[*types.TypeName]*javaClassInfo)
g.constructors = make(map[*types.TypeName][]*types.Func)
for _, s := range g.structs {
classes := embeddedJavaClasses(s.t)
if len(classes) == 0 {
continue
}
inf := &javaClassInfo{
methods: make(map[string]*java.FuncSet),
genNoargCon: true, // java.lang.Object has a no-arg constructor
}
for _, n := range classes {
cls := g.clsMap[n]
for _, fs := range cls.AllMethods {
hasMeth := false
for _, f := range fs.Funcs {
if !f.Final {
hasMeth = true
}
}
if hasMeth {
inf.methods[fs.GoName] = fs
}
}
inf.supers = append(inf.supers, cls)
if !cls.Interface {
if inf.extends != nil {
g.errorf("%s embeds more than one Java class; only one is allowed.", s.obj)
}
if cls.Final {
g.errorf("%s embeds final Java class %s", s.obj, cls.Name)
}
inf.extends = cls
inf.genNoargCon = cls.HasNoArgCon
}
}
g.jstructs[s.obj] = inf
}
for _, f := range g.funcs {
if t := g.constructorType(f); t != nil {
jinf := g.jstructs[t]
if jinf != nil {
sig := f.Type().(*types.Signature)
jinf.genNoargCon = jinf.genNoargCon && sig.Params().Len() > 0
}
g.constructors[t] = append(g.constructors[t], f)
}
}
}
func (j *javaClassInfo) toJavaType(T types.Type) *java.Type {
switch T := T.(type) {
case *types.Basic:
var kind java.TypeKind
switch T.Kind() {
case types.Bool, types.UntypedBool:
kind = java.Boolean
case types.Uint8:
kind = java.Byte
case types.Int16:
kind = java.Short
case types.Int32, types.UntypedRune: // types.Rune
kind = java.Int
case types.Int64, types.UntypedInt:
kind = java.Long
case types.Float32:
kind = java.Float
case types.Float64, types.UntypedFloat:
kind = java.Double
case types.String, types.UntypedString:
kind = java.String
default:
return nil
}
return &java.Type{Kind: kind}
case *types.Slice:
switch e := T.Elem().(type) {
case *types.Basic:
switch e.Kind() {
case types.Uint8: // Byte.
return &java.Type{Kind: java.Array, Elem: &java.Type{Kind: java.Byte}}
}
}
return nil
case *types.Named:
if isJavaType(T) {
return &java.Type{Kind: java.Object, Class: classNameFor(T)}
}
}
return nil
}
// lookupMethod searches the Java class descriptor for a method
// that matches the Go method.
func (j *javaClassInfo) lookupMethod(m *types.Func, hasThis bool) *java.Func {
jm := j.methods[m.Name()]
if jm == nil {
// If an exact match is not found, try the method with trailing underscores
// stripped. This way, name clashes can be avoided when overriding multiple
// overloaded methods from Go.
base := strings.TrimRight(m.Name(), "_")
jm = j.methods[base]
if jm == nil {
return nil
}
}
// A name match was found. Now use the parameter and return types to locate
// the correct variant.
sig := m.Type().(*types.Signature)
params := sig.Params()
// Convert Go parameter types to their Java counterparts, if possible.
var jparams []*java.Type
i := 0
if hasThis {
i = 1
}
for ; i < params.Len(); i++ {
jparams = append(jparams, j.toJavaType(params.At(i).Type()))
}
var ret *java.Type
var throws bool
if results := sig.Results(); results.Len() > 0 {
ret = j.toJavaType(results.At(0).Type())
if results.Len() > 1 {
throws = isErrorType(results.At(1).Type())
}
}
loop:
for _, f := range jm.Funcs {
if len(f.Params) != len(jparams) {
continue
}
if throws != (f.Throws != "") {
continue
}
if !reflect.DeepEqual(ret, f.Ret) {
continue
}
for i, p := range f.Params {
if !reflect.DeepEqual(p, jparams[i]) {
continue loop
}
}
return f
}
return nil
}
// ClassNames returns the list of names of the generated Java classes and interfaces.
func (g *JavaGen) ClassNames() []string {
var names []string
for _, s := range g.structs {
names = append(names, g.javaTypeName(s.obj.Name()))
}
for _, iface := range g.interfaces {
names = append(names, g.javaTypeName(iface.obj.Name()))
}
return names
}
func (g *JavaGen) GenClass(idx int) error {
ns := len(g.structs)
if idx < ns {
s := g.structs[idx]
g.genStruct(s)
} else {
iface := g.interfaces[idx-ns]
g.genInterface(iface)
}
if len(g.err) > 0 {
return g.err
}
return nil
}
func (g *JavaGen) genProxyImpl(name string) {
g.Printf("private final int refnum;\n\n")
g.Printf("@Override public final int incRefnum() {\n")
g.Printf(" Seq.incGoRef(refnum, this);\n")
g.Printf(" return refnum;\n")
g.Printf("}\n\n")
}
func (g *JavaGen) genStruct(s structInfo) {
pkgPath := ""
if g.Pkg != nil {
pkgPath = g.Pkg.Path()
}
n := g.javaTypeName(s.obj.Name())
g.Printf(javaPreamble, g.javaPkgName(g.Pkg), n, g.gobindOpts(), pkgPath)
fields := exportedFields(s.t)
methods := exportedMethodSet(types.NewPointer(s.obj.Type()))
var impls []string
jinf := g.jstructs[s.obj]
if jinf != nil {
impls = append(impls, "Seq.GoObject")
for _, cls := range jinf.supers {
if cls.Interface {
impls = append(impls, g.javaTypeName(cls.Name))
}
}
} else {
impls = append(impls, "Seq.Proxy")
}
pT := types.NewPointer(s.obj.Type())
for _, iface := range g.allIntf {
if types.AssignableTo(pT, iface.obj.Type()) {
n := iface.obj.Name()
if p := iface.obj.Pkg(); p != g.Pkg {
if n == JavaClassName(p) {
n = n + "_"
}
n = fmt.Sprintf("%s.%s", g.javaPkgName(p), n)
} else {
n = g.javaTypeName(n)
}
impls = append(impls, n)
}
}
doc := g.docs[n]
g.javadoc(doc.Doc())
g.Printf("public final class %s", n)
if jinf != nil {
if jinf.extends != nil {
g.Printf(" extends %s", g.javaTypeName(jinf.extends.Name))
}
}
if len(impls) > 0 {
g.Printf(" implements %s", strings.Join(impls, ", "))
}
g.Printf(" {\n")
g.Indent()
g.Printf("static { %s.touch(); }\n\n", g.className())
g.genProxyImpl(n)
cons := g.constructors[s.obj]
for _, f := range cons {
if !g.isConsSigSupported(f.Type()) {
g.Printf("// skipped constructor %s.%s with unsupported parameter or return types\n\n", n, f.Name())
continue
}
g.genConstructor(f, n, jinf != nil)
}
if jinf == nil || jinf.genNoargCon {
// constructor for Go instantiated instances.
g.Printf("%s(int refnum) { this.refnum = refnum; Seq.trackGoRef(refnum, this); }\n\n", n)
if len(cons) == 0 {
// Generate default no-arg constructor
g.Printf("public %s() { this.refnum = __New(); Seq.trackGoRef(refnum, this); }\n\n", n)
g.Printf("private static native int __New();\n\n")
}
}
for _, f := range fields {
if t := f.Type(); !g.isSupported(t) {
g.Printf("// skipped field %s.%s with unsupported type: %s\n\n", n, f.Name(), t)
continue
}
fdoc := doc.Member(f.Name())
g.javadoc(fdoc)
g.Printf("public final native %s get%s();\n", g.javaType(f.Type()), f.Name())
g.javadoc(fdoc)
g.Printf("public final native void set%s(%s v);\n\n", f.Name(), g.javaType(f.Type()))
}
var isStringer bool
for _, m := range methods {
if !g.isSigSupported(m.Type()) {
g.Printf("// skipped method %s.%s with unsupported parameter or return types\n\n", n, m.Name())
continue
}
g.javadoc(doc.Member(m.Name()))
var jm *java.Func
hasThis := false
if jinf != nil {
hasThis = g.hasThis(n, m)
jm = jinf.lookupMethod(m, hasThis)
if jm != nil {
g.Printf("@Override ")
}
}
g.Printf("public native ")
g.genFuncSignature(m, jm, hasThis)
t := m.Type().(*types.Signature)
isStringer = isStringer || (m.Name() == "String" && t.Params().Len() == 0 && t.Results().Len() == 1 &&
types.Identical(t.Results().At(0).Type(), types.Typ[types.String]))
}
if jinf == nil {
g.genObjectMethods(n, fields, isStringer)
}
g.Outdent()
g.Printf("}\n\n")
}
// isConsSigSupported reports whether the generators can handle a given
// constructor signature.
func (g *JavaGen) isConsSigSupported(t types.Type) bool {
if !g.isSigSupported(t) {
return false
}
// Skip constructors taking a single int32 argument
// since they clash with the proxy constructors that
// take a refnum.
params := t.(*types.Signature).Params()
if params.Len() != 1 {
return true
}
if t, ok := params.At(0).Type().(*types.Basic); ok {
switch t.Kind() {
case types.Int32, types.Uint32:
return false
}
}
return true
}
// javaTypeName returns the class name of a given Go type name. If
// the type name clashes with the package class name, an underscore is
// appended.
func (g *JavaGen) javaTypeName(n string) string {
if n == JavaClassName(g.Pkg) {
return n + "_"
}
return n
}
func (g *JavaGen) javadoc(doc string) {
if doc == "" {
return
}
// JavaDoc expects HTML-escaped documentation.
g.Printf("/**\n * %s */\n", html.EscapeString(doc))
}
// hasThis reports whether a method has an implicit "this" parameter.
func (g *JavaGen) hasThis(sName string, m *types.Func) bool {
sig := m.Type().(*types.Signature)
params := sig.Params()
if params.Len() == 0 {
return false
}
v := params.At(0)
if v.Name() != "this" {
return false
}
t, ok := v.Type().(*types.Named)
if !ok {
return false
}
obj := t.Obj()
pkg := obj.Pkg()
if pkgFirstElem(pkg) != "Java" {
return false
}
clsName := classNameFor(t)
exp := g.javaPkgName(g.Pkg) + "." + sName
if clsName != exp {
g.errorf("the type %s of the `this` argument to method %s.%s is not %s", clsName, sName, m.Name(), exp)
return false
}
return true
}
func (g *JavaGen) genConstructor(f *types.Func, n string, jcls bool) {
g.javadoc(g.docs[f.Name()].Doc())
g.Printf("public %s(", n)
g.genFuncArgs(f, nil, false)
g.Printf(") {\n")
g.Indent()
sig := f.Type().(*types.Signature)
params := sig.Params()
if jcls {
g.Printf("super(")
for i := 0; i < params.Len(); i++ {
if i > 0 {
g.Printf(", ")
}
g.Printf("%s", g.paramName(params, i))
}
g.Printf(");\n")
}
g.Printf("this.refnum = ")
g.Printf("__%s(", f.Name())
for i := 0; i < params.Len(); i++ {
if i > 0 {
g.Printf(", ")
}
g.Printf("%s", g.paramName(params, i))
}
g.Printf(");\n")
g.Printf("Seq.trackGoRef(refnum, this);\n")
g.Outdent()
g.Printf("}\n\n")
g.Printf("private static native int __%s(", f.Name())
g.genFuncArgs(f, nil, false)
g.Printf(");\n\n")
}
// genFuncArgs generated Java function arguments declaration for the function f.
// If the supplied overridden java function is supplied, genFuncArgs omits the implicit
// this argument.
func (g *JavaGen) genFuncArgs(f *types.Func, jm *java.Func, hasThis bool) {
sig := f.Type().(*types.Signature)
params := sig.Params()
first := 0
if hasThis {
// Skip the implicit this argument to the Go method
first = 1
}
for i := first; i < params.Len(); i++ {
if i > first {
g.Printf(", ")
}
v := params.At(i)
name := g.paramName(params, i)
jt := g.javaType(v.Type())
g.Printf("%s %s", jt, name)
}
}
func (g *JavaGen) genObjectMethods(n string, fields []*types.Var, isStringer bool) {
g.Printf("@Override public boolean equals(Object o) {\n")
g.Indent()
g.Printf("if (o == null || !(o instanceof %s)) {\n return false;\n}\n", n)
g.Printf("%s that = (%s)o;\n", n, n)
for _, f := range fields {
if t := f.Type(); !g.isSupported(t) {
g.Printf("// skipped field %s.%s with unsupported type: %s\n\n", n, f.Name(), t)
continue
}
nf := f.Name()
g.Printf("%s this%s = get%s();\n", g.javaType(f.Type()), nf, nf)
g.Printf("%s that%s = that.get%s();\n", g.javaType(f.Type()), nf, nf)
if isJavaPrimitive(f.Type()) {
g.Printf("if (this%s != that%s) {\n return false;\n}\n", nf, nf)
} else {
g.Printf("if (this%s == null) {\n", nf)
g.Indent()
g.Printf("if (that%s != null) {\n return false;\n}\n", nf)
g.Outdent()
g.Printf("} else if (!this%s.equals(that%s)) {\n return false;\n}\n", nf, nf)
}
}
g.Printf("return true;\n")
g.Outdent()
g.Printf("}\n\n")
g.Printf("@Override public int hashCode() {\n")
g.Printf(" return java.util.Arrays.hashCode(new Object[] {")
idx := 0
for _, f := range fields {
if t := f.Type(); !g.isSupported(t) {
continue
}
if idx > 0 {
g.Printf(", ")
}
idx++
g.Printf("get%s()", f.Name())
}
g.Printf("});\n")
g.Printf("}\n\n")
g.Printf("@Override public String toString() {\n")
g.Indent()
if isStringer {
g.Printf("return string();\n")
} else {
g.Printf("StringBuilder b = new StringBuilder();\n")
g.Printf(`b.append("%s").append("{");`, n)
g.Printf("\n")
for _, f := range fields {
if t := f.Type(); !g.isSupported(t) {
continue
}
n := f.Name()
g.Printf(`b.append("%s:").append(get%s()).append(",");`, n, n)
g.Printf("\n")
}
g.Printf(`return b.append("}").toString();`)
g.Printf("\n")
}
g.Outdent()
g.Printf("}\n")
}
func (g *JavaGen) genInterface(iface interfaceInfo) {
pkgPath := ""
if g.Pkg != nil {
pkgPath = g.Pkg.Path()
}
g.Printf(javaPreamble, g.javaPkgName(g.Pkg), g.javaTypeName(iface.obj.Name()), g.gobindOpts(), pkgPath)
var exts []string
numM := iface.t.NumMethods()
for _, other := range g.allIntf {
// Only extend interfaces with fewer methods to avoid circular references
if other.t.NumMethods() < numM && types.AssignableTo(iface.t, other.t) {
n := other.obj.Name()
if p := other.obj.Pkg(); p != g.Pkg {
if n == JavaClassName(p) {
n = n + "_"
}
n = fmt.Sprintf("%s.%s", g.javaPkgName(p), n)
} else {
n = g.javaTypeName(n)
}
exts = append(exts, n)
}
}
doc := g.docs[iface.obj.Name()]
g.javadoc(doc.Doc())
g.Printf("public interface %s", g.javaTypeName(iface.obj.Name()))
if len(exts) > 0 {
g.Printf(" extends %s", strings.Join(exts, ", "))
}
g.Printf(" {\n")
g.Indent()
for _, m := range iface.summary.callable {
if !g.isSigSupported(m.Type()) {
g.Printf("// skipped method %s.%s with unsupported parameter or return types\n\n", iface.obj.Name(), m.Name())
continue
}
g.javadoc(doc.Member(m.Name()))
g.Printf("public ")
g.genFuncSignature(m, nil, false)
}
g.Printf("\n")
g.Outdent()
g.Printf("}\n\n")
}
func isJavaPrimitive(T types.Type) bool {
b, ok := T.(*types.Basic)
if !ok {
return false
}
switch b.Kind() {
case types.Bool, types.Uint8, types.Float32, types.Float64,
types.Int, types.Int8, types.Int16, types.Int32, types.Int64:
return true
}
return false
}
// jniType returns a string that can be used as a JNI type.
func (g *JavaGen) jniType(T types.Type) string {
switch T := T.(type) {
case *types.Basic:
switch T.Kind() {
case types.Bool, types.UntypedBool:
return "jboolean"
case types.Int:
return "jlong"
case types.Int8:
return "jbyte"
case types.Int16:
return "jshort"
case types.Int32, types.UntypedRune: // types.Rune
return "jint"
case types.Int64, types.UntypedInt:
return "jlong"
case types.Uint8: // types.Byte
// TODO(crawshaw): Java bytes are signed, so this is
// questionable, but vital.
return "jbyte"
// TODO(crawshaw): case types.Uint, types.Uint16, types.Uint32, types.Uint64:
case types.Float32:
return "jfloat"
case types.Float64, types.UntypedFloat:
return "jdouble"
case types.String, types.UntypedString:
return "jstring"
default:
g.errorf("unsupported basic type: %s", T)
return "TODO"
}
case *types.Slice:
return "jbyteArray"
case *types.Pointer:
if _, ok := T.Elem().(*types.Named); ok {
return g.jniType(T.Elem())
}
g.errorf("unsupported pointer to type: %s", T)
case *types.Named:
return "jobject"
default:
g.errorf("unsupported jniType: %#+v, %s\n", T, T)
}
return "TODO"
}
func (g *JavaGen) javaBasicType(T *types.Basic) string {
switch T.Kind() {
case types.Bool, types.UntypedBool:
return "boolean"
case types.Int:
return "long"
case types.Int8:
return "byte"
case types.Int16:
return "short"
case types.Int32, types.UntypedRune: // types.Rune
return "int"
case types.Int64, types.UntypedInt:
return "long"
case types.Uint8: // types.Byte
// TODO(crawshaw): Java bytes are signed, so this is
// questionable, but vital.
return "byte"
// TODO(crawshaw): case types.Uint, types.Uint16, types.Uint32, types.Uint64:
case types.Float32:
return "float"
case types.Float64, types.UntypedFloat:
return "double"
case types.String, types.UntypedString:
return "String"
default:
g.errorf("unsupported basic type: %s", T)
return "TODO"
}
}
// javaType returns a string that can be used as a Java type.
func (g *JavaGen) javaType(T types.Type) string {
if isErrorType(T) {
// The error type is usually translated into an exception in
// Java, however the type can be exposed in other ways, such
// as an exported field.
return "java.lang.Exception"
} else if isJavaType(T) {
return classNameFor(T)
}
switch T := T.(type) {
case *types.Basic:
return g.javaBasicType(T)
case *types.Slice:
elem := g.javaType(T.Elem())
return elem + "[]"
case *types.Pointer:
if _, ok := T.Elem().(*types.Named); ok {
return g.javaType(T.Elem())
}
g.errorf("unsupported pointer to type: %s", T)
case *types.Named:
n := T.Obj()
nPkg := n.Pkg()
if !isErrorType(T) && !g.validPkg(nPkg) {
g.errorf("type %s is in %s, which is not bound", n.Name(), nPkg)
break
}
// TODO(crawshaw): more checking here
clsName := n.Name()
if nPkg != g.Pkg {
if clsName == JavaClassName(nPkg) {
clsName += "_"
}
return fmt.Sprintf("%s.%s", g.javaPkgName(nPkg), clsName)
} else {
return g.javaTypeName(clsName)
}
default:
g.errorf("unsupported javaType: %#+v, %s\n", T, T)
}
return "TODO"
}
func (g *JavaGen) genJNIFuncSignature(o *types.Func, sName string, jm *java.Func, proxy, isjava bool) {
sig := o.Type().(*types.Signature)
res := sig.Results()
var ret string
switch res.Len() {
case 2:
ret = g.jniType(res.At(0).Type())
case 1:
if isErrorType(res.At(0).Type()) {
ret = "void"
} else {
ret = g.jniType(res.At(0).Type())
}
case 0:
ret = "void"
default:
g.errorf("too many result values: %s", o)
return
}
g.Printf("JNIEXPORT %s JNICALL\n", ret)
g.Printf("Java_%s_", g.jniPkgName())
if sName != "" {
if proxy {
g.Printf("%s", java.JNIMangle(g.className()))
// 0024 is the mangled form of $, for naming inner classes.
g.Printf("_00024proxy%s", sName)
} else {
g.Printf("%s", java.JNIMangle(g.javaTypeName(sName)))
}
} else {
g.Printf("%s", java.JNIMangle(g.className()))
}
g.Printf("_")
if jm != nil {
g.Printf("%s", jm.JNIName)
} else {
oName := javaNameReplacer(lowerFirst(o.Name()))
g.Printf("%s", java.JNIMangle(oName))
}
g.Printf("(JNIEnv* env, ")
if sName != "" {
g.Printf("jobject __this__")
} else {
g.Printf("jclass _clazz")
}
params := sig.Params()
i := 0
if isjava && params.Len() > 0 && params.At(0).Name() == "this" {
// Skip the implicit this argument, if any.
i = 1
}
for ; i < params.Len(); i++ {
g.Printf(", ")
v := sig.Params().At(i)
name := g.paramName(params, i)
jt := g.jniType(v.Type())
g.Printf("%s %s", jt, name)
}
g.Printf(")")
}
func (g *JavaGen) jniPkgName() string {
return strings.Replace(java.JNIMangle(g.javaPkgName(g.Pkg)), ".", "_", -1)
}
var javaLetterDigitRE = regexp.MustCompile(`[0-9a-zA-Z$_]`)
func (g *JavaGen) paramName(params *types.Tuple, pos int) string {
name := basicParamName(params, pos)
if !javaLetterDigitRE.MatchString(name) {
name = fmt.Sprintf("p%d", pos)
}
return javaNameReplacer(name)
}
func (g *JavaGen) genFuncSignature(o *types.Func, jm *java.Func, hasThis bool) {
sig := o.Type().(*types.Signature)
res := sig.Results()
var returnsError bool
var ret string
switch res.Len() {
case 2:
if !isErrorType(res.At(1).Type()) {
g.errorf("second result value must be of type error: %s", o)
return
}
returnsError = true
ret = g.javaType(res.At(0).Type())
case 1:
if isErrorType(res.At(0).Type()) {
returnsError = true
ret = "void"
} else {
ret = g.javaType(res.At(0).Type())
}
case 0:
ret = "void"
default:
g.errorf("too many result values: %s", o)
return
}
g.Printf("%s ", ret)
if jm != nil {
g.Printf("%s", jm.Name)
} else {
g.Printf("%s", javaNameReplacer(lowerFirst(o.Name())))
}
g.Printf("(")
g.genFuncArgs(o, jm, hasThis)
g.Printf(")")
if returnsError {
if jm != nil {
if jm.Throws == "" {
g.errorf("%s declares an error return value but the overridden method does not throw", o)
return
}
g.Printf(" throws %s", jm.Throws)
} else {
g.Printf(" throws Exception")
}
}
g.Printf(";\n")
}
func (g *JavaGen) genVar(o *types.Var) {
if t := o.Type(); !g.isSupported(t) {
g.Printf("// skipped variable %s with unsupported type: %s\n\n", o.Name(), t)
return
}
jType := g.javaType(o.Type())
doc := g.docs[o.Name()].Doc()
// setter
g.javadoc(doc)
g.Printf("public static native void set%s(%s v);\n", o.Name(), jType)
// getter
g.javadoc(doc)
g.Printf("public static native %s get%s();\n\n", jType, o.Name())
}
// genCRetClear clears the result value from a JNI call if an exception was
// raised.
func (g *JavaGen) genCRetClear(varName string, t types.Type, exc string) {
g.Printf("if (%s != NULL) {\n", exc)
g.Indent()
switch t := t.(type) {
case *types.Basic:
switch t.Kind() {
case types.String:
g.Printf("%s = NULL;\n", varName)
default:
g.Printf("%s = 0;\n", varName)
}
case *types.Slice, *types.Named, *types.Pointer:
g.Printf("%s = NULL;\n", varName)
}
g.Outdent()
g.Printf("}\n")
}
func (g *JavaGen) genJavaToC(varName string, t types.Type, mode varMode) {
switch t := t.(type) {
case *types.Basic:
switch t.Kind() {
case types.String:
g.Printf("nstring _%s = go_seq_from_java_string(env, %s);\n", varName, varName)
default:
g.Printf("%s _%s = (%s)%s;\n", g.cgoType(t), varName, g.cgoType(t), varName)
}
case *types.Slice:
switch e := t.Elem().(type) {
case *types.Basic:
switch e.Kind() {
case types.Uint8: // Byte.
g.Printf("nbyteslice _%s = go_seq_from_java_bytearray(env, %s, %d);\n", varName, varName, toCFlag(mode == modeRetained))
default:
g.errorf("unsupported type: %s", t)
}
default:
g.errorf("unsupported type: %s", t)
}
case *types.Named:
switch u := t.Underlying().(type) {
case *types.Interface:
g.Printf("int32_t _%s = go_seq_to_refnum(env, %s);\n", varName, varName)
default:
g.errorf("unsupported named type: %s / %T", u, u)
}
case *types.Pointer:
g.Printf("int32_t _%s = go_seq_to_refnum(env, %s);\n", varName, varName)
default:
g.Printf("%s _%s = (%s)%s;\n", g.cgoType(t), varName, g.cgoType(t), varName)
}
}
func (g *JavaGen) genCToJava(toName, fromName string, t types.Type, mode varMode) {
switch t := t.(type) {
case *types.Basic:
switch t.Kind() {
case types.String:
g.Printf("jstring %s = go_seq_to_java_string(env, %s);\n", toName, fromName)
case types.Bool:
g.Printf("jboolean %s = %s ? JNI_TRUE : JNI_FALSE;\n", toName, fromName)
default:
g.Printf("%s %s = (%s)%s;\n", g.jniType(t), toName, g.jniType(t), fromName)
}
case *types.Slice:
switch e := t.Elem().(type) {
case *types.Basic:
switch e.Kind() {
case types.Uint8: // Byte.
g.Printf("jbyteArray %s = go_seq_to_java_bytearray(env, %s, %d);\n", toName, fromName, toCFlag(mode == modeRetained))
default:
g.errorf("unsupported type: %s", t)
}
default:
g.errorf("unsupported type: %s", t)
}
case *types.Pointer:
// TODO(crawshaw): test *int
// TODO(crawshaw): test **Generator
switch t := t.Elem().(type) {
case *types.Named:
g.genFromRefnum(toName, fromName, t, t.Obj())
default:
g.errorf("unsupported type %s", t)
}
case *types.Named:
switch t.Underlying().(type) {
case *types.Interface, *types.Pointer:
g.genFromRefnum(toName, fromName, t, t.Obj())
default:
g.errorf("unsupported, direct named type %s", t)
}
default:
g.Printf("%s %s = (%s)%s;\n", g.jniType(t), toName, g.jniType(t), fromName)
}
}
func (g *JavaGen) genFromRefnum(toName, fromName string, t types.Type, o *types.TypeName) {
oPkg := o.Pkg()
isJava := isJavaType(o.Type())
if !isErrorType(o.Type()) && !g.validPkg(oPkg) && !isJava {
g.errorf("type %s is defined in package %s, which is not bound", t, oPkg)
return
}
p := pkgPrefix(oPkg)
g.Printf("jobject %s = go_seq_from_refnum(env, %s, ", toName, fromName)
if isJava {
g.Printf("NULL, NULL")
} else {
g.Printf("proxy_class_%s_%s, proxy_class_%s_%s_cons", p, o.Name(), p, o.Name())
}
g.Printf(");\n")
}
func (g *JavaGen) gobindOpts() string {
opts := []string{"-lang=java"}
if g.JavaPkg != "" {
opts = append(opts, "-javapkg="+g.JavaPkg)
}