java.go 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183
  1. // Copyright 2016 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // The java package takes the result of an AST traversal by the
  5. // importers package and queries the java command for the type
  6. // information for the referenced Java classes and interfaces.
  7. //
  8. // It is the of go/types for Java types and is used by the bind
  9. // package to generate Go wrappers for Java API on Android.
  10. package java
  11. import (
  12. "bufio"
  13. "bytes"
  14. "errors"
  15. "fmt"
  16. "os/exec"
  17. "reflect"
  18. "strings"
  19. "unicode"
  20. "unicode/utf8"
  21. "golang.org/x/mobile/internal/importers"
  22. )
  23. // Class is the bind representation of a Java class or
  24. // interface.
  25. // Use Import to convert class references to Class.
  26. type Class struct {
  27. // "java.pkg.Class.Inner"
  28. Name string
  29. // "java.pkg.Class$Inner"
  30. FindName string
  31. // JNI mangled name
  32. JNIName string
  33. // "Inner"
  34. PkgName string
  35. Funcs []*FuncSet
  36. Methods []*FuncSet
  37. // funcMap maps function names.
  38. funcMap map[string]*FuncSet
  39. // FuncMap maps method names.
  40. methodMap map[string]*FuncSet
  41. // All methods, including methods from
  42. // supers.
  43. AllMethods []*FuncSet
  44. Vars []*Var
  45. Supers []string
  46. Final bool
  47. Abstract bool
  48. Interface bool
  49. Throwable bool
  50. // Whether the class has a no-arg constructor
  51. HasNoArgCon bool
  52. }
  53. // FuncSet is the set of overloaded variants of a function.
  54. // If the function is not overloaded, its FuncSet contains
  55. // one entry.
  56. type FuncSet struct {
  57. Name string
  58. GoName string
  59. Funcs []*Func
  60. CommonSig
  61. }
  62. // CommonSig is a signature compatible with every
  63. // overloaded variant of a FuncSet.
  64. type CommonSig struct {
  65. // Variadic is set if the signature covers variants
  66. // with varying number of parameters.
  67. Variadic bool
  68. // HasRet is true if at least one variant returns a
  69. // value.
  70. HasRet bool
  71. Throws bool
  72. Params []*Type
  73. Ret *Type
  74. }
  75. // Func is a Java static function or method or constructor.
  76. type Func struct {
  77. FuncSig
  78. ArgDesc string
  79. // Mangled JNI name
  80. JNIName string
  81. Static bool
  82. Abstract bool
  83. Final bool
  84. Public bool
  85. Constructor bool
  86. Params []*Type
  87. Ret *Type
  88. Decl string
  89. Throws string
  90. }
  91. // FuncSig uniquely identifies a Java Func.
  92. type FuncSig struct {
  93. Name string
  94. // The method descriptor, in JNI format.
  95. Desc string
  96. }
  97. // Var is a Java member variable.
  98. type Var struct {
  99. Name string
  100. Static bool
  101. Final bool
  102. Val string
  103. Type *Type
  104. }
  105. // Type is a Java type.
  106. type Type struct {
  107. Kind TypeKind
  108. Class string
  109. Elem *Type
  110. }
  111. type TypeKind int
  112. type Importer struct {
  113. Bootclasspath string
  114. Classpath string
  115. // JavaPkg is java package name for generated classes.
  116. JavaPkg string
  117. clsMap map[string]*Class
  118. }
  119. // funcRef is a reference to a Java function (static method).
  120. // It is used as a key to filter unused Java functions.
  121. type funcRef struct {
  122. clsName string
  123. goName string
  124. }
  125. type errClsNotFound struct {
  126. name string
  127. }
  128. const (
  129. Int TypeKind = iota
  130. Boolean
  131. Short
  132. Char
  133. Byte
  134. Long
  135. Float
  136. Double
  137. String
  138. Array
  139. Object
  140. )
  141. func (e *errClsNotFound) Error() string {
  142. return "class not found: " + e.name
  143. }
  144. // IsAvailable reports whether the required tools are available for
  145. // Import to work. In particular, IsAvailable checks the existence
  146. // of the javap binary.
  147. func IsAvailable() bool {
  148. _, err := javapPath()
  149. return err == nil
  150. }
  151. func javapPath() (string, error) {
  152. return exec.LookPath("javap")
  153. }
  154. // Import returns Java Class descriptors for a list of references.
  155. //
  156. // The javap command from the Java SDK is used to dump
  157. // class information. Its output looks like this:
  158. //
  159. // Compiled from "System.java"
  160. // public final class java.lang.System {
  161. //
  162. // public static final java.io.InputStream in;
  163. // descriptor: Ljava/io/InputStream;
  164. // public static final java.io.PrintStream out;
  165. // descriptor: Ljava/io/PrintStream;
  166. // public static final java.io.PrintStream err;
  167. // descriptor: Ljava/io/PrintStream;
  168. // public static void setIn(java.io.InputStream);
  169. // descriptor: (Ljava/io/InputStream;)V
  170. //
  171. // ...
  172. //
  173. // }
  174. func (j *Importer) Import(refs *importers.References) ([]*Class, error) {
  175. if j.clsMap == nil {
  176. j.clsMap = make(map[string]*Class)
  177. }
  178. clsSet := make(map[string]struct{})
  179. var names []string
  180. for _, ref := range refs.Refs {
  181. // The reference could be to some/pkg.Class or some/pkg/Class.Identifier. Include both.
  182. pkg := strings.Replace(ref.Pkg, "/", ".", -1)
  183. for _, cls := range []string{pkg, pkg + "." + ref.Name} {
  184. if _, exists := clsSet[cls]; !exists {
  185. clsSet[cls] = struct{}{}
  186. names = append(names, cls)
  187. }
  188. }
  189. }
  190. // Make sure toString() is included; it is called when wrapping Java exception types to Go
  191. // errors.
  192. refs.Names["ToString"] = struct{}{}
  193. funcRefs := make(map[funcRef]struct{})
  194. for _, ref := range refs.Refs {
  195. pkgName := strings.Replace(ref.Pkg, "/", ".", -1)
  196. funcRefs[funcRef{pkgName, ref.Name}] = struct{}{}
  197. }
  198. classes, err := j.importClasses(names, true)
  199. if err != nil {
  200. return nil, err
  201. }
  202. j.filterReferences(classes, refs, funcRefs)
  203. supers, err := j.importReferencedClasses(classes)
  204. if err != nil {
  205. return nil, err
  206. }
  207. j.filterReferences(supers, refs, funcRefs)
  208. // Embedders refer to every exported Go struct that will have its class
  209. // generated. Allow Go code to reverse bind to those classes by synthesizing
  210. // their class descriptors.
  211. for _, emb := range refs.Embedders {
  212. n := emb.Pkg + "." + emb.Name
  213. if j.JavaPkg != "" {
  214. n = j.JavaPkg + "." + n
  215. }
  216. if _, exists := j.clsMap[n]; exists {
  217. continue
  218. }
  219. clsSet[n] = struct{}{}
  220. cls := &Class{
  221. Name: n,
  222. FindName: n,
  223. JNIName: JNIMangle(n),
  224. PkgName: emb.Name,
  225. HasNoArgCon: true,
  226. }
  227. for _, ref := range emb.Refs {
  228. jpkg := strings.Replace(ref.Pkg, "/", ".", -1)
  229. super := jpkg + "." + ref.Name
  230. if _, exists := j.clsMap[super]; !exists {
  231. return nil, fmt.Errorf("failed to find Java class %s, embedded by %s", super, n)
  232. }
  233. cls.Supers = append(cls.Supers, super)
  234. }
  235. classes = append(classes, cls)
  236. j.clsMap[cls.Name] = cls
  237. }
  238. // Include implicit classes that are used in parameter or return values.
  239. for _, cls := range classes {
  240. for _, fsets := range [][]*FuncSet{cls.Funcs, cls.Methods} {
  241. for _, fs := range fsets {
  242. for _, f := range fs.Funcs {
  243. names := j.implicitFuncTypes(f)
  244. for _, name := range names {
  245. if _, exists := clsSet[name]; exists {
  246. continue
  247. }
  248. clsSet[name] = struct{}{}
  249. classes = append(classes, j.clsMap[name])
  250. }
  251. }
  252. }
  253. }
  254. }
  255. for _, cls := range j.clsMap {
  256. j.fillFuncSigs(cls.Funcs)
  257. j.fillFuncSigs(cls.Methods)
  258. for _, m := range cls.Methods {
  259. j.fillSuperSigs(cls, m)
  260. }
  261. }
  262. for _, cls := range j.clsMap {
  263. j.fillAllMethods(cls)
  264. }
  265. // Include classes that appear as ancestor types for overloaded signatures.
  266. for _, cls := range classes {
  267. for _, funcs := range [][]*FuncSet{cls.Funcs, cls.AllMethods} {
  268. for _, f := range funcs {
  269. for _, p := range f.Params {
  270. if p == nil || p.Kind != Object {
  271. continue
  272. }
  273. if _, exists := clsSet[p.Class]; !exists {
  274. clsSet[p.Class] = struct{}{}
  275. classes = append(classes, j.clsMap[p.Class])
  276. }
  277. }
  278. if t := f.Ret; t != nil && t.Kind == Object {
  279. if _, exists := clsSet[t.Class]; !exists {
  280. clsSet[t.Class] = struct{}{}
  281. classes = append(classes, j.clsMap[t.Class])
  282. }
  283. }
  284. }
  285. }
  286. }
  287. for _, cls := range classes {
  288. j.fillJNINames(cls.Funcs)
  289. j.fillJNINames(cls.AllMethods)
  290. }
  291. j.fillThrowables(classes)
  292. return classes, nil
  293. }
  294. func (j *Importer) fillJNINames(funcs []*FuncSet) {
  295. for _, fs := range funcs {
  296. for _, f := range fs.Funcs {
  297. f.JNIName = JNIMangle(f.Name)
  298. if len(fs.Funcs) > 1 {
  299. f.JNIName += "__" + JNIMangle(f.ArgDesc)
  300. }
  301. }
  302. }
  303. }
  304. // commonType finds the most specific type common to t1 and t2.
  305. // If t1 and t2 are both Java classes, the most specific ancestor
  306. // class is returned.
  307. // Else if the types are equal, their type is returned.
  308. // Finally, nil is returned, indicating no common type.
  309. func commonType(clsMap map[string]*Class, t1, t2 *Type) *Type {
  310. if t1 == nil || t2 == nil {
  311. return nil
  312. }
  313. if reflect.DeepEqual(t1, t2) {
  314. return t1
  315. }
  316. if t1.Kind != Object || t2.Kind != Object {
  317. // The types are fundamentally incompatible
  318. return nil
  319. }
  320. superSet := make(map[string]struct{})
  321. supers := []string{t1.Class}
  322. for len(supers) > 0 {
  323. var newSupers []string
  324. for _, s := range supers {
  325. cls := clsMap[s]
  326. superSet[s] = struct{}{}
  327. newSupers = append(newSupers, cls.Supers...)
  328. }
  329. supers = newSupers
  330. }
  331. supers = []string{t2.Class}
  332. for len(supers) > 0 {
  333. var newSupers []string
  334. for _, s := range supers {
  335. if _, exists := superSet[s]; exists {
  336. return &Type{Kind: Object, Class: s}
  337. }
  338. cls := clsMap[s]
  339. newSupers = append(newSupers, cls.Supers...)
  340. }
  341. supers = newSupers
  342. }
  343. return &Type{Kind: Object, Class: "java.lang.Object"}
  344. }
  345. // combineSigs finds the most specific function signature
  346. // that covers all its overload variants.
  347. // If a function has only one variant, its common signature
  348. // is the signature of that variant.
  349. func combineSigs(clsMap map[string]*Class, sigs ...CommonSig) CommonSig {
  350. var common CommonSig
  351. minp := len(sigs[0].Params)
  352. for i := 1; i < len(sigs); i++ {
  353. sig := sigs[i]
  354. n := len(sig.Params)
  355. common.Variadic = common.Variadic || sig.Variadic || n != minp
  356. if n < minp {
  357. minp = n
  358. }
  359. }
  360. for i, sig := range sigs {
  361. for j, p := range sig.Params {
  362. idx := j
  363. // If the common signature is variadic, combine all parameters in the
  364. // last parameter type of the shortest parameter list.
  365. if idx > minp {
  366. idx = minp
  367. }
  368. if idx < len(common.Params) {
  369. common.Params[idx] = commonType(clsMap, common.Params[idx], p)
  370. } else {
  371. common.Params = append(common.Params, p)
  372. }
  373. }
  374. common.Throws = common.Throws || sig.Throws
  375. common.HasRet = common.HasRet || sig.HasRet
  376. if i > 0 {
  377. common.Ret = commonType(clsMap, common.Ret, sig.Ret)
  378. } else {
  379. common.Ret = sig.Ret
  380. }
  381. }
  382. return common
  383. }
  384. // fillSuperSigs combines methods signatures with super class signatures,
  385. // to preserve the assignability of classes to their super classes.
  386. //
  387. // For example, the class
  388. //
  389. // class A {
  390. // void f();
  391. // }
  392. //
  393. // is by itself represented by the Go interface
  394. //
  395. // type A interface {
  396. // f()
  397. // }
  398. //
  399. // However, if class
  400. //
  401. // class B extends A {
  402. // void f(int);
  403. // }
  404. //
  405. // is also imported, it will be represented as
  406. //
  407. // type B interface {
  408. // f(...int32)
  409. // }
  410. //
  411. // To make Go B assignable to Go A, the signature of A's f must
  412. // be updated to f(...int32) as well.
  413. func (j *Importer) fillSuperSigs(cls *Class, m *FuncSet) {
  414. for _, s := range cls.Supers {
  415. sup := j.clsMap[s]
  416. if sm, exists := sup.methodMap[m.GoName]; exists {
  417. sm.CommonSig = combineSigs(j.clsMap, sm.CommonSig, m.CommonSig)
  418. }
  419. j.fillSuperSigs(sup, m)
  420. }
  421. }
  422. func (v *Var) Constant() bool {
  423. return v.Static && v.Final && v.Val != ""
  424. }
  425. // Mangle a name according to
  426. // http://docs.oracle.com/javase/6/docs/technotes/guides/jni/spec/design.html#wp16696
  427. //
  428. // TODO: Support unicode characters
  429. func JNIMangle(s string) string {
  430. var m []byte
  431. for i := 0; i < len(s); i++ {
  432. switch c := s[i]; c {
  433. case '.', '/':
  434. m = append(m, '_')
  435. case '$':
  436. m = append(m, "_00024"...)
  437. case '_':
  438. m = append(m, "_1"...)
  439. case ';':
  440. m = append(m, "_2"...)
  441. case '[':
  442. m = append(m, "_3"...)
  443. default:
  444. m = append(m, c)
  445. }
  446. }
  447. return string(m)
  448. }
  449. func (t *Type) Type() string {
  450. switch t.Kind {
  451. case Int:
  452. return "int"
  453. case Boolean:
  454. return "boolean"
  455. case Short:
  456. return "short"
  457. case Char:
  458. return "char"
  459. case Byte:
  460. return "byte"
  461. case Long:
  462. return "long"
  463. case Float:
  464. return "float"
  465. case Double:
  466. return "double"
  467. case String:
  468. return "String"
  469. case Array:
  470. return t.Elem.Type() + "[]"
  471. case Object:
  472. return t.Class
  473. default:
  474. panic("invalid kind")
  475. }
  476. }
  477. func (t *Type) JNIType() string {
  478. switch t.Kind {
  479. case Int:
  480. return "jint"
  481. case Boolean:
  482. return "jboolean"
  483. case Short:
  484. return "jshort"
  485. case Char:
  486. return "jchar"
  487. case Byte:
  488. return "jbyte"
  489. case Long:
  490. return "jlong"
  491. case Float:
  492. return "jfloat"
  493. case Double:
  494. return "jdouble"
  495. case String:
  496. return "jstring"
  497. case Array:
  498. return "jarray"
  499. case Object:
  500. return "jobject"
  501. default:
  502. panic("invalid kind")
  503. }
  504. }
  505. func (t *Type) CType() string {
  506. switch t.Kind {
  507. case Int, Boolean, Short, Char, Byte, Long, Float, Double:
  508. return t.JNIType()
  509. case String:
  510. return "nstring"
  511. case Array:
  512. if t.Elem.Kind != Byte {
  513. panic("unsupported array type")
  514. }
  515. return "nbyteslice"
  516. case Object:
  517. return "jint"
  518. default:
  519. panic("invalid kind")
  520. }
  521. }
  522. func (t *Type) JNICallType() string {
  523. switch t.Kind {
  524. case Int:
  525. return "Int"
  526. case Boolean:
  527. return "Boolean"
  528. case Short:
  529. return "Short"
  530. case Char:
  531. return "Char"
  532. case Byte:
  533. return "Byte"
  534. case Long:
  535. return "Long"
  536. case Float:
  537. return "Float"
  538. case Double:
  539. return "Double"
  540. case String, Object, Array:
  541. return "Object"
  542. default:
  543. panic("invalid kind")
  544. }
  545. }
  546. func (j *Importer) filterReferences(classes []*Class, refs *importers.References, funcRefs map[funcRef]struct{}) {
  547. for _, cls := range classes {
  548. var filtered []*FuncSet
  549. for _, f := range cls.Funcs {
  550. if _, exists := funcRefs[funcRef{cls.Name, f.GoName}]; exists {
  551. filtered = append(filtered, f)
  552. }
  553. }
  554. cls.Funcs = filtered
  555. filtered = nil
  556. for _, m := range cls.Methods {
  557. if _, exists := refs.Names[m.GoName]; exists {
  558. filtered = append(filtered, m)
  559. }
  560. }
  561. cls.Methods = filtered
  562. }
  563. }
  564. // importClasses imports the named classes from the classpaths of the Importer.
  565. func (j *Importer) importClasses(names []string, allowMissingClasses bool) ([]*Class, error) {
  566. if len(names) == 0 {
  567. return nil, nil
  568. }
  569. args := []string{"-J-Duser.language=en", "-s", "-protected", "-constants"}
  570. args = append(args, "-classpath", j.Classpath)
  571. if j.Bootclasspath != "" {
  572. args = append(args, "-bootclasspath", j.Bootclasspath)
  573. }
  574. args = append(args, names...)
  575. javapPath, err := javapPath()
  576. if err != nil {
  577. return nil, err
  578. }
  579. javap := exec.Command(javapPath, args...)
  580. out, err := javap.CombinedOutput()
  581. if err != nil {
  582. if _, ok := err.(*exec.ExitError); !ok {
  583. return nil, fmt.Errorf("javap failed: %v", err)
  584. }
  585. // Not every name is a Java class so an exit error from javap is not
  586. // fatal.
  587. }
  588. s := bufio.NewScanner(bytes.NewBuffer(out))
  589. var classes []*Class
  590. for _, name := range names {
  591. cls, err := j.scanClass(s, name)
  592. if err != nil {
  593. _, notfound := err.(*errClsNotFound)
  594. if notfound && allowMissingClasses {
  595. continue
  596. }
  597. if notfound && name != "android.databinding.DataBindingComponent" {
  598. return nil, err
  599. }
  600. // The Android Databinding library generates android.databinding.DataBindingComponent
  601. // too late in the build process for the gobind plugin to import it. Synthesize a class
  602. // for it instead.
  603. cls = &Class{
  604. Name: name,
  605. FindName: name,
  606. Interface: true,
  607. PkgName: "databinding",
  608. JNIName: JNIMangle(name),
  609. }
  610. }
  611. classes = append(classes, cls)
  612. j.clsMap[name] = cls
  613. }
  614. return classes, nil
  615. }
  616. // importReferencedClasses imports all implicit classes (super types, parameter and
  617. // return types) for the given classes not already imported.
  618. func (j *Importer) importReferencedClasses(classes []*Class) ([]*Class, error) {
  619. var allCls []*Class
  620. // Include methods from extended or implemented classes.
  621. for {
  622. set := make(map[string]struct{})
  623. for _, cls := range classes {
  624. j.unknownImplicitClasses(cls, set)
  625. }
  626. if len(set) == 0 {
  627. break
  628. }
  629. var names []string
  630. for n := range set {
  631. names = append(names, n)
  632. }
  633. newCls, err := j.importClasses(names, false)
  634. if err != nil {
  635. return nil, err
  636. }
  637. allCls = append(allCls, newCls...)
  638. classes = newCls
  639. }
  640. return allCls, nil
  641. }
  642. func (j *Importer) implicitFuncTypes(f *Func) []string {
  643. var unk []string
  644. if rt := f.Ret; rt != nil && rt.Kind == Object {
  645. unk = append(unk, rt.Class)
  646. }
  647. for _, t := range f.Params {
  648. if t.Kind == Object {
  649. unk = append(unk, t.Class)
  650. }
  651. }
  652. return unk
  653. }
  654. func (j *Importer) unknownImplicitClasses(cls *Class, set map[string]struct{}) {
  655. for _, fsets := range [][]*FuncSet{cls.Funcs, cls.Methods} {
  656. for _, fs := range fsets {
  657. for _, f := range fs.Funcs {
  658. names := j.implicitFuncTypes(f)
  659. for _, name := range names {
  660. if _, exists := j.clsMap[name]; !exists {
  661. set[name] = struct{}{}
  662. }
  663. }
  664. }
  665. }
  666. }
  667. for _, n := range cls.Supers {
  668. if s, exists := j.clsMap[n]; exists {
  669. j.unknownImplicitClasses(s, set)
  670. } else {
  671. set[n] = struct{}{}
  672. }
  673. }
  674. }
  675. func (j *Importer) implicitFuncClasses(funcs []*FuncSet, impl []string) []string {
  676. var l []string
  677. for _, fs := range funcs {
  678. for _, f := range fs.Funcs {
  679. if rt := f.Ret; rt != nil && rt.Kind == Object {
  680. l = append(l, rt.Class)
  681. }
  682. for _, t := range f.Params {
  683. if t.Kind == Object {
  684. l = append(l, t.Class)
  685. }
  686. }
  687. }
  688. }
  689. return impl
  690. }
  691. func (j *Importer) scanClass(s *bufio.Scanner, name string) (*Class, error) {
  692. if !s.Scan() {
  693. return nil, fmt.Errorf("%s: missing javap header", name)
  694. }
  695. head := s.Text()
  696. if errPref := "Error: "; strings.HasPrefix(head, errPref) {
  697. msg := head[len(errPref):]
  698. if strings.HasPrefix(msg, "class not found: "+name) {
  699. return nil, &errClsNotFound{name}
  700. }
  701. return nil, errors.New(msg)
  702. }
  703. if !strings.HasPrefix(head, "Compiled from ") {
  704. return nil, fmt.Errorf("%s: unexpected header: %s", name, head)
  705. }
  706. if !s.Scan() {
  707. return nil, fmt.Errorf("%s: missing javap class declaration", name)
  708. }
  709. clsDecl := s.Text()
  710. cls, err := j.scanClassDecl(name, clsDecl)
  711. if err != nil {
  712. return nil, err
  713. }
  714. cls.JNIName = JNIMangle(cls.Name)
  715. clsElems := strings.Split(cls.Name, ".")
  716. cls.PkgName = clsElems[len(clsElems)-1]
  717. var funcs []*Func
  718. for s.Scan() {
  719. decl := strings.TrimSpace(s.Text())
  720. if decl == "}" {
  721. break
  722. } else if decl == "" {
  723. continue
  724. }
  725. if !s.Scan() {
  726. return nil, fmt.Errorf("%s: missing descriptor for member %q", name, decl)
  727. }
  728. desc := strings.TrimSpace(s.Text())
  729. desc = strings.TrimPrefix(desc, "descriptor: ")
  730. var static, final, abstract, public bool
  731. // Trim modifiders from the declaration.
  732. loop:
  733. for {
  734. idx := strings.Index(decl, " ")
  735. if idx == -1 {
  736. break
  737. }
  738. keyword := decl[:idx]
  739. switch keyword {
  740. case "public":
  741. public = true
  742. case "protected", "native":
  743. // ignore
  744. case "static":
  745. static = true
  746. case "final":
  747. final = true
  748. case "abstract":
  749. abstract = true
  750. default:
  751. // Hopefully we reached the declaration now.
  752. break loop
  753. }
  754. decl = decl[idx+1:]
  755. }
  756. // Trim ending ;
  757. decl = decl[:len(decl)-1]
  758. if idx := strings.Index(decl, "("); idx != -1 {
  759. f, err := j.scanMethod(decl, desc, idx)
  760. if err != nil {
  761. return nil, fmt.Errorf("%s: %v", name, err)
  762. }
  763. if f != nil {
  764. f.Static = static
  765. f.Abstract = abstract
  766. f.Public = public || cls.Interface
  767. f.Final = final
  768. f.Constructor = f.Name == cls.FindName
  769. if f.Constructor {
  770. cls.HasNoArgCon = cls.HasNoArgCon || len(f.Params) == 0
  771. f.Public = f.Public && !cls.Abstract
  772. f.Name = "new"
  773. f.Ret = &Type{Class: name, Kind: Object}
  774. }
  775. funcs = append(funcs, f)
  776. }
  777. } else {
  778. // Member is a variable
  779. v, err := j.scanVar(decl, desc)
  780. if err != nil {
  781. return nil, fmt.Errorf("%s: %v", name, err)
  782. }
  783. if v != nil && public {
  784. v.Static = static
  785. v.Final = final
  786. cls.Vars = append(cls.Vars, v)
  787. }
  788. }
  789. }
  790. for _, f := range funcs {
  791. var m map[string]*FuncSet
  792. var l *[]*FuncSet
  793. goName := initialUpper(f.Name)
  794. if f.Static || f.Constructor {
  795. m = cls.funcMap
  796. l = &cls.Funcs
  797. } else {
  798. m = cls.methodMap
  799. l = &cls.Methods
  800. }
  801. fs, exists := m[goName]
  802. if !exists {
  803. fs = &FuncSet{
  804. Name: f.Name,
  805. GoName: goName,
  806. }
  807. m[goName] = fs
  808. *l = append(*l, fs)
  809. }
  810. fs.Funcs = append(fs.Funcs, f)
  811. }
  812. return cls, nil
  813. }
  814. func (j *Importer) scanClassDecl(name string, decl string) (*Class, error) {
  815. isRoot := name == "java.lang.Object"
  816. cls := &Class{
  817. Name: name,
  818. funcMap: make(map[string]*FuncSet),
  819. methodMap: make(map[string]*FuncSet),
  820. HasNoArgCon: isRoot,
  821. }
  822. const (
  823. stMod = iota
  824. stName
  825. stExt
  826. stImpl
  827. )
  828. superClsDecl := isRoot
  829. st := stMod
  830. var w []byte
  831. // if > 0, we're inside a generics declaration
  832. gennest := 0
  833. for i := 0; i < len(decl); i++ {
  834. c := decl[i]
  835. switch c {
  836. default:
  837. if gennest == 0 {
  838. w = append(w, c)
  839. }
  840. case '>':
  841. gennest--
  842. case '<':
  843. gennest++
  844. case '{':
  845. if !superClsDecl && !cls.Interface {
  846. cls.Supers = append(cls.Supers, "java.lang.Object")
  847. }
  848. return cls, nil
  849. case ' ', ',':
  850. if gennest > 0 {
  851. break
  852. }
  853. switch w := string(w); w {
  854. default:
  855. switch st {
  856. case stName:
  857. if strings.Replace(w, "$", ".", -1) != strings.Replace(name, "$", ".", -1) {
  858. return nil, fmt.Errorf("unexpected name %q in class declaration: %q", w, decl)
  859. }
  860. cls.FindName = w
  861. case stExt:
  862. superClsDecl = true
  863. cls.Supers = append(cls.Supers, w)
  864. case stImpl:
  865. if !cls.Interface {
  866. cls.Supers = append(cls.Supers, w)
  867. }
  868. default:
  869. return nil, fmt.Errorf("unexpected %q in class declaration: %q", w, decl)
  870. }
  871. case "":
  872. // skip
  873. case "public":
  874. if st != stMod {
  875. return nil, fmt.Errorf("unexpected %q in class declaration: %q", w, decl)
  876. }
  877. case "abstract":
  878. if st != stMod {
  879. return nil, fmt.Errorf("unexpected %q in class declaration: %q", w, decl)
  880. }
  881. cls.Abstract = true
  882. case "final":
  883. if st != stMod {
  884. return nil, fmt.Errorf("unexpected %q in class declaration: %q", w, decl)
  885. }
  886. cls.Final = true
  887. case "interface":
  888. cls.Interface = true
  889. fallthrough
  890. case "class":
  891. if st != stMod {
  892. return nil, fmt.Errorf("unexpected %q in class declaration: %q", w, decl)
  893. }
  894. st = stName
  895. case "extends":
  896. if st != stName {
  897. return nil, fmt.Errorf("unexpected %q in class declaration: %q", w, decl)
  898. }
  899. st = stExt
  900. case "implements":
  901. if st != stName && st != stExt {
  902. return nil, fmt.Errorf("unexpected %q in class declaration: %q", w, decl)
  903. }
  904. st = stImpl
  905. }
  906. w = w[:0]
  907. }
  908. }
  909. return nil, fmt.Errorf("missing ending { in class declaration: %q", decl)
  910. }
  911. func (j *Importer) scanVar(decl, desc string) (*Var, error) {
  912. v := new(Var)
  913. const eq = " = "
  914. idx := strings.Index(decl, eq)
  915. if idx != -1 {
  916. val, ok := j.parseJavaValue(decl[idx+len(eq):])
  917. if !ok {
  918. // Skip constants that cannot be represented in Go
  919. return nil, nil
  920. }
  921. v.Val = val
  922. } else {
  923. idx = len(decl)
  924. }
  925. for i := idx - 1; i >= 0; i-- {
  926. if i == 0 || decl[i-1] == ' ' {
  927. v.Name = decl[i:idx]
  928. break
  929. }
  930. }
  931. if v.Name == "" {
  932. return nil, fmt.Errorf("unable to parse member name from declaration: %q", decl)
  933. }
  934. typ, _, err := j.parseJavaType(desc)
  935. if err != nil {
  936. return nil, fmt.Errorf("invalid type signature for %s: %q", v.Name, desc)
  937. }
  938. v.Type = typ
  939. return v, nil
  940. }
  941. func (j *Importer) scanMethod(decl, desc string, parenIdx int) (*Func, error) {
  942. // Member is a method
  943. f := new(Func)
  944. f.Desc = desc
  945. for i := parenIdx - 1; i >= 0; i-- {
  946. if i == 0 || decl[i-1] == ' ' {
  947. f.Name = decl[i:parenIdx]
  948. break
  949. }
  950. }
  951. if f.Name == "" {
  952. return nil, fmt.Errorf("unable to parse method name from declaration: %q", decl)
  953. }
  954. if desc[0] != '(' {
  955. return nil, fmt.Errorf("invalid descriptor for method %s: %q", f.Name, desc)
  956. }
  957. const throws = " throws "
  958. if idx := strings.Index(decl, throws); idx != -1 {
  959. f.Throws = decl[idx+len(throws):]
  960. }
  961. i := 1
  962. for desc[i] != ')' {
  963. typ, n, err := j.parseJavaType(desc[i:])
  964. if err != nil {
  965. return nil, fmt.Errorf("invalid descriptor for method %s: %v", f.Name, err)
  966. }
  967. i += n
  968. f.Params = append(f.Params, typ)
  969. }
  970. f.ArgDesc = desc[1:i]
  971. i++ // skip ending )
  972. if desc[i] != 'V' {
  973. typ, _, err := j.parseJavaType(desc[i:])
  974. if err != nil {
  975. return nil, fmt.Errorf("invalid descriptor for method %s: %v", f.Name, err)
  976. }
  977. f.Ret = typ
  978. }
  979. return f, nil
  980. }
  981. func (j *Importer) fillThrowables(classes []*Class) {
  982. thrCls, ok := j.clsMap["java.lang.Throwable"]
  983. if !ok {
  984. // If Throwable isn't in the class map
  985. // no imported class inherits from Throwable
  986. return
  987. }
  988. for _, cls := range classes {
  989. j.fillThrowableFor(cls, thrCls)
  990. }
  991. }
  992. func (j *Importer) fillThrowableFor(cls, thrCls *Class) {
  993. if cls.Interface || cls.Throwable {
  994. return
  995. }
  996. cls.Throwable = cls == thrCls
  997. for _, name := range cls.Supers {
  998. sup := j.clsMap[name]
  999. j.fillThrowableFor(sup, thrCls)
  1000. cls.Throwable = cls.Throwable || sup.Throwable
  1001. }
  1002. }
  1003. func commonSig(f *Func) CommonSig {
  1004. return CommonSig{
  1005. Params: f.Params,
  1006. Ret: f.Ret,
  1007. HasRet: f.Ret != nil,
  1008. Throws: f.Throws != "",
  1009. }
  1010. }
  1011. func (j *Importer) fillFuncSigs(funcs []*FuncSet) {
  1012. for _, fs := range funcs {
  1013. var sigs []CommonSig
  1014. for _, f := range fs.Funcs {
  1015. sigs = append(sigs, commonSig(f))
  1016. }
  1017. fs.CommonSig = combineSigs(j.clsMap, sigs...)
  1018. }
  1019. }
  1020. func (j *Importer) fillAllMethods(cls *Class) {
  1021. if len(cls.AllMethods) > 0 {
  1022. return
  1023. }
  1024. for _, supName := range cls.Supers {
  1025. super := j.clsMap[supName]
  1026. j.fillAllMethods(super)
  1027. }
  1028. var fsets []*FuncSet
  1029. fsets = append(fsets, cls.Methods...)
  1030. for _, supName := range cls.Supers {
  1031. super := j.clsMap[supName]
  1032. fsets = append(fsets, super.AllMethods...)
  1033. }
  1034. sigs := make(map[FuncSig]struct{})
  1035. methods := make(map[string]*FuncSet)
  1036. for _, fs := range fsets {
  1037. clsFs, exists := methods[fs.Name]
  1038. if !exists {
  1039. clsFs = &FuncSet{
  1040. Name: fs.Name,
  1041. GoName: fs.GoName,
  1042. CommonSig: fs.CommonSig,
  1043. }
  1044. cls.AllMethods = append(cls.AllMethods, clsFs)
  1045. methods[fs.Name] = clsFs
  1046. } else {
  1047. // Combine the (overloaded) signature with the other variants.
  1048. clsFs.CommonSig = combineSigs(j.clsMap, clsFs.CommonSig, fs.CommonSig)
  1049. }
  1050. for _, f := range fs.Funcs {
  1051. if _, exists := sigs[f.FuncSig]; exists {
  1052. continue
  1053. }
  1054. sigs[f.FuncSig] = struct{}{}
  1055. clsFs.Funcs = append(clsFs.Funcs, f)
  1056. }
  1057. }
  1058. }
  1059. func (j *Importer) parseJavaValue(v string) (string, bool) {
  1060. v = strings.TrimRight(v, "ldf")
  1061. switch v {
  1062. case "", "NaN", "Infinity", "-Infinity":
  1063. return "", false
  1064. default:
  1065. if v[0] == '\'' {
  1066. // Skip character constants, since they can contain invalid code points
  1067. // that are unacceptable to Go.
  1068. return "", false
  1069. }
  1070. return v, true
  1071. }
  1072. }
  1073. func (j *Importer) parseJavaType(desc string) (*Type, int, error) {
  1074. t := new(Type)
  1075. var n int
  1076. if desc == "" {
  1077. return t, n, errors.New("empty type signature")
  1078. }
  1079. n++
  1080. switch desc[0] {
  1081. case 'Z':
  1082. t.Kind = Boolean
  1083. case 'B':
  1084. t.Kind = Byte
  1085. case 'C':
  1086. t.Kind = Char
  1087. case 'S':
  1088. t.Kind = Short
  1089. case 'I':
  1090. t.Kind = Int
  1091. case 'J':
  1092. t.Kind = Long
  1093. case 'F':
  1094. t.Kind = Float
  1095. case 'D':
  1096. t.Kind = Double
  1097. case 'L':
  1098. var clsName string
  1099. for i := n; i < len(desc); i++ {
  1100. if desc[i] == ';' {
  1101. clsName = strings.Replace(desc[n:i], "/", ".", -1)
  1102. clsName = strings.Replace(clsName, "$", ".", -1)
  1103. n += i - n + 1
  1104. break
  1105. }
  1106. }
  1107. if clsName == "" {
  1108. return t, n, errors.New("missing ; in class type signature")
  1109. }
  1110. if clsName == "java.lang.String" {
  1111. t.Kind = String
  1112. } else {
  1113. t.Kind = Object
  1114. t.Class = clsName
  1115. }
  1116. case '[':
  1117. et, n2, err := j.parseJavaType(desc[n:])
  1118. if err != nil {
  1119. return t, n, err
  1120. }
  1121. n += n2
  1122. t.Kind = Array
  1123. t.Elem = et
  1124. default:
  1125. return t, n, fmt.Errorf("invalid type signature: %s", desc)
  1126. }
  1127. return t, n, nil
  1128. }
  1129. func initialUpper(s string) string {
  1130. if s == "" {
  1131. return ""
  1132. }
  1133. r, n := utf8.DecodeRuneInString(s)
  1134. return string(unicode.ToUpper(r)) + s[n:]
  1135. }