| 1 | // Copyright 2015 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 | |
| 5 | package bind |
| 6 | |
| 7 | import ( |
| 8 | "fmt" |
| 9 | "go/constant" |
| 10 | "go/types" |
| 11 | "math" |
| 12 | "strings" |
| 13 | |
| 14 | "golang.org/x/mobile/internal/importers/objc" |
| 15 | ) |
| 16 | |
| 17 | // TODO(hyangah): handle method name conflicts. |
| 18 | // - struct with SetF method and exported F field. |
| 19 | // - method names conflicting with NSObject methods. e.g. Init |
| 20 | // - interface type with InitWithRef. |
| 21 | |
| 22 | // TODO(hyangah): error code/domain propagation |
| 23 | |
| 24 | type ObjcGen struct { |
| 25 | Prefix string // prefix arg passed by flag. |
| 26 | |
| 27 | *Generator |
| 28 | |
| 29 | // fields set by init. |
| 30 | namePrefix string |
| 31 | // Map of all wrapped Objc types |
| 32 | wrapMap map[string]*objc.Named |
| 33 | // Structs that embeds Objc wrapper types. |
| 34 | ostructs map[*types.TypeName]*objcClassInfo |
| 35 | modules []string |
| 36 | // Constructors is a map from Go struct types to a list |
| 37 | // of exported constructor functions for the type, on the form |
| 38 | // func New<Type>(...) *Type |
| 39 | constructors map[*types.TypeName][]*types.Func |
| 40 | } |
| 41 | |
| 42 | type objcClassInfo struct { |
| 43 | // The Objc class this class extends. |
| 44 | extends *objc.Named |
| 45 | // All classes and protocols this class extends and conforms to. |
| 46 | supers []*objc.Named |
| 47 | methods map[string]*objc.Func |
| 48 | } |
| 49 | |
| 50 | func (g *ObjcGen) Init(wrappers []*objc.Named) { |
| 51 | g.Generator.Init() |
| 52 | g.namePrefix = g.namePrefixOf(g.Pkg) |
| 53 | g.wrapMap = make(map[string]*objc.Named) |
| 54 | g.constructors = make(map[*types.TypeName][]*types.Func) |
| 55 | modMap := make(map[string]struct{}) |
| 56 | for _, w := range wrappers { |
| 57 | g.wrapMap[w.GoName] = w |
| 58 | if _, exists := modMap[w.Module]; !exists { |
| 59 | if !w.Generated { |
| 60 | g.modules = append(g.modules, w.Module) |
| 61 | } |
| 62 | modMap[w.Module] = struct{}{} |
| 63 | } |
| 64 | } |
| 65 | if _, exists := modMap["Foundation"]; !exists { |
| 66 | g.modules = append(g.modules, "Foundation") |
| 67 | } |
| 68 | g.ostructs = make(map[*types.TypeName]*objcClassInfo) |
| 69 | for _, s := range g.structs { |
| 70 | embds := embeddedObjcTypes(s.t) |
| 71 | if len(embds) == 0 { |
| 72 | continue |
| 73 | } |
| 74 | inf := &objcClassInfo{ |
| 75 | methods: make(map[string]*objc.Func), |
| 76 | } |
| 77 | for _, n := range embds { |
| 78 | t := g.wrapMap[n] |
| 79 | for _, f := range t.AllMethods { |
| 80 | inf.methods[f.GoName] = f |
| 81 | } |
| 82 | inf.supers = append(inf.supers, t) |
| 83 | if !t.Protocol { |
| 84 | if inf.extends != nil { |
| 85 | g.errorf("%s embeds more than one ObjC class; only one is allowed.", s.obj) |
| 86 | } |
| 87 | inf.extends = t |
| 88 | } |
| 89 | } |
| 90 | g.ostructs[s.obj] = inf |
| 91 | } |
| 92 | for _, f := range g.funcs { |
| 93 | if t := g.constructorType(f); t != nil { |
| 94 | g.constructors[t] = append(g.constructors[t], f) |
| 95 | } |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | func (g *ObjcGen) namePrefixOf(pkg *types.Package) string { |
| 100 | if pkg == nil { |
| 101 | return "Universe" |
| 102 | } |
| 103 | p := g.Prefix |
| 104 | return p + strings.Title(pkg.Name()) |
| 105 | } |
| 106 | |
| 107 | func (g *ObjcGen) GenGoH() error { |
| 108 | var pkgPath string |
| 109 | if g.Pkg != nil { |
| 110 | pkgPath = g.Pkg.Path() |
| 111 | } |
| 112 | g.Printf(objcPreamble, pkgPath, g.gobindOpts(), pkgPath) |
| 113 | g.Printf("#ifndef __GO_%s_H__\n", g.pkgName) |
| 114 | g.Printf("#define __GO_%s_H__\n\n", g.pkgName) |
| 115 | g.Printf("#include <stdint.h>\n") |
| 116 | g.Printf("#include <objc/objc.h>\n") |
| 117 | |
| 118 | for _, i := range g.interfaces { |
| 119 | if !i.summary.implementable { |
| 120 | continue |
| 121 | } |
| 122 | for _, m := range i.summary.callable { |
| 123 | if !g.isSigSupported(m.Type()) { |
| 124 | g.Printf("// skipped method %s.%s with unsupported parameter or return types\n\n", i.obj.Name(), m.Name()) |
| 125 | continue |
| 126 | } |
| 127 | g.genInterfaceMethodSignature(m, i.obj.Name(), true, g.paramName) |
| 128 | g.Printf("\n") |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | g.Printf("#endif\n") |
| 133 | |
| 134 | if len(g.err) > 0 { |
| 135 | return g.err |
| 136 | } |
| 137 | return nil |
| 138 | } |
| 139 | |
| 140 | func (g *ObjcGen) GenH() error { |
| 141 | var pkgPath string |
| 142 | if g.Pkg != nil { |
| 143 | pkgPath = g.Pkg.Path() |
| 144 | } |
| 145 | g.Printf(objcPreamble, pkgPath, g.gobindOpts(), pkgPath) |
| 146 | g.Printf("#ifndef __%s_H__\n", g.namePrefix) |
| 147 | g.Printf("#define __%s_H__\n", g.namePrefix) |
| 148 | g.Printf("\n") |
| 149 | for _, m := range g.modules { |
| 150 | g.Printf("@import %s;\n", m) |
| 151 | } |
| 152 | g.Printf("#include \"ref.h\"\n") |
| 153 | if g.Pkg != nil { |
| 154 | g.Printf("#include \"Universe.objc.h\"\n\n") |
| 155 | } |
| 156 | |
| 157 | if g.Pkg != nil { |
| 158 | for _, pkg := range g.Pkg.Imports() { |
| 159 | if g.validPkg(pkg) { |
| 160 | g.Printf("#include %q\n", g.namePrefixOf(pkg)+".objc.h") |
| 161 | } |
| 162 | } |
| 163 | } |
| 164 | g.Printf("\n") |
| 165 | |
| 166 | // Forward declaration of @class and @protocol |
| 167 | for _, s := range g.structs { |
| 168 | g.Printf("@class %s%s;\n", g.namePrefix, s.obj.Name()) |
| 169 | } |
| 170 | for _, i := range g.interfaces { |
| 171 | g.Printf("@protocol %s%s;\n", g.namePrefix, i.obj.Name()) |
| 172 | if i.summary.implementable { |
| 173 | g.Printf("@class %s%s;\n", g.namePrefix, i.obj.Name()) |
| 174 | // Forward declaration for other cases will be handled at the beginning of GenM. |
| 175 | } |
| 176 | } |
| 177 | if len(g.structs) > 0 || len(g.interfaces) > 0 { |
| 178 | g.Printf("\n") |
| 179 | } |
| 180 | |
| 181 | // @interfaces |
| 182 | for _, i := range g.interfaces { |
| 183 | g.genInterfaceH(i.obj, i.t) |
| 184 | g.Printf("\n") |
| 185 | } |
| 186 | for _, s := range g.structs { |
| 187 | g.genStructH(s.obj, s.t) |
| 188 | g.Printf("\n") |
| 189 | } |
| 190 | |
| 191 | // const |
| 192 | // TODO: prefix with k?, or use a class method? |
| 193 | for _, obj := range g.constants { |
| 194 | if _, ok := obj.Type().(*types.Basic); !ok || !g.isSupported(obj.Type()) { |
| 195 | g.Printf("// skipped const %s with unsupported type: %s\n\n", obj.Name(), obj.Type()) |
| 196 | continue |
| 197 | } |
| 198 | g.objcdoc(g.docs[obj.Name()].Doc()) |
| 199 | switch b := obj.Type().(*types.Basic); b.Kind() { |
| 200 | case types.String, types.UntypedString: |
| 201 | g.Printf("FOUNDATION_EXPORT NSString* _Nonnull const %s%s;\n", g.namePrefix, obj.Name()) |
| 202 | default: |
| 203 | g.Printf("FOUNDATION_EXPORT const %s %s%s;\n", g.objcType(obj.Type()), g.namePrefix, obj.Name()) |
| 204 | } |
| 205 | } |
| 206 | if len(g.constants) > 0 { |
| 207 | g.Printf("\n") |
| 208 | } |
| 209 | |
| 210 | // var |
| 211 | if len(g.vars) > 0 { |
| 212 | g.Printf("@interface %s : NSObject\n", g.namePrefix) |
| 213 | for _, obj := range g.vars { |
| 214 | if t := obj.Type(); !g.isSupported(t) { |
| 215 | g.Printf("// skipped variable %s with unsupported type: %s\n\n", obj.Name(), t) |
| 216 | continue |
| 217 | } |
| 218 | objcType := g.objcType(obj.Type()) |
| 219 | g.objcdoc(g.docs[obj.Name()].Doc()) |
| 220 | g.Printf("+ (%s) %s;\n", objcType, objcNameReplacer(lowerFirst(obj.Name()))) |
| 221 | g.Printf("+ (void) set%s:(%s)v;\n", obj.Name(), objcType) |
| 222 | g.Printf("\n") |
| 223 | } |
| 224 | g.Printf("@end\n\n") |
| 225 | } |
| 226 | |
| 227 | // static functions. |
| 228 | for _, obj := range g.funcs { |
| 229 | g.genFuncH(obj) |
| 230 | g.Printf("\n") |
| 231 | } |
| 232 | |
| 233 | for _, i := range g.interfaces { |
| 234 | if i.summary.implementable { |
| 235 | g.Printf("@class %s%s;\n\n", g.namePrefix, i.obj.Name()) |
| 236 | } |
| 237 | } |
| 238 | for _, i := range g.interfaces { |
| 239 | if i.summary.implementable { |
| 240 | // @interface Interface -- similar to what genStructH does. |
| 241 | g.genInterfaceInterface(i.obj, i.summary, true) |
| 242 | g.Printf("\n") |
| 243 | } |
| 244 | } |
| 245 | |
| 246 | g.Printf("#endif\n") |
| 247 | |
| 248 | if len(g.err) > 0 { |
| 249 | return g.err |
| 250 | } |
| 251 | return nil |
| 252 | } |
| 253 | |
| 254 | func (g *ObjcGen) gobindOpts() string { |
| 255 | opts := []string{"-lang=objc"} |
| 256 | if g.Prefix != "" { |
| 257 | opts = append(opts, fmt.Sprintf("-prefix=%q", g.Prefix)) |
| 258 | } |
| 259 | return strings.Join(opts, " ") |
| 260 | } |
| 261 | |
| 262 | func (g *ObjcGen) GenM() error { |
| 263 | var pkgPath string |
| 264 | if g.Pkg != nil { |
| 265 | pkgPath = g.Pkg.Path() |
| 266 | } |
| 267 | g.Printf(objcPreamble, pkgPath, g.gobindOpts(), pkgPath) |
| 268 | g.Printf("#include <Foundation/Foundation.h>\n") |
| 269 | g.Printf("#include \"seq.h\"\n") |
| 270 | g.Printf("#include \"_cgo_export.h\"\n") |
| 271 | g.Printf("#include %q\n", g.namePrefix+".objc.h") |
| 272 | g.Printf("\n") |
| 273 | |
| 274 | // struct |
| 275 | for _, s := range g.structs { |
| 276 | g.genStructM(s.obj, s.t) |
| 277 | g.Printf("\n") |
| 278 | } |
| 279 | |
| 280 | // interface |
| 281 | var needProxy []*types.TypeName |
| 282 | for _, i := range g.interfaces { |
| 283 | if g.genInterfaceM(i.obj, i.t) { |
| 284 | needProxy = append(needProxy, i.obj) |
| 285 | } |
| 286 | g.Printf("\n") |
| 287 | } |
| 288 | |
| 289 | // const |
| 290 | for _, o := range g.constants { |
| 291 | g.genConstM(o) |
| 292 | } |
| 293 | if len(g.constants) > 0 { |
| 294 | g.Printf("\n") |
| 295 | } |
| 296 | |
| 297 | // vars |
| 298 | if len(g.vars) > 0 { |
| 299 | g.Printf("@implementation %s\n", g.namePrefix) |
| 300 | for _, o := range g.vars { |
| 301 | g.genVarM(o) |
| 302 | } |
| 303 | g.Printf("@end\n\n") |
| 304 | } |
| 305 | |
| 306 | g.Printf("\n") |
| 307 | |
| 308 | for _, obj := range g.funcs { |
| 309 | if !g.isSigSupported(obj.Type()) { |
| 310 | g.Printf("// skipped function %s with unsupported parameter or return types\n\n", obj.Name()) |
| 311 | continue |
| 312 | } |
| 313 | g.genFuncM(obj) |
| 314 | g.Printf("\n") |
| 315 | } |
| 316 | |
| 317 | for _, i := range g.interfaces { |
| 318 | for _, m := range i.summary.callable { |
| 319 | if !g.isSigSupported(m.Type()) { |
| 320 | g.Printf("// skipped method %s.%s with unsupported parameter or return types\n\n", i.obj.Name(), m.Name()) |
| 321 | continue |
| 322 | } |
| 323 | g.genInterfaceMethodProxy(i.obj, m) |
| 324 | } |
| 325 | } |
| 326 | |
| 327 | g.Printf("__attribute__((constructor)) static void init() {\n") |
| 328 | g.Indent() |
| 329 | g.Printf("init_seq();\n") |
| 330 | g.Outdent() |
| 331 | g.Printf("}\n") |
| 332 | |
| 333 | if len(g.err) > 0 { |
| 334 | return g.err |
| 335 | } |
| 336 | |
| 337 | return nil |
| 338 | } |
| 339 | |
| 340 | func (g *ObjcGen) genVarM(o *types.Var) { |
| 341 | if t := o.Type(); !g.isSupported(t) { |
| 342 | g.Printf("// skipped variable %s with unsupported type: %s\n\n", o.Name(), t) |
| 343 | return |
| 344 | } |
| 345 | objcType := g.objcType(o.Type()) |
| 346 | |
| 347 | // setter |
| 348 | g.Printf("+ (void) set%s:(%s)v {\n", o.Name(), objcType) |
| 349 | g.Indent() |
| 350 | g.genWrite("v", o.Type(), modeRetained) |
| 351 | g.Printf("var_set%s_%s(_v);\n", g.pkgPrefix, o.Name()) |
| 352 | g.genRelease("v", o.Type(), modeRetained) |
| 353 | g.Outdent() |
| 354 | g.Printf("}\n\n") |
| 355 | |
| 356 | // getter |
| 357 | g.Printf("+ (%s) %s {\n", objcType, objcNameReplacer(lowerFirst(o.Name()))) |
| 358 | g.Indent() |
| 359 | g.Printf("%s r0 = ", g.cgoType(o.Type())) |
| 360 | g.Printf("var_get%s_%s();\n", g.pkgPrefix, o.Name()) |
| 361 | g.genRead("_r0", "r0", o.Type(), modeRetained) |
| 362 | g.Printf("return _r0;\n") |
| 363 | g.Outdent() |
| 364 | g.Printf("}\n\n") |
| 365 | } |
| 366 | |
| 367 | func (g *ObjcGen) genConstM(o *types.Const) { |
| 368 | if _, ok := o.Type().(*types.Basic); !ok || !g.isSupported(o.Type()) { |
| 369 | g.Printf("// skipped const %s with unsupported type: %s\n\n", o.Name(), o.Type()) |
| 370 | return |
| 371 | } |
| 372 | cName := fmt.Sprintf("%s%s", g.namePrefix, o.Name()) |
| 373 | objcType := g.objcType(o.Type()) |
| 374 | |
| 375 | switch b := o.Type().(*types.Basic); b.Kind() { |
| 376 | case types.Bool, types.UntypedBool: |
| 377 | v := "NO" |
| 378 | if constant.BoolVal(o.Val()) { |
| 379 | v = "YES" |
| 380 | } |
| 381 | g.Printf("const BOOL %s = %s;\n", cName, v) |
| 382 | |
| 383 | case types.String, types.UntypedString: |
| 384 | g.Printf("NSString* const %s = @%s;\n", cName, o.Val().ExactString()) |
| 385 | |
| 386 | case types.Int, types.Int8, types.Int16, types.Int32: |
| 387 | g.Printf("const %s %s = %s;\n", objcType, cName, o.Val()) |
| 388 | |
| 389 | case types.Int64, types.UntypedInt: |
| 390 | i, exact := constant.Int64Val(o.Val()) |
| 391 | if !exact { |
| 392 | g.errorf("const value %s for %s cannot be represented as %s", o.Val(), o.Name(), objcType) |
| 393 | return |
| 394 | } |
| 395 | if i == math.MinInt64 { |
| 396 | // -9223372036854775808LL does not work because 922337203685477508 is |
| 397 | // larger than max int64. |
| 398 | g.Printf("const int64_t %s = %dLL-1;\n", cName, i+1) |
| 399 | } else { |
| 400 | g.Printf("const int64_t %s = %dLL;\n", cName, i) |
| 401 | } |
| 402 | |
| 403 | case types.Float32, types.Float64, types.UntypedFloat: |
| 404 | f, _ := constant.Float64Val(o.Val()) |
| 405 | if math.IsInf(f, 0) || math.Abs(f) > math.MaxFloat64 { |
| 406 | g.errorf("const value %s for %s cannot be represented as double", o.Val(), o.Name()) |
| 407 | return |
| 408 | } |
| 409 | g.Printf("const %s %s = %g;\n", objcType, cName, f) |
| 410 | |
| 411 | default: |
| 412 | g.errorf("unsupported const type %s for %s", b, o.Name()) |
| 413 | } |
| 414 | } |
| 415 | |
| 416 | type funcSummary struct { |
| 417 | name string |
| 418 | goname string |
| 419 | ret string |
| 420 | sig *types.Signature |
| 421 | params, retParams []paramInfo |
| 422 | hasself bool |
| 423 | initName string |
| 424 | } |
| 425 | |
| 426 | type paramInfo struct { |
| 427 | typ types.Type |
| 428 | name string |
| 429 | } |
| 430 | |
| 431 | func (g *ObjcGen) funcSummary(obj *types.TypeName, f *types.Func) *funcSummary { |
| 432 | sig := f.Type().(*types.Signature) |
| 433 | s := &funcSummary{goname: f.Name(), sig: sig} |
| 434 | var om *objc.Func |
| 435 | var sigElems []string |
| 436 | oinf := g.ostructs[obj] |
| 437 | if oinf != nil { |
| 438 | om = oinf.methods[f.Name()] |
| 439 | } |
| 440 | if om != nil { |
| 441 | sigElems = strings.Split(om.Sig, ":") |
| 442 | s.name = sigElems[0] |
| 443 | } else { |
| 444 | s.name = f.Name() |
| 445 | } |
| 446 | params := sig.Params() |
| 447 | first := 0 |
| 448 | if oinf != nil { |
| 449 | if params.Len() > 0 { |
| 450 | v := params.At(0) |
| 451 | if v.Name() == "self" { |
| 452 | t := v.Type() |
| 453 | if t, ok := t.(*types.Named); ok { |
| 454 | if pkg := t.Obj().Pkg(); pkgFirstElem(pkg) == "ObjC" { |
| 455 | s.hasself = true |
| 456 | module := pkg.Path()[len("ObjC/"):] |
| 457 | typName := module + "." + t.Obj().Name() |
| 458 | exp := g.namePrefix + "." + obj.Name() |
| 459 | if typName != exp { |
| 460 | g.errorf("the type %s of the `this` argument to method %s is not %s", typName, f.Name(), exp) |
| 461 | } |
| 462 | } |
| 463 | } |
| 464 | } |
| 465 | } |
| 466 | } |
| 467 | for i := first; i < params.Len(); i++ { |
| 468 | p := params.At(i) |
| 469 | v := paramInfo{ |
| 470 | typ: p.Type(), |
| 471 | } |
| 472 | if om != nil { |
| 473 | v.name = sigElems[i-first] |
| 474 | } else { |
| 475 | v.name = g.paramName(params, i) |
| 476 | } |
| 477 | s.params = append(s.params, v) |
| 478 | } |
| 479 | if obj != nil { |
| 480 | if pref := "New" + obj.Name(); strings.Index(f.Name(), pref) != -1 { |
| 481 | s.initName = "init" + f.Name()[len(pref):] |
| 482 | } |
| 483 | } |
| 484 | res := sig.Results() |
| 485 | switch res.Len() { |
| 486 | case 0: |
| 487 | s.ret = "void" |
| 488 | case 1: |
| 489 | p := res.At(0) |
| 490 | if isErrorType(p.Type()) { |
| 491 | s.retParams = append(s.retParams, paramInfo{ |
| 492 | typ: p.Type(), |
| 493 | name: "error", |
| 494 | }) |
| 495 | s.ret = "BOOL" |
| 496 | } else { |
| 497 | name := p.Name() |
| 498 | if name == "" || paramRE.MatchString(name) { |
| 499 | name = "ret0_" |
| 500 | } |
| 501 | typ := p.Type() |
| 502 | s.retParams = append(s.retParams, paramInfo{typ: typ, name: name}) |
| 503 | s.ret = g.objcType(typ) |
| 504 | } |
| 505 | case 2: |
| 506 | name := res.At(0).Name() |
| 507 | if name == "" || paramRE.MatchString(name) { |
| 508 | name = "ret0_" |
| 509 | } |
| 510 | typ := res.At(0).Type() |
| 511 | s.retParams = append(s.retParams, paramInfo{ |
| 512 | typ: typ, |
| 513 | name: name, |
| 514 | }) |
| 515 | if isNullableType(typ) { |
| 516 | s.ret = g.objcType(typ) // Return is nullable, so satisfies the ObjC/Swift error protocol |
| 517 | } else { |
| 518 | s.ret = "BOOL" // Return is not nullable, must use an output parameter and return bool |
| 519 | } |
| 520 | |
| 521 | if !isErrorType(res.At(1).Type()) { |
| 522 | g.errorf("second result value must be of type error: %s", f) |
| 523 | return nil |
| 524 | } |
| 525 | s.retParams = append(s.retParams, paramInfo{ |
| 526 | typ: res.At(1).Type(), |
| 527 | name: "error", // TODO(hyangah): name collision check. |
| 528 | }) |
| 529 | default: |
| 530 | // TODO(hyangah): relax the constraint on multiple return params. |
| 531 | g.errorf("too many result values: %s", f) |
| 532 | return nil |
| 533 | } |
| 534 | |
| 535 | return s |
| 536 | } |
| 537 | |
| 538 | func (s *funcSummary) asFunc(g *ObjcGen) string { |
| 539 | var params []string |
| 540 | for _, p := range s.params { |
| 541 | params = append(params, g.objcParamType(p.typ)+" "+p.name) |
| 542 | } |
| 543 | skip := 0 |
| 544 | if s.returnsVal() { |
| 545 | skip = 1 |
| 546 | } |
| 547 | for _, p := range s.retParams[skip:] { |
| 548 | params = append(params, g.objcType(p.typ)+"* _Nullable "+p.name) |
| 549 | } |
| 550 | paramContents := "void" |
| 551 | if len(params) > 0 { |
| 552 | paramContents = strings.Join(params, ", ") |
| 553 | } |
| 554 | return fmt.Sprintf("%s %s%s(%s)", s.ret, g.namePrefix, s.name, paramContents) |
| 555 | } |
| 556 | |
| 557 | func (s *funcSummary) asMethod(g *ObjcGen) string { |
| 558 | return fmt.Sprintf("(%s)%s%s", s.ret, objcNameReplacer(lowerFirst(s.name)), s.asSignature(g)) |
| 559 | } |
| 560 | |
| 561 | func (s *funcSummary) asSignature(g *ObjcGen) string { |
| 562 | var params []string |
| 563 | skip := 0 |
| 564 | if s.hasself { |
| 565 | skip = 1 |
| 566 | } |
| 567 | for i, p := range s.params[skip:] { |
| 568 | var key string |
| 569 | if i != 0 { |
| 570 | key = p.name |
| 571 | } |
| 572 | params = append(params, fmt.Sprintf("%s:(%s)%s", key, g.objcParamType(p.typ), p.name)) |
| 573 | } |
| 574 | skip = 0 |
| 575 | if s.returnsVal() { |
| 576 | skip = 1 |
| 577 | } |
| 578 | for _, p := range s.retParams[skip:] { |
| 579 | var key string |
| 580 | if len(params) > 0 { |
| 581 | key = p.name |
| 582 | } |
| 583 | params = append(params, fmt.Sprintf("%s:(%s)%s", key, g.objcType(p.typ)+"* _Nullable", p.name)) |
| 584 | } |
| 585 | return strings.Join(params, " ") |
| 586 | } |
| 587 | |
| 588 | func (s *funcSummary) asInitSignature(g *ObjcGen) string { |
| 589 | var params []string |
| 590 | for i, p := range s.params { |
| 591 | var key string |
| 592 | if i > 0 { |
| 593 | key = p.name |
| 594 | } |
| 595 | params = append(params, fmt.Sprintf("%s:(%s)%s", key, g.objcParamType(p.typ), p.name)) |
| 596 | } |
| 597 | return strings.Join(params, " ") |
| 598 | } |
| 599 | |
| 600 | func (s *funcSummary) callMethod(g *ObjcGen) string { |
| 601 | var params []string |
| 602 | for i, p := range s.params { |
| 603 | var key string |
| 604 | if i != 0 { |
| 605 | key = p.name |
| 606 | } |
| 607 | params = append(params, fmt.Sprintf("%s:_%s", key, p.name)) |
| 608 | } |
| 609 | skip := 0 |
| 610 | if s.returnsVal() { |
| 611 | skip = 1 |
| 612 | } |
| 613 | for _, p := range s.retParams[skip:] { |
| 614 | var key string |
| 615 | if len(params) > 0 { |
| 616 | key = p.name |
| 617 | } |
| 618 | params = append(params, fmt.Sprintf("%s:&%s", key, p.name)) |
| 619 | } |
| 620 | return fmt.Sprintf("%s%s", objcNameReplacer(lowerFirst(s.name)), strings.Join(params, " ")) |
| 621 | } |
| 622 | |
| 623 | func (s *funcSummary) returnsVal() bool { |
| 624 | return (len(s.retParams) == 1 && !isErrorType(s.retParams[0].typ)) || (len(s.retParams) == 2 && isNullableType(s.retParams[0].typ)) |
| 625 | } |
| 626 | |
| 627 | func (g *ObjcGen) paramName(params *types.Tuple, pos int) string { |
| 628 | name := basicParamName(params, pos) |
| 629 | return objcNameReplacer(name) |
| 630 | } |
| 631 | |
| 632 | func (g *ObjcGen) genFuncH(obj *types.Func) { |
| 633 | if !g.isSigSupported(obj.Type()) { |
| 634 | g.Printf("// skipped function %s with unsupported parameter or return types\n\n", obj.Name()) |
| 635 | return |
| 636 | } |
| 637 | if s := g.funcSummary(nil, obj); s != nil { |
| 638 | g.objcdoc(g.docs[obj.Name()].Doc()) |
| 639 | g.Printf("FOUNDATION_EXPORT %s;\n", s.asFunc(g)) |
| 640 | } |
| 641 | } |
| 642 | |
| 643 | func (g *ObjcGen) genFuncM(obj *types.Func) { |
| 644 | s := g.funcSummary(nil, obj) |
| 645 | if s == nil { |
| 646 | return |
| 647 | } |
| 648 | g.Printf("%s {\n", s.asFunc(g)) |
| 649 | g.Indent() |
| 650 | g.genFunc(s, "") |
| 651 | g.Outdent() |
| 652 | g.Printf("}\n") |
| 653 | } |
| 654 | |
| 655 | func (g *ObjcGen) genGetter(oName string, f *types.Var) { |
| 656 | t := f.Type() |
| 657 | g.Printf("- (%s)%s {\n", g.objcType(t), objcNameReplacer(lowerFirst(f.Name()))) |
| 658 | g.Indent() |
| 659 | g.Printf("int32_t refnum = go_seq_go_to_refnum(self._ref);\n") |
| 660 | g.Printf("%s r0 = ", g.cgoType(f.Type())) |
| 661 | g.Printf("proxy%s_%s_%s_Get(refnum);\n", g.pkgPrefix, oName, f.Name()) |
| 662 | g.genRead("_r0", "r0", f.Type(), modeRetained) |
| 663 | g.Printf("return _r0;\n") |
| 664 | g.Outdent() |
| 665 | g.Printf("}\n\n") |
| 666 | } |
| 667 | |
| 668 | func (g *ObjcGen) genSetter(oName string, f *types.Var) { |
| 669 | t := f.Type() |
| 670 | |
| 671 | g.Printf("- (void)set%s:(%s)v {\n", f.Name(), g.objcType(t)) |
| 672 | g.Indent() |
| 673 | g.Printf("int32_t refnum = go_seq_go_to_refnum(self._ref);\n") |
| 674 | g.genWrite("v", f.Type(), modeRetained) |
| 675 | g.Printf("proxy%s_%s_%s_Set(refnum, _v);\n", g.pkgPrefix, oName, f.Name()) |
| 676 | g.genRelease("v", f.Type(), modeRetained) |
| 677 | g.Outdent() |
| 678 | g.Printf("}\n\n") |
| 679 | } |
| 680 | |
| 681 | func (g *ObjcGen) genWrite(varName string, t types.Type, mode varMode) { |
| 682 | switch t := types.Unalias(t).(type) { |
| 683 | case *types.Basic: |
| 684 | switch t.Kind() { |
| 685 | case types.String: |
| 686 | g.Printf("nstring _%s = go_seq_from_objc_string(%s);\n", varName, varName) |
| 687 | default: |
| 688 | g.Printf("%s _%s = (%s)%s;\n", g.cgoType(t), varName, g.cgoType(t), varName) |
| 689 | } |
| 690 | case *types.Slice: |
| 691 | if isBytesSlice(t) { |
| 692 | g.Printf("nbyteslice _%s = go_seq_from_objc_bytearray(%s, %d);\n", varName, varName, toCFlag(mode == modeRetained)) |
| 693 | return |
| 694 | } |
| 695 | g.errorf("unsupported type: %s", t) |
| 696 | case *types.Named: |
| 697 | switch u := t.Underlying().(type) { |
| 698 | case *types.Interface: |
| 699 | g.genRefWrite(varName) |
| 700 | default: |
| 701 | g.errorf("unsupported named type: %s / %T", u, u) |
| 702 | } |
| 703 | case *types.Pointer: |
| 704 | g.genRefWrite(varName) |
| 705 | default: |
| 706 | g.Printf("%s _%s = (%s)%s;\n", g.cgoType(t), varName, g.cgoType(t), varName) |
| 707 | } |
| 708 | } |
| 709 | |
| 710 | func (g *ObjcGen) genRefWrite(varName string) { |
| 711 | g.Printf("int32_t _%s;\n", varName) |
| 712 | g.Printf("if ([%s conformsToProtocol:@protocol(goSeqRefInterface)]) {\n", varName) |
| 713 | g.Indent() |
| 714 | g.Printf("id<goSeqRefInterface> %[1]s_proxy = (id<goSeqRefInterface>)(%[1]s);\n", varName) |
| 715 | g.Printf("_%s = go_seq_go_to_refnum(%s_proxy._ref);\n", varName, varName) |
| 716 | g.Outdent() |
| 717 | g.Printf("} else {\n") |
| 718 | g.Indent() |
| 719 | g.Printf("_%s = go_seq_to_refnum(%s);\n", varName, varName) |
| 720 | g.Outdent() |
| 721 | g.Printf("}\n") |
| 722 | } |
| 723 | |
| 724 | func (g *ObjcGen) genRefRead(toName, fromName string, t types.Type) { |
| 725 | ptype := g.refTypeBase(t) |
| 726 | g.Printf("%s* %s = nil;\n", ptype, toName) |
| 727 | g.Printf("GoSeqRef* %s_ref = go_seq_from_refnum(%s);\n", toName, fromName) |
| 728 | g.Printf("if (%s_ref != NULL) {\n", toName) |
| 729 | g.Printf(" %s = %s_ref.obj;\n", toName, toName) |
| 730 | g.Printf(" if (%s == nil) {\n", toName) |
| 731 | if isObjcType(t) { |
| 732 | g.Printf(" LOG_FATAL(@\"unexpected NULL reference\");\n") |
| 733 | } else { |
| 734 | g.Printf(" %s = [[%s alloc] initWithRef:%s_ref];\n", toName, ptype, toName) |
| 735 | } |
| 736 | g.Printf(" }\n") |
| 737 | g.Printf("}\n") |
| 738 | } |
| 739 | |
| 740 | func (g *ObjcGen) genRead(toName, fromName string, t types.Type, mode varMode) { |
| 741 | switch t := types.Unalias(t).(type) { |
| 742 | case *types.Basic: |
| 743 | switch t.Kind() { |
| 744 | case types.String: |
| 745 | g.Printf("NSString *%s = go_seq_to_objc_string(%s);\n", toName, fromName) |
| 746 | case types.Bool: |
| 747 | g.Printf("BOOL %s = %s ? YES : NO;\n", toName, fromName) |
| 748 | default: |
| 749 | g.Printf("%s %s = (%s)%s;\n", g.objcType(t), toName, g.objcType(t), fromName) |
| 750 | } |
| 751 | case *types.Slice: |
| 752 | if isBytesSlice(t) { |
| 753 | g.Printf("NSData *%s = go_seq_to_objc_bytearray(%s, %d);\n", toName, fromName, toCFlag(mode == modeRetained)) |
| 754 | return |
| 755 | } |
| 756 | g.errorf("unsupported type: %s", t) |
| 757 | case *types.Pointer: |
| 758 | switch t := types.Unalias(t.Elem()).(type) { |
| 759 | case *types.Named: |
| 760 | g.genRefRead(toName, fromName, types.NewPointer(t)) |
| 761 | default: |
| 762 | g.errorf("unsupported type %s", t) |
| 763 | } |
| 764 | case *types.Named: |
| 765 | switch t.Underlying().(type) { |
| 766 | case *types.Interface, *types.Pointer: |
| 767 | g.genRefRead(toName, fromName, t) |
| 768 | default: |
| 769 | g.errorf("unsupported, direct named type %s", t) |
| 770 | } |
| 771 | default: |
| 772 | g.Printf("%s %s = (%s)%s;\n", g.objcType(t), toName, g.objcType(t), fromName) |
| 773 | } |
| 774 | } |
| 775 | |
| 776 | func (g *ObjcGen) genFunc(s *funcSummary, objName string) { |
| 777 | skip := 0 |
| 778 | if objName != "" { |
| 779 | g.Printf("int32_t refnum = go_seq_go_to_refnum(self._ref);\n") |
| 780 | if s.hasself { |
| 781 | skip = 1 |
| 782 | g.Printf("int32_t _self = go_seq_to_refnum(self);\n") |
| 783 | } |
| 784 | } |
| 785 | for _, p := range s.params[skip:] { |
| 786 | g.genWrite(p.name, p.typ, modeTransient) |
| 787 | } |
| 788 | resPrefix := "" |
| 789 | if len(s.retParams) > 0 { |
| 790 | if len(s.retParams) == 1 { |
| 791 | g.Printf("%s r0 = ", g.cgoType(s.retParams[0].typ)) |
| 792 | } else { |
| 793 | resPrefix = "res." |
| 794 | g.Printf("struct proxy%s_%s_%s_return res = ", g.pkgPrefix, objName, s.goname) |
| 795 | } |
| 796 | } |
| 797 | g.Printf("proxy%s_%s_%s(", g.pkgPrefix, objName, s.goname) |
| 798 | if objName != "" { |
| 799 | g.Printf("refnum") |
| 800 | if s.hasself { |
| 801 | g.Printf(", _self") |
| 802 | } |
| 803 | } |
| 804 | for i, p := range s.params[skip:] { |
| 805 | if i > 0 || objName != "" { |
| 806 | g.Printf(", ") |
| 807 | } |
| 808 | g.Printf("_%s", p.name) |
| 809 | } |
| 810 | g.Printf(");\n") |
| 811 | for _, p := range s.params { |
| 812 | g.genRelease(p.name, p.typ, modeTransient) |
| 813 | } |
| 814 | |
| 815 | for i, r := range s.retParams { |
| 816 | g.genRead("_"+r.name, fmt.Sprintf("%sr%d", resPrefix, i), r.typ, modeRetained) |
| 817 | } |
| 818 | skip = 0 |
| 819 | if s.returnsVal() { |
| 820 | skip = 1 |
| 821 | } |
| 822 | for _, p := range s.retParams[skip:] { |
| 823 | if isErrorType(p.typ) { |
| 824 | g.Printf("if (_%s != nil && %s != nil) {\n", p.name, p.name) |
| 825 | g.Indent() |
| 826 | g.Printf("*%s = _%s;\n", p.name, p.name) |
| 827 | g.Outdent() |
| 828 | g.Printf("}\n") |
| 829 | } else { |
| 830 | g.Printf("*%s = _%s;\n", p.name, p.name) |
| 831 | } |
| 832 | } |
| 833 | |
| 834 | if n := len(s.retParams); n > 0 { |
| 835 | var ( |
| 836 | first = s.retParams[0] |
| 837 | last = s.retParams[n-1] |
| 838 | ) |
| 839 | if (n == 1 && isErrorType(last.typ)) || (n == 2 && !isNullableType(first.typ) && isErrorType(last.typ)) { |
| 840 | g.Printf("return (_%s == nil);\n", last.name) |
| 841 | } else { |
| 842 | if s.returnsVal() && isErrorType(last.typ) { |
| 843 | g.Printf("if (_%s != nil) {\n", last.name) |
| 844 | g.Indent() |
| 845 | g.Printf("return nil;\n") |
| 846 | g.Outdent() |
| 847 | g.Printf("}\n") |
| 848 | } |
| 849 | g.Printf("return _%s;\n", first.name) |
| 850 | } |
| 851 | } |
| 852 | } |
| 853 | |
| 854 | func (g *ObjcGen) genInterfaceInterface(obj *types.TypeName, summary ifaceSummary, isProtocol bool) { |
| 855 | doc := g.docs[obj.Name()] |
| 856 | g.objcdoc(doc.Doc()) |
| 857 | g.Printf("@interface %[1]s%[2]s : ", g.namePrefix, obj.Name()) |
| 858 | if isErrorType(obj.Type()) { |
| 859 | g.Printf("NSError") |
| 860 | } else { |
| 861 | g.Printf("NSObject") |
| 862 | } |
| 863 | prots := []string{"goSeqRefInterface"} |
| 864 | if isProtocol { |
| 865 | prots = append(prots, fmt.Sprintf("%[1]s%[2]s", g.namePrefix, obj.Name())) |
| 866 | } |
| 867 | g.Printf(" <%s>", strings.Join(prots, ", ")) |
| 868 | g.Printf(" {\n}\n") |
| 869 | g.Printf("@property(strong, readonly) _Nonnull id _ref;\n") |
| 870 | g.Printf("\n") |
| 871 | g.Printf("- (nonnull instancetype)initWithRef:(_Nonnull id)ref;\n") |
| 872 | for _, m := range summary.callable { |
| 873 | if !g.isSigSupported(m.Type()) { |
| 874 | g.Printf("// skipped method %s.%s with unsupported parameter or return types\n\n", obj.Name(), m.Name()) |
| 875 | continue |
| 876 | } |
| 877 | s := g.funcSummary(nil, m) |
| 878 | g.objcdoc(doc.Member(m.Name())) |
| 879 | g.Printf("- %s;\n", s.asMethod(g)) |
| 880 | } |
| 881 | g.Printf("@end\n") |
| 882 | } |
| 883 | |
| 884 | func (g *ObjcGen) genInterfaceH(obj *types.TypeName, t *types.Interface) { |
| 885 | doc := g.docs[obj.Name()] |
| 886 | summary := makeIfaceSummary(t) |
| 887 | if !summary.implementable { |
| 888 | g.genInterfaceInterface(obj, summary, false) |
| 889 | return |
| 890 | } |
| 891 | g.Printf("@protocol %s%s <NSObject>\n", g.namePrefix, obj.Name()) |
| 892 | for _, m := range makeIfaceSummary(t).callable { |
| 893 | if !g.isSigSupported(m.Type()) { |
| 894 | g.Printf("// skipped method %s.%s with unsupported parameter or return types\n\n", obj.Name(), m.Name()) |
| 895 | continue |
| 896 | } |
| 897 | s := g.funcSummary(nil, m) |
| 898 | g.objcdoc(doc.Member(m.Name())) |
| 899 | g.Printf("- %s;\n", s.asMethod(g)) |
| 900 | } |
| 901 | g.Printf("@end\n") |
| 902 | } |
| 903 | |
| 904 | func (g *ObjcGen) genInterfaceM(obj *types.TypeName, t *types.Interface) bool { |
| 905 | summary := makeIfaceSummary(t) |
| 906 | |
| 907 | // @implementation Interface -- similar to what genStructM does. |
| 908 | g.Printf("@implementation %s%s {\n", g.namePrefix, obj.Name()) |
| 909 | g.Printf("}\n") |
| 910 | g.Printf("\n") |
| 911 | g.Printf("- (nonnull instancetype)initWithRef:(id)ref {\n") |
| 912 | g.Indent() |
| 913 | if isErrorType(obj.Type()) { |
| 914 | g.Printf("if (self) {\n") |
| 915 | g.Printf(" __ref = ref;\n") |
| 916 | g.Printf(" self = [super initWithDomain:@\"go\" code:1 userInfo:@{NSLocalizedDescriptionKey: [self error]}];\n") |
| 917 | g.Printf("}\n") |
| 918 | } else { |
| 919 | g.Printf("self = [super init];\n") |
| 920 | g.Printf("if (self) { __ref = ref; }\n") |
| 921 | } |
| 922 | g.Printf("return self;\n") |
| 923 | g.Outdent() |
| 924 | g.Printf("}\n") |
| 925 | g.Printf("\n") |
| 926 | |
| 927 | for _, m := range summary.callable { |
| 928 | if !g.isSigSupported(m.Type()) { |
| 929 | g.Printf("// skipped method %s.%s with unsupported parameter or return types\n\n", obj.Name(), m.Name()) |
| 930 | continue |
| 931 | } |
| 932 | s := g.funcSummary(nil, m) |
| 933 | g.Printf("- %s {\n", s.asMethod(g)) |
| 934 | g.Indent() |
| 935 | g.genFunc(s, obj.Name()) |
| 936 | g.Outdent() |
| 937 | g.Printf("}\n\n") |
| 938 | } |
| 939 | g.Printf("@end\n") |
| 940 | g.Printf("\n") |
| 941 | |
| 942 | return summary.implementable |
| 943 | } |
| 944 | |
| 945 | func (g *ObjcGen) genInterfaceMethodProxy(obj *types.TypeName, m *types.Func) { |
| 946 | oName := obj.Name() |
| 947 | s := g.funcSummary(nil, m) |
| 948 | g.genInterfaceMethodSignature(m, oName, false, g.paramName) |
| 949 | g.Indent() |
| 950 | g.Printf("@autoreleasepool {\n") |
| 951 | g.Indent() |
| 952 | g.Printf("%s* o = go_seq_objc_from_refnum(refnum);\n", g.refTypeBase(obj.Type())) |
| 953 | for _, p := range s.params { |
| 954 | g.genRead("_"+p.name, p.name, p.typ, modeTransient) |
| 955 | } |
| 956 | |
| 957 | // call method |
| 958 | for _, p := range s.retParams { |
| 959 | if isErrorType(p.typ) { |
| 960 | g.Printf("NSError* %s = nil;\n", p.name) |
| 961 | } else { |
| 962 | g.Printf("%s %s;\n", g.objcType(p.typ), p.name) |
| 963 | } |
| 964 | } |
| 965 | |
| 966 | if isErrorType(obj.Type()) && m.Name() == "Error" { |
| 967 | // As a special case, ObjC NSErrors are passed to Go pretending to implement the Go error interface. |
| 968 | // They don't actually have an Error method, so calls to it needs to be rerouted. |
| 969 | g.Printf("%s = [o localizedDescription];\n", s.retParams[0].name) |
| 970 | } else { |
| 971 | if s.ret == "void" { |
| 972 | g.Printf("[o %s];\n", s.callMethod(g)) |
| 973 | } else if !s.returnsVal() { |
| 974 | g.Printf("%s returnVal = [o %s];\n", s.ret, s.callMethod(g)) |
| 975 | } else { |
| 976 | g.Printf("%s = [o %s];\n", s.retParams[0].name, s.callMethod(g)) |
| 977 | } |
| 978 | } |
| 979 | |
| 980 | if len(s.retParams) > 0 { |
| 981 | if len(s.retParams) == 1 && !isErrorType(s.retParams[0].typ) { |
| 982 | p := s.retParams[0] |
| 983 | g.genWrite(p.name, p.typ, modeRetained) |
| 984 | g.Printf("return _%s;\n", p.name) |
| 985 | } else { |
| 986 | var rets []string |
| 987 | for _, p := range s.retParams { |
| 988 | if isErrorType(p.typ) { |
| 989 | g.Printf("NSError *_%s = nil;\n", p.name) |
| 990 | if !s.returnsVal() { |
| 991 | g.Printf("if (!returnVal) {\n") |
| 992 | } else { |
| 993 | g.Printf("if (%s != nil) {\n", p.name) |
| 994 | } |
| 995 | g.Indent() |
| 996 | g.Printf("_%[1]s = %[1]s;\n", p.name) |
| 997 | g.Outdent() |
| 998 | g.Printf("}\n") |
| 999 | g.genWrite("_"+p.name, p.typ, modeRetained) |
| 1000 | rets = append(rets, "__"+p.name) |
| 1001 | } else { |
| 1002 | g.genWrite(p.name, p.typ, modeRetained) |
| 1003 | rets = append(rets, "_"+p.name) |
| 1004 | } |
| 1005 | } |
| 1006 | if len(rets) > 1 { |
| 1007 | g.Printf("cproxy%s_%s_%s_return _sres = {\n", g.pkgPrefix, oName, m.Name()) |
| 1008 | g.Printf(" %s\n", strings.Join(rets, ", ")) |
| 1009 | g.Printf("};\n") |
| 1010 | g.Printf("return _sres;\n") |
| 1011 | } else { |
| 1012 | g.Printf("return %s;\n", rets[0]) |
| 1013 | } |
| 1014 | } |
| 1015 | } |
| 1016 | g.Outdent() |
| 1017 | g.Printf("}\n") |
| 1018 | g.Outdent() |
| 1019 | g.Printf("}\n\n") |
| 1020 | } |
| 1021 | |
| 1022 | // genRelease cleans up arguments that weren't copied in genWrite. |
| 1023 | func (g *ObjcGen) genRelease(varName string, t types.Type, mode varMode) { |
| 1024 | switch t := types.Unalias(t).(type) { |
| 1025 | case *types.Slice: |
| 1026 | if isBytesSlice(t) && mode == modeTransient { |
| 1027 | // If the argument was not mutable, go_seq_from_objc_bytearray created a copy. |
| 1028 | // Free it here. |
| 1029 | g.Printf("if (![%s isKindOfClass:[NSMutableData class]]) {\n", varName) |
| 1030 | g.Printf(" free(_%s.ptr);\n", varName) |
| 1031 | g.Printf("}\n") |
| 1032 | } |
| 1033 | } |
| 1034 | } |
| 1035 | |
| 1036 | func (g *ObjcGen) genStructH(obj *types.TypeName, t *types.Struct) { |
| 1037 | doc := g.docs[obj.Name()] |
| 1038 | g.objcdoc(doc.Doc()) |
| 1039 | g.Printf("@interface %s%s : ", g.namePrefix, obj.Name()) |
| 1040 | oinf := g.ostructs[obj] |
| 1041 | var prots []string |
| 1042 | if oinf != nil { |
| 1043 | for _, sup := range oinf.supers { |
| 1044 | if !sup.Protocol { |
| 1045 | g.Printf("%s", sup.Name) |
| 1046 | } else { |
| 1047 | prots = append(prots, sup.Name) |
| 1048 | } |
| 1049 | } |
| 1050 | } else { |
| 1051 | g.Printf("NSObject") |
| 1052 | prots = append(prots, "goSeqRefInterface") |
| 1053 | } |
| 1054 | pT := types.NewPointer(obj.Type()) |
| 1055 | for _, iface := range g.allIntf { |
| 1056 | p := iface.obj.Pkg() |
| 1057 | if g.Pkg != nil && g.Pkg != p { |
| 1058 | // To avoid header include cycles, only declare implementation of interfaces |
| 1059 | // from imported packages. TODO(elias.naur): Include every interface that |
| 1060 | // doesn't introduce an include cycle. |
| 1061 | found := false |
| 1062 | for _, imp := range g.Pkg.Imports() { |
| 1063 | if imp == p { |
| 1064 | found = true |
| 1065 | break |
| 1066 | } |
| 1067 | } |
| 1068 | if !found { |
| 1069 | continue |
| 1070 | } |
| 1071 | } |
| 1072 | obj := iface.obj |
| 1073 | if types.AssignableTo(pT, obj.Type()) { |
| 1074 | n := fmt.Sprintf("%s%s", g.namePrefixOf(obj.Pkg()), obj.Name()) |
| 1075 | prots = append(prots, n) |
| 1076 | } |
| 1077 | } |
| 1078 | |
| 1079 | if len(prots) > 0 { |
| 1080 | g.Printf(" <%s>", strings.Join(prots, ", ")) |
| 1081 | } |
| 1082 | g.Printf(" {\n") |
| 1083 | g.Printf("}\n") |
| 1084 | g.Printf("@property(strong, readonly) _Nonnull id _ref;\n") |
| 1085 | g.Printf("\n") |
| 1086 | g.Printf("- (nonnull instancetype)initWithRef:(_Nonnull id)ref;\n") |
| 1087 | cons := g.constructors[obj] |
| 1088 | if oinf == nil { |
| 1089 | for _, f := range cons { |
| 1090 | if !g.isSigSupported(f.Type()) { |
| 1091 | g.Printf("// skipped constructor %s.%s with unsupported parameter or return types\n\n", obj.Name(), f.Name()) |
| 1092 | continue |
| 1093 | } |
| 1094 | g.genInitH(obj, f) |
| 1095 | } |
| 1096 | } |
| 1097 | if oinf != nil || len(cons) == 0 { |
| 1098 | // default constructor won't return nil |
| 1099 | g.Printf("- (nonnull instancetype)init;\n") |
| 1100 | } |
| 1101 | |
| 1102 | // accessors to exported fields. |
| 1103 | for _, f := range exportedFields(t) { |
| 1104 | if t := f.Type(); !g.isSupported(t) { |
| 1105 | g.Printf("// skipped field %s.%s with unsupported type: %s\n\n", obj.Name(), f.Name(), t) |
| 1106 | continue |
| 1107 | } |
| 1108 | name, typ := f.Name(), g.objcType(f.Type()) |
| 1109 | g.objcdoc(doc.Member(f.Name())) |
| 1110 | |
| 1111 | // properties are atomic by default so explicitly say otherwise |
| 1112 | g.Printf("@property (nonatomic) %s %s;\n", typ, objcNameReplacer(lowerFirst(name))) |
| 1113 | } |
| 1114 | |
| 1115 | // exported methods |
| 1116 | for _, m := range exportedMethodSet(types.NewPointer(obj.Type())) { |
| 1117 | if !g.isSigSupported(m.Type()) { |
| 1118 | g.Printf("// skipped method %s.%s with unsupported parameter or return types\n\n", obj.Name(), m.Name()) |
| 1119 | continue |
| 1120 | } |
| 1121 | s := g.funcSummary(obj, m) |
| 1122 | g.objcdoc(doc.Member(m.Name())) |
| 1123 | g.Printf("- %s;\n", s.asMethod(g)) |
| 1124 | } |
| 1125 | g.Printf("@end\n") |
| 1126 | } |
| 1127 | |
| 1128 | func (g *ObjcGen) objcdoc(doc string) { |
| 1129 | if doc == "" { |
| 1130 | return |
| 1131 | } |
| 1132 | g.Printf("/**\n * %s */\n", doc) |
| 1133 | } |
| 1134 | |
| 1135 | func (g *ObjcGen) genStructM(obj *types.TypeName, t *types.Struct) { |
| 1136 | fields := exportedFields(t) |
| 1137 | methods := exportedMethodSet(types.NewPointer(obj.Type())) |
| 1138 | |
| 1139 | g.Printf("\n") |
| 1140 | oinf := g.ostructs[obj] |
| 1141 | g.Printf("@implementation %s%s {\n", g.namePrefix, obj.Name()) |
| 1142 | g.Printf("}\n\n") |
| 1143 | g.Printf("- (nonnull instancetype)initWithRef:(_Nonnull id)ref {\n") |
| 1144 | g.Indent() |
| 1145 | g.Printf("self = [super init];\n") |
| 1146 | g.Printf("if (self) { __ref = ref; }\n") |
| 1147 | g.Printf("return self;\n") |
| 1148 | g.Outdent() |
| 1149 | g.Printf("}\n\n") |
| 1150 | cons := g.constructors[obj] |
| 1151 | if oinf == nil { |
| 1152 | for _, f := range cons { |
| 1153 | if !g.isSigSupported(f.Type()) { |
| 1154 | g.Printf("// skipped constructor %s.%s with unsupported parameter or return types\n\n", obj, f.Name()) |
| 1155 | continue |
| 1156 | } |
| 1157 | g.genInitM(obj, f) |
| 1158 | } |
| 1159 | } |
| 1160 | if oinf != nil || len(cons) == 0 { |
| 1161 | g.Printf("- (nonnull instancetype)init {\n") |
| 1162 | g.Indent() |
| 1163 | g.Printf("self = [super init];\n") |
| 1164 | g.Printf("if (self) {\n") |
| 1165 | g.Indent() |
| 1166 | g.Printf("__ref = go_seq_from_refnum(new_%s_%s());\n", g.pkgPrefix, obj.Name()) |
| 1167 | g.Outdent() |
| 1168 | g.Printf("}\n") |
| 1169 | g.Printf("return self;\n") |
| 1170 | g.Outdent() |
| 1171 | g.Printf("}\n\n") |
| 1172 | } |
| 1173 | |
| 1174 | for _, f := range fields { |
| 1175 | if !g.isSupported(f.Type()) { |
| 1176 | g.Printf("// skipped unsupported field %s with type %s\n\n", f.Name(), f.Type()) |
| 1177 | continue |
| 1178 | } |
| 1179 | g.genGetter(obj.Name(), f) |
| 1180 | g.genSetter(obj.Name(), f) |
| 1181 | } |
| 1182 | |
| 1183 | for _, m := range methods { |
| 1184 | if !g.isSigSupported(m.Type()) { |
| 1185 | g.Printf("// skipped method %s.%s with unsupported parameter or return types\n\n", obj.Name(), m.Name()) |
| 1186 | continue |
| 1187 | } |
| 1188 | s := g.funcSummary(obj, m) |
| 1189 | g.Printf("- %s {\n", s.asMethod(g)) |
| 1190 | g.Indent() |
| 1191 | g.genFunc(s, obj.Name()) |
| 1192 | g.Outdent() |
| 1193 | g.Printf("}\n\n") |
| 1194 | } |
| 1195 | g.Printf("@end\n\n") |
| 1196 | } |
| 1197 | |
| 1198 | func (g *ObjcGen) genInitH(obj *types.TypeName, f *types.Func) { |
| 1199 | s := g.funcSummary(obj, f) |
| 1200 | doc := g.docs[f.Name()] |
| 1201 | g.objcdoc(doc.Doc()) |
| 1202 | |
| 1203 | // custom inits can return nil in Go so make them nullable |
| 1204 | g.Printf("- (nullable instancetype)%s%s;\n", s.initName, s.asInitSignature(g)) |
| 1205 | } |
| 1206 | |
| 1207 | func (g *ObjcGen) genInitM(obj *types.TypeName, f *types.Func) { |
| 1208 | s := g.funcSummary(obj, f) |
| 1209 | g.Printf("- (instancetype)%s%s {\n", s.initName, s.asInitSignature(g)) |
| 1210 | g.Indent() |
| 1211 | g.Printf("self = [super init];\n") |
| 1212 | g.Printf("if (!self) return nil;\n") |
| 1213 | for _, p := range s.params { |
| 1214 | g.genWrite(p.name, p.typ, modeTransient) |
| 1215 | } |
| 1216 | // Constructors always return a mandatory *T and an optional error |
| 1217 | if len(s.retParams) == 1 { |
| 1218 | g.Printf("%s refnum = ", g.cgoType(s.retParams[0].typ)) |
| 1219 | } else { |
| 1220 | g.Printf("struct proxy%s__%s_return res = ", g.pkgPrefix, s.goname) |
| 1221 | } |
| 1222 | g.Printf("proxy%s__%s(", g.pkgPrefix, s.goname) |
| 1223 | for i, p := range s.params { |
| 1224 | if i > 0 { |
| 1225 | g.Printf(", ") |
| 1226 | } |
| 1227 | g.Printf("_%s", p.name) |
| 1228 | } |
| 1229 | g.Printf(");\n") |
| 1230 | for _, p := range s.params { |
| 1231 | g.genRelease(p.name, p.typ, modeTransient) |
| 1232 | } |
| 1233 | if len(s.retParams) == 2 { |
| 1234 | g.Printf("int32_t refnum = res.r0;\n") |
| 1235 | g.Printf("GoSeqRef *_err = go_seq_from_refnum(res.r1);\n") |
| 1236 | } |
| 1237 | g.Printf("__ref = go_seq_from_refnum(refnum);\n") |
| 1238 | if len(s.retParams) == 2 { |
| 1239 | g.Printf("if (_err != NULL)\n") |
| 1240 | g.Printf(" return nil;\n") |
| 1241 | } |
| 1242 | g.Printf("return self;\n") |
| 1243 | g.Outdent() |
| 1244 | g.Printf("}\n\n") |
| 1245 | } |
| 1246 | |
| 1247 | func (g *ObjcGen) errorf(format string, args ...interface{}) { |
| 1248 | g.err = append(g.err, fmt.Errorf(format, args...)) |
| 1249 | } |
| 1250 | |
| 1251 | func (g *ObjcGen) refTypeBase(typ types.Type) string { |
| 1252 | switch typ := typ.(type) { |
| 1253 | case *types.Pointer: |
| 1254 | if _, ok := typ.Elem().(*types.Named); ok { |
| 1255 | return g.objcType(typ.Elem()) |
| 1256 | } |
| 1257 | case *types.Named: |
| 1258 | n := typ.Obj() |
| 1259 | if isObjcType(typ) { |
| 1260 | return g.wrapMap[n.Name()].Name |
| 1261 | } |
| 1262 | if isErrorType(typ) || g.validPkg(n.Pkg()) { |
| 1263 | switch typ.Underlying().(type) { |
| 1264 | case *types.Interface, *types.Struct: |
| 1265 | return g.namePrefixOf(n.Pkg()) + n.Name() |
| 1266 | } |
| 1267 | } |
| 1268 | } |
| 1269 | |
| 1270 | // fallback to whatever objcType returns. This must not happen. |
| 1271 | return g.objcType(typ) |
| 1272 | } |
| 1273 | |
| 1274 | func (g *ObjcGen) objcParamType(t types.Type) string { |
| 1275 | switch typ := types.Unalias(t).(type) { |
| 1276 | case *types.Basic: |
| 1277 | switch typ.Kind() { |
| 1278 | case types.String, types.UntypedString: |
| 1279 | return "NSString* _Nullable" |
| 1280 | } |
| 1281 | } |
| 1282 | return g.objcType(t) |
| 1283 | |
| 1284 | } |
| 1285 | |
| 1286 | func (g *ObjcGen) objcType(typ types.Type) string { |
| 1287 | |
| 1288 | if isErrorType(typ) { |
| 1289 | return "NSError* _Nullable" |
| 1290 | } |
| 1291 | |
| 1292 | switch typ := types.Unalias(typ).(type) { |
| 1293 | case *types.Basic: |
| 1294 | switch typ.Kind() { |
| 1295 | case types.Bool, types.UntypedBool: |
| 1296 | return "BOOL" |
| 1297 | case types.Int: |
| 1298 | return "long" |
| 1299 | case types.Int8: |
| 1300 | return "int8_t" |
| 1301 | case types.Int16: |
| 1302 | return "int16_t" |
| 1303 | case types.Int32, types.UntypedRune: // types.Rune |
| 1304 | return "int32_t" |
| 1305 | case types.Int64, types.UntypedInt: |
| 1306 | return "int64_t" |
| 1307 | case types.Uint8: |
| 1308 | // byte is an alias of uint8, and the alias is lost. |
| 1309 | return "byte" |
| 1310 | case types.Uint16: |
| 1311 | return "uint16_t" |
| 1312 | case types.Uint32: |
| 1313 | return "uint32_t" |
| 1314 | case types.Uint64: |
| 1315 | return "uint64_t" |
| 1316 | case types.Float32: |
| 1317 | return "float" |
| 1318 | case types.Float64, types.UntypedFloat: |
| 1319 | return "double" |
| 1320 | case types.String, types.UntypedString: |
| 1321 | return "NSString* _Nonnull" |
| 1322 | default: |
| 1323 | g.errorf("unsupported type: %s", typ) |
| 1324 | return "TODO" |
| 1325 | } |
| 1326 | case *types.Slice: |
| 1327 | elem := g.objcType(typ.Elem()) |
| 1328 | // Special case: NSData seems to be a better option for byte slice. |
| 1329 | if elem == "byte" { |
| 1330 | return "NSData* _Nullable" |
| 1331 | } |
| 1332 | // TODO(hyangah): support other slice types: NSArray or CFArrayRef. |
| 1333 | // Investigate the performance implication. |
| 1334 | g.errorf("unsupported type: %s", typ) |
| 1335 | return "TODO" |
| 1336 | case *types.Pointer: |
| 1337 | if _, ok := types.Unalias(typ.Elem()).(*types.Named); ok { |
| 1338 | return g.objcType(typ.Elem()) + "* _Nullable" |
| 1339 | } |
| 1340 | g.errorf("unsupported pointer to type: %s", typ) |
| 1341 | return "TODO" |
| 1342 | case *types.Named: |
| 1343 | n := typ.Obj() |
| 1344 | if isObjcType(typ) { |
| 1345 | w := g.wrapMap[n.Name()] |
| 1346 | return w.ObjcType() |
| 1347 | } |
| 1348 | if !isErrorType(typ) && !g.validPkg(n.Pkg()) { |
| 1349 | g.errorf("type %s is in package %s, which is not bound", n.Name(), n.Pkg().Name()) |
| 1350 | return "TODO" |
| 1351 | } |
| 1352 | switch t := typ.Underlying().(type) { |
| 1353 | case *types.Interface: |
| 1354 | if makeIfaceSummary(t).implementable { |
| 1355 | return "id<" + g.namePrefixOf(n.Pkg()) + n.Name() + "> _Nullable" |
| 1356 | } else { |
| 1357 | return g.namePrefixOf(n.Pkg()) + n.Name() + "* _Nullable" |
| 1358 | } |
| 1359 | case *types.Struct: |
| 1360 | return g.namePrefixOf(n.Pkg()) + n.Name() |
| 1361 | } |
| 1362 | g.errorf("unsupported, named type %s", typ) |
| 1363 | return "TODO" |
| 1364 | default: |
| 1365 | g.errorf("unsupported type: %#+v, %s", typ, typ) |
| 1366 | return "TODO" |
| 1367 | } |
| 1368 | } |
| 1369 | |
| 1370 | // embeddedObjcTypes returns the possible empty list of Objc types embedded |
| 1371 | // in the given struct type. |
| 1372 | func embeddedObjcTypes(t *types.Struct) []string { |
| 1373 | typeSet := make(map[string]struct{}) |
| 1374 | var typs []string |
| 1375 | for i := 0; i < t.NumFields(); i++ { |
| 1376 | f := t.Field(i) |
| 1377 | if !f.Exported() { |
| 1378 | continue |
| 1379 | } |
| 1380 | if ft := f.Type(); isObjcType(ft) { |
| 1381 | name := ft.(*types.Named).Obj().Name() |
| 1382 | if _, exists := typeSet[name]; !exists { |
| 1383 | typeSet[name] = struct{}{} |
| 1384 | typs = append(typs, name) |
| 1385 | } |
| 1386 | } |
| 1387 | } |
| 1388 | return typs |
| 1389 | } |
| 1390 | |
| 1391 | func isObjcType(t types.Type) bool { |
| 1392 | return typePkgFirstElem(t) == "ObjC" |
| 1393 | } |
| 1394 | |
| 1395 | var objcNameReplacer = newNameSanitizer([]string{ |
| 1396 | "bool", "bycopy", "byref", "char", "const", "double", "float", |
| 1397 | "id", "in", "init", "inout", "int", "long", "nil", "oneway", |
| 1398 | "out", "self", "short", "signed", "super", "unsigned", "void", |
| 1399 | "volatile"}) |
| 1400 | |
| 1401 | const ( |
| 1402 | objcPreamble = `// Objective-C API for talking to %[1]s Go package. |
| 1403 | // gobind %[2]s %[3]s |
| 1404 | // |
| 1405 | // File is generated by gobind. Do not edit. |
| 1406 | |
| 1407 | ` |
| 1408 | ) |