objc.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868
  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 objc package takes the result of an AST traversal by the
  5. // importers package and uses the clang command to dump the type
  6. // information for the referenced ObjC classes and protocols.
  7. //
  8. // It is the of go/types for ObjC types and is used by the bind
  9. // package to generate Go wrappers for ObjC API on iOS.
  10. package objc
  11. import (
  12. "bufio"
  13. "bytes"
  14. "fmt"
  15. "os/exec"
  16. "strings"
  17. "unicode"
  18. "unicode/utf8"
  19. "golang.org/x/mobile/internal/importers"
  20. )
  21. type parser struct {
  22. sdkPath string
  23. sc *bufio.Scanner
  24. decl string
  25. indent int
  26. last string
  27. // Current module as parsed from the AST tree.
  28. module string
  29. }
  30. type TypeKind int
  31. // Named represents ObjC classes and protocols.
  32. type Named struct {
  33. Name string
  34. GoName string
  35. Module string
  36. Funcs []*Func
  37. Methods []*Func
  38. AllMethods []*Func
  39. Supers []Super
  40. // For deduplication of function or method
  41. // declarations.
  42. funcMap map[string]struct{}
  43. Protocol bool
  44. // Generated is true if the type is wrapper of a
  45. // generated Go struct.
  46. Generated bool
  47. }
  48. // Super denotes a super class or protocol.
  49. type Super struct {
  50. Name string
  51. Protocol bool
  52. }
  53. // Func is a ObjC method, static functions as well as
  54. // instance methods.
  55. type Func struct {
  56. Sig string
  57. GoName string
  58. Params []*Param
  59. Ret *Type
  60. Static bool
  61. // Method whose name start with "init"
  62. Constructor bool
  63. }
  64. type Param struct {
  65. Name string
  66. Type *Type
  67. }
  68. type Type struct {
  69. Kind TypeKind
  70. // For Interface and Protocol types.
  71. Name string
  72. // For 'id' types.
  73. instanceType bool
  74. // The declared type raw from the AST.
  75. Decl string
  76. // Set if the type is a pointer to its kind. For classes
  77. // Indirect is true if the type is a double pointer, e.g.
  78. // NSObject **.
  79. Indirect bool
  80. }
  81. const (
  82. Unknown TypeKind = iota
  83. Protocol
  84. Class
  85. String
  86. Data
  87. Int
  88. Uint
  89. Short
  90. Ushort
  91. Bool
  92. Char
  93. Uchar
  94. Float
  95. Double
  96. )
  97. // Import returns descriptors for a list of references to
  98. // ObjC protocols and classes.
  99. //
  100. // The type information is parsed from the output of clang -cc1
  101. // -ast-dump.
  102. func Import(refs *importers.References) ([]*Named, error) {
  103. var modules []string
  104. modMap := make(map[string]struct{})
  105. typeNames := make(map[string][]string)
  106. typeSet := make(map[string]struct{})
  107. genMods := make(map[string]struct{})
  108. for _, emb := range refs.Embedders {
  109. genMods[initialUpper(emb.Pkg)] = struct{}{}
  110. }
  111. for _, ref := range refs.Refs {
  112. var module, name string
  113. if idx := strings.Index(ref.Pkg, "/"); idx != -1 {
  114. // ref is a static method reference.
  115. module = ref.Pkg[:idx]
  116. name = ref.Pkg[idx+1:]
  117. } else {
  118. // ref is a type name.
  119. module = ref.Pkg
  120. name = ref.Name
  121. }
  122. if _, exists := typeSet[name]; !exists {
  123. typeNames[module] = append(typeNames[module], name)
  124. typeSet[name] = struct{}{}
  125. }
  126. if _, exists := modMap[module]; !exists {
  127. // Include the module only if it is generated.
  128. if _, exists := genMods[module]; !exists {
  129. modMap[module] = struct{}{}
  130. modules = append(modules, module)
  131. }
  132. }
  133. }
  134. sdkPathOut, err := exec.Command("xcrun", "--sdk", "iphonesimulator", "--show-sdk-path").CombinedOutput()
  135. if err != nil {
  136. return nil, err
  137. }
  138. sdkPath := strings.TrimSpace(string(sdkPathOut))
  139. var allTypes []*Named
  140. typeMap := make(map[string]*Named)
  141. for _, module := range modules {
  142. types, err := importModule(string(sdkPath), module, typeNames[module], typeMap)
  143. if err != nil {
  144. return nil, fmt.Errorf("%s: %v", module, err)
  145. }
  146. allTypes = append(allTypes, types...)
  147. }
  148. // Embedders refer to every exported Go struct that will have its class
  149. // generated. Allow Go code to reverse bind to those classes by synthesizing
  150. // their descriptors.
  151. for _, emb := range refs.Embedders {
  152. module := initialUpper(emb.Pkg)
  153. named := &Named{
  154. Name: module + emb.Name,
  155. GoName: emb.Name,
  156. Module: module,
  157. Generated: true,
  158. }
  159. for _, ref := range emb.Refs {
  160. t, exists := typeMap[ref.Name]
  161. if !exists {
  162. return nil, fmt.Errorf("type not found: %q", ref.Name)
  163. }
  164. named.Supers = append(named.Supers, Super{
  165. Name: t.Name,
  166. Protocol: t.Protocol,
  167. })
  168. }
  169. typeMap[emb.Name] = named
  170. allTypes = append(allTypes, named)
  171. }
  172. initTypes(allTypes, refs, typeMap)
  173. // Include implicit types that are used in parameter or return values.
  174. newTypes := allTypes
  175. for len(newTypes) > 0 {
  176. var impTypes []*Named
  177. for _, t := range newTypes {
  178. for _, funcs := range [][]*Func{t.Funcs, t.AllMethods} {
  179. for _, f := range funcs {
  180. types := implicitFuncTypes(f)
  181. for _, name := range types {
  182. if _, exists := typeSet[name]; exists {
  183. continue
  184. }
  185. typeSet[name] = struct{}{}
  186. t, exists := typeMap[name]
  187. if !exists {
  188. return nil, fmt.Errorf("implicit type %q not found", name)
  189. }
  190. impTypes = append(impTypes, t)
  191. }
  192. }
  193. }
  194. }
  195. initTypes(impTypes, refs, typeMap)
  196. allTypes = append(allTypes, impTypes...)
  197. newTypes = impTypes
  198. }
  199. return allTypes, nil
  200. }
  201. func implicitFuncTypes(f *Func) []string {
  202. var types []string
  203. if rt := f.Ret; rt != nil && !rt.instanceType && (rt.Kind == Class || rt.Kind == Protocol) {
  204. types = append(types, rt.Name)
  205. }
  206. for _, p := range f.Params {
  207. if t := p.Type; !t.instanceType && (t.Kind == Class || t.Kind == Protocol) {
  208. types = append(types, t.Name)
  209. }
  210. }
  211. return types
  212. }
  213. func initTypes(types []*Named, refs *importers.References, typeMap map[string]*Named) {
  214. for _, t := range types {
  215. fillAllMethods(t, typeMap)
  216. }
  217. // Move constructors to functions. They are represented in Go
  218. // as functions.
  219. for _, t := range types {
  220. var methods []*Func
  221. for _, f := range t.AllMethods {
  222. if f.Constructor {
  223. f.Static = true
  224. t.Funcs = append(t.Funcs, f)
  225. } else {
  226. methods = append(methods, f)
  227. }
  228. }
  229. t.AllMethods = methods
  230. }
  231. for _, t := range types {
  232. mangleMethodNames(t.AllMethods)
  233. mangleMethodNames(t.Funcs)
  234. }
  235. filterReferences(types, refs, typeMap)
  236. for _, t := range types {
  237. resolveInstanceTypes(t, t.Funcs)
  238. resolveInstanceTypes(t, t.AllMethods)
  239. }
  240. }
  241. func filterReferences(types []*Named, refs *importers.References, typeMap map[string]*Named) {
  242. refFuncs := make(map[[2]string]struct{})
  243. for _, ref := range refs.Refs {
  244. if sep := strings.Index(ref.Pkg, "/"); sep != -1 {
  245. pkgName := ref.Pkg[sep+1:]
  246. n := typeMap[pkgName]
  247. if n == nil {
  248. continue
  249. }
  250. refFuncs[[...]string{pkgName, ref.Name}] = struct{}{}
  251. }
  252. }
  253. for _, t := range types {
  254. var filtered []*Func
  255. for _, f := range t.Funcs {
  256. if _, exists := refFuncs[[...]string{t.GoName, f.GoName}]; exists {
  257. filtered = append(filtered, f)
  258. }
  259. }
  260. t.Funcs = filtered
  261. filtered = nil
  262. for _, m := range t.Methods {
  263. if _, exists := refs.Names[m.GoName]; exists {
  264. filtered = append(filtered, m)
  265. }
  266. }
  267. t.Methods = filtered
  268. filtered = nil
  269. for _, m := range t.AllMethods {
  270. if _, exists := refs.Names[m.GoName]; exists {
  271. filtered = append(filtered, m)
  272. }
  273. }
  274. t.AllMethods = filtered
  275. }
  276. }
  277. // mangleMethodNames assigns unique Go names to ObjC methods. If a method name is unique
  278. // within the same method list, its name is used with its first letter in upper case.
  279. // Multiple methods with the same name have their full signature appended, with : removed.
  280. func mangleMethodNames(allFuncs []*Func) {
  281. goName := func(n string, constructor bool) string {
  282. if constructor {
  283. n = "new" + n[len("init"):]
  284. }
  285. return initialUpper(n)
  286. }
  287. overloads := make(map[string][]*Func)
  288. for i, f := range allFuncs {
  289. // Copy function so each class can have its own
  290. // name mangling.
  291. f := *f
  292. allFuncs[i] = &f
  293. f.GoName = goName(f.Sig, f.Constructor)
  294. if colon := strings.Index(f.GoName, ":"); colon != -1 {
  295. f.GoName = f.GoName[:colon]
  296. }
  297. overloads[f.GoName] = append(overloads[f.GoName], &f)
  298. }
  299. fallbacks := make(map[string][]*Func)
  300. for _, funcs := range overloads {
  301. if len(funcs) == 1 {
  302. continue
  303. }
  304. for _, f := range funcs {
  305. sig := f.Sig
  306. if strings.HasSuffix(sig, ":") {
  307. sig = sig[:len(sig)-1]
  308. }
  309. sigElems := strings.Split(f.Sig, ":")
  310. for i := 0; i < len(sigElems); i++ {
  311. sigElems[i] = initialUpper(sigElems[i])
  312. }
  313. name := strings.Join(sigElems, "")
  314. f.GoName = goName(name, f.Constructor)
  315. fallbacks[f.GoName] = append(fallbacks[f.GoName], f)
  316. }
  317. }
  318. for _, funcs := range fallbacks {
  319. if len(funcs) == 1 {
  320. continue
  321. }
  322. for _, f := range funcs {
  323. name := strings.Replace(f.Sig, ":", "_", -1)
  324. f.GoName = goName(name, f.Constructor)
  325. }
  326. }
  327. }
  328. func resolveInstanceType(n *Named, t *Type) *Type {
  329. if !t.instanceType || t.Kind != Protocol {
  330. return t
  331. }
  332. // Copy and update the type name for instancetype types
  333. ct := *t
  334. ct.instanceType = false
  335. ct.Decl = n.Name + " *"
  336. if n.Name == "NSString" {
  337. ct.Kind = String
  338. ct.Name = ""
  339. } else {
  340. ct.Kind = Class
  341. ct.Name = n.Name
  342. }
  343. return &ct
  344. }
  345. func resolveInstanceTypes(n *Named, funcs []*Func) {
  346. for _, f := range funcs {
  347. for _, p := range f.Params {
  348. p.Type = resolveInstanceType(n, p.Type)
  349. }
  350. if f.Ret != nil {
  351. f.Ret = resolveInstanceType(n, f.Ret)
  352. }
  353. }
  354. }
  355. func fillAllMethods(n *Named, typeMap map[string]*Named) {
  356. if len(n.AllMethods) > 0 {
  357. return
  358. }
  359. if len(n.Supers) == 0 {
  360. n.AllMethods = n.Methods
  361. return
  362. }
  363. for _, sup := range n.Supers {
  364. super := lookup(sup.Name, sup.Protocol, typeMap)
  365. fillAllMethods(super, typeMap)
  366. }
  367. methods := make(map[string]struct{})
  368. for _, sup := range n.Supers {
  369. super := lookup(sup.Name, sup.Protocol, typeMap)
  370. for _, f := range super.AllMethods {
  371. if _, exists := methods[f.Sig]; !exists {
  372. methods[f.Sig] = struct{}{}
  373. n.AllMethods = append(n.AllMethods, f)
  374. }
  375. }
  376. }
  377. for _, f := range n.Methods {
  378. if _, exists := methods[f.Sig]; !exists {
  379. n.AllMethods = append(n.AllMethods, f)
  380. }
  381. }
  382. }
  383. const (
  384. frameworksPath = "/System/Library/Frameworks/"
  385. )
  386. // importModule parses ObjC type information with clang -cc1 -ast-dump.
  387. //
  388. // TODO: Use module.map files to precisely model the @import Module.Identifier
  389. // directive. For now, importModules assumes the single umbrella header
  390. // file Module.framework/Headers/Module.h contains every declaration.
  391. func importModule(sdkPath, module string, identifiers []string, typeMap map[string]*Named) ([]*Named, error) {
  392. hFile := fmt.Sprintf(sdkPath+frameworksPath+"%s.framework/Headers/%[1]s.h", module)
  393. clang := exec.Command("xcrun", "--sdk", "iphonesimulator", "clang", "-cc1", "-triple", "x86_64-apple-ios8.0.0-simulator", "-isysroot", sdkPath, "-ast-dump", "-fblocks", "-fobjc-arc", "-x", "objective-c", hFile)
  394. out, err := clang.CombinedOutput()
  395. if err != nil {
  396. return nil, fmt.Errorf("clang failed to parse module: %v: %s", err, out)
  397. }
  398. p := &parser{
  399. sdkPath: sdkPath,
  400. sc: bufio.NewScanner(bytes.NewBuffer(out)),
  401. }
  402. if err := p.parseModule(module, typeMap); err != nil {
  403. return nil, err
  404. }
  405. var types []*Named
  406. for _, ident := range identifiers {
  407. named, exists := typeMap[ident]
  408. if !exists {
  409. return nil, fmt.Errorf("no such type: %s", ident)
  410. }
  411. types = append(types, named)
  412. }
  413. return types, nil
  414. }
  415. func (p *parser) scanLine() bool {
  416. for {
  417. l := p.last
  418. if l == "" {
  419. if !p.sc.Scan() {
  420. return false
  421. }
  422. l = p.sc.Text()
  423. } else {
  424. p.last = ""
  425. }
  426. indent := (strings.Index(l, "-") + 1) / 2
  427. switch {
  428. case indent > p.indent:
  429. // Skip
  430. case indent < p.indent:
  431. p.indent--
  432. p.last = l
  433. return false
  434. case indent == p.indent:
  435. p.decl = l[p.indent*2:]
  436. return true
  437. }
  438. }
  439. }
  440. func (p *parser) parseModule(module string, typeMap map[string]*Named) (err error) {
  441. defer func() {
  442. if rerr := recover(); rerr != nil {
  443. err = rerr.(error)
  444. }
  445. }()
  446. if !p.scanLine() {
  447. return nil
  448. }
  449. // A header file AST starts with
  450. //
  451. // TranslationUnitDecl 0x103833ad0 <<invalid sloc>> <invalid sloc>
  452. if w := p.scanWord(); w != "TranslationUnitDecl" {
  453. return fmt.Errorf("unexpected AST root: %q", w)
  454. }
  455. p.indent++
  456. for {
  457. if !p.scanLine() {
  458. break
  459. }
  460. switch w := p.scanWord(); w {
  461. case "ObjCCategoryDecl":
  462. // ObjCCategoryDecl 0x103d9bdb8 <line:48:1, line:63:2> line:48:12 NSDateCreation
  463. // |-ObjCInterface 0x103d9a788 'NSDate'
  464. // Skip the node address, the source code range, position.
  465. p.scanWord()
  466. p.parseLocation()
  467. catName := p.scanWord()
  468. p.indent++
  469. if !p.scanLine() {
  470. return fmt.Errorf("no interface for category %s", catName)
  471. }
  472. if w := p.scanWord(); w != "ObjCInterface" {
  473. return fmt.Errorf("unexpected declaaration %s for category %s", w, catName)
  474. }
  475. p.scanWord()
  476. clsName := p.scanWord()
  477. clsName = clsName[1 : len(clsName)-1]
  478. named := lookup(clsName, false, typeMap)
  479. if named == nil {
  480. return fmt.Errorf("category %s references unknown class %s", catName, clsName)
  481. }
  482. p.parseInterface(named)
  483. case "ObjCInterfaceDecl", "ObjCProtocolDecl":
  484. // ObjCProtocolDecl 0x104116450 <line:15:1, line:47:2> line:15:11 NSObject
  485. // or
  486. // ObjCInterfaceDecl 0x1041ca480 <line:17:29, line:64:2> line:17:40 UIResponder
  487. prot := w == "ObjCProtocolDecl"
  488. // Skip the node address, the source code range, position.
  489. p.scanWord()
  490. if strings.HasPrefix(p.decl, "prev ") {
  491. p.scanWord()
  492. p.scanWord()
  493. }
  494. p.parseLocation()
  495. if strings.HasPrefix(p.decl, "implicit ") {
  496. p.scanWord()
  497. }
  498. name := p.decl
  499. named := p.lookupOrCreate(name, prot, typeMap)
  500. p.indent++
  501. p.parseInterface(named)
  502. default:
  503. }
  504. }
  505. return nil
  506. }
  507. func lookup(name string, prot bool, typeMap map[string]*Named) *Named {
  508. var mangled string
  509. if prot {
  510. mangled = name + "P"
  511. } else {
  512. mangled = name + "C"
  513. }
  514. if n := typeMap[mangled]; n != nil {
  515. return n
  516. }
  517. return typeMap[name]
  518. }
  519. // lookupOrCreate looks up the type name in the type map. If it doesn't exist, it creates
  520. // and returns a new type. If it does exist, it returns the existing type. If there are both
  521. // a class and a protocol with the same name, their type names are mangled by prefixing
  522. // 'C' or 'P' and then re-inserted into the type map.
  523. func (p *parser) lookupOrCreate(name string, prot bool, typeMap map[string]*Named) *Named {
  524. mangled := name + "C"
  525. otherMangled := name + "P"
  526. if prot {
  527. mangled, otherMangled = otherMangled, mangled
  528. }
  529. named, exists := typeMap[mangled]
  530. if exists {
  531. return named
  532. }
  533. named, exists = typeMap[name]
  534. if exists {
  535. if named.Protocol == prot {
  536. return named
  537. }
  538. // Both a class and a protocol exists with the same name.
  539. delete(typeMap, name)
  540. named.GoName = otherMangled
  541. typeMap[otherMangled] = named
  542. named = &Named{
  543. GoName: mangled,
  544. }
  545. } else {
  546. named = &Named{
  547. GoName: name,
  548. }
  549. }
  550. named.Name = name
  551. named.Protocol = prot
  552. named.funcMap = make(map[string]struct{})
  553. named.Module = p.module
  554. typeMap[named.GoName] = named
  555. return named
  556. }
  557. func (p *parser) parseInterface(n *Named) {
  558. for {
  559. more := p.scanLine()
  560. if !more {
  561. break
  562. }
  563. switch w := p.scanWord(); w {
  564. case "super":
  565. if w := p.scanWord(); w != "ObjCInterface" {
  566. panic(fmt.Errorf("unknown super type: %s", w))
  567. }
  568. // Skip node address.
  569. p.scanWord()
  570. super := p.scanWord()
  571. // Remove single quotes
  572. super = super[1 : len(super)-1]
  573. n.Supers = append(n.Supers, Super{super, false})
  574. case "ObjCProtocol":
  575. p.scanWord()
  576. super := p.scanWord()
  577. super = super[1 : len(super)-1]
  578. n.Supers = append(n.Supers, Super{super, true})
  579. case "ObjCMethodDecl":
  580. f := p.parseMethod()
  581. if f == nil {
  582. continue
  583. }
  584. var key string
  585. if f.Static {
  586. key = "+" + f.Sig
  587. } else {
  588. key = "-" + f.Sig
  589. }
  590. if _, exists := n.funcMap[key]; !exists {
  591. n.funcMap[key] = struct{}{}
  592. if f.Static {
  593. n.Funcs = append(n.Funcs, f)
  594. } else {
  595. n.Methods = append(n.Methods, f)
  596. }
  597. }
  598. }
  599. }
  600. }
  601. func (p *parser) parseMethod() *Func {
  602. // ObjCMethodDecl 0x103bdfb80 <line:17:1, col:27> col:1 - isEqual: 'BOOL':'_Bool'
  603. // Skip the address, range, position.
  604. p.scanWord()
  605. p.parseLocation()
  606. if strings.HasPrefix(p.decl, "implicit") {
  607. p.scanWord()
  608. }
  609. f := new(Func)
  610. switch w := p.scanWord(); w {
  611. case "+":
  612. f.Static = true
  613. case "-":
  614. f.Static = false
  615. default:
  616. panic(fmt.Errorf("unknown method type for %q", w))
  617. }
  618. f.Sig = p.scanWord()
  619. if f.Sig == "dealloc" {
  620. // ARC forbids dealloc
  621. return nil
  622. }
  623. if strings.HasPrefix(f.Sig, "init") {
  624. f.Constructor = true
  625. }
  626. f.Ret = p.parseType()
  627. p.indent++
  628. for {
  629. more := p.scanLine()
  630. if !more {
  631. break
  632. }
  633. switch p.scanWord() {
  634. case "UnavailableAttr":
  635. p.indent--
  636. return nil
  637. case "ParmVarDecl":
  638. f.Params = append(f.Params, p.parseParameter())
  639. }
  640. }
  641. return f
  642. }
  643. func (p *parser) parseParameter() *Param {
  644. // ParmVarDecl 0x1041caca8 <col:70, col:80> col:80 event 'UIEvent * _Nullable':'UIEvent *'
  645. // Skip address, source range, position.
  646. p.scanWord()
  647. p.parseLocation()
  648. return &Param{Name: p.scanWord(), Type: p.parseType()}
  649. }
  650. func (p *parser) parseType() *Type {
  651. // NSUInteger':'unsigned long'
  652. s := strings.SplitN(p.decl, ":", 2)
  653. decl := s[0]
  654. var canon string
  655. if len(s) == 2 {
  656. canon = s[1]
  657. } else {
  658. canon = decl
  659. }
  660. // unquote the type
  661. canon = canon[1 : len(canon)-1]
  662. if canon == "void" {
  663. return nil
  664. }
  665. decl = decl[1 : len(decl)-1]
  666. instancetype := strings.HasPrefix(decl, "instancetype")
  667. // Strip modifiers
  668. mods := []string{"__strong", "__unsafe_unretained", "const", "__strong", "_Nonnull", "_Nullable", "__autoreleasing"}
  669. for _, mod := range mods {
  670. if idx := strings.Index(canon, mod); idx != -1 {
  671. canon = canon[:idx] + canon[idx+len(mod):]
  672. }
  673. if idx := strings.Index(decl, mod); idx != -1 {
  674. decl = decl[:idx] + decl[idx+len(mod):]
  675. }
  676. }
  677. canon = strings.TrimSpace(canon)
  678. decl = strings.TrimSpace(decl)
  679. t := &Type{
  680. Decl: decl,
  681. instanceType: instancetype,
  682. }
  683. switch canon {
  684. case "int", "long", "long long":
  685. t.Kind = Int
  686. case "unsigned int", "unsigned long", "unsigned long long":
  687. t.Kind = Uint
  688. case "short":
  689. t.Kind = Short
  690. case "unsigned short":
  691. t.Kind = Ushort
  692. case "char":
  693. t.Kind = Char
  694. case "unsigned char":
  695. t.Kind = Uchar
  696. case "float":
  697. t.Kind = Float
  698. case "double":
  699. t.Kind = Double
  700. case "_Bool":
  701. t.Kind = Bool
  702. case "NSString *":
  703. t.Kind = String
  704. case "NSData *":
  705. t.Kind = Data
  706. default:
  707. switch {
  708. case strings.HasPrefix(canon, "enum"):
  709. t.Kind = Int
  710. case strings.HasPrefix(canon, "id"):
  711. _, gen := p.splitGeneric(canon)
  712. t.Kind = Protocol
  713. t.Name = gen
  714. default:
  715. if ind := strings.Count(canon, "*"); 1 <= ind && ind <= 2 {
  716. space := strings.Index(canon, " ")
  717. name := canon[:space]
  718. name, _ = p.splitGeneric(name)
  719. t.Kind = Class
  720. t.Name = name
  721. t.Indirect = ind > 1
  722. }
  723. }
  724. }
  725. return t
  726. }
  727. func (p *parser) splitGeneric(decl string) (string, string) {
  728. // NSArray<KeyType>
  729. if br := strings.Index(decl, "<"); br != -1 {
  730. return decl[:br], decl[br+1 : len(decl)-1]
  731. } else {
  732. return decl, ""
  733. }
  734. }
  735. func (p *parser) parseSrcPos() {
  736. const invPref = "<invalid sloc>"
  737. if strings.HasPrefix(p.decl, invPref) {
  738. p.decl = p.decl[len(invPref):]
  739. return
  740. }
  741. var loc string
  742. const scrPref = "<scratch space>"
  743. if strings.HasPrefix(p.decl, scrPref) {
  744. // <scratch space>:130:1
  745. p.decl = p.decl[len(scrPref):]
  746. loc = "line" + p.scanWord()
  747. } else {
  748. // line:17:2, col:18 or, a file location:
  749. // /.../UIKit.framework/Headers/UISelectionFeedbackGenerator.h:16:1
  750. loc = p.scanWord()
  751. }
  752. locs := strings.SplitN(loc, ":", 2)
  753. if len(locs) != 2 && len(locs) != 3 {
  754. panic(fmt.Errorf("invalid source position: %q", loc))
  755. }
  756. switch loc := locs[0]; loc {
  757. case "line", "col":
  758. default:
  759. if !strings.HasPrefix(loc, p.sdkPath) {
  760. panic(fmt.Errorf("invalid source position: %q", loc))
  761. }
  762. loc = loc[len(p.sdkPath):]
  763. switch {
  764. case strings.HasPrefix(loc, "/usr/include/objc/"):
  765. p.module = "Foundation"
  766. case strings.HasPrefix(loc, frameworksPath):
  767. loc = loc[len(frameworksPath):]
  768. i := strings.Index(loc, ".framework")
  769. if i == -1 {
  770. panic(fmt.Errorf("invalid source position: %q", loc))
  771. }
  772. p.module = loc[:i]
  773. // Some types are declared in CoreFoundation.framework
  774. // even though they belong in Foundation in Objective-C.
  775. if p.module == "CoreFoundation" {
  776. p.module = "Foundation"
  777. }
  778. default:
  779. }
  780. }
  781. }
  782. func (p *parser) parseLocation() {
  783. // Source ranges are on the form: <line:17:29, line:64:2>.
  784. if !strings.HasPrefix(p.decl, "<") {
  785. panic(fmt.Errorf("1no source range first in %s", p.decl))
  786. }
  787. p.decl = p.decl[1:]
  788. p.parseSrcPos()
  789. if strings.HasPrefix(p.decl, ", ") {
  790. p.decl = p.decl[2:]
  791. p.parseSrcPos()
  792. }
  793. if !strings.HasPrefix(p.decl, "> ") {
  794. panic(fmt.Errorf("no source range first in %s", p.decl))
  795. }
  796. p.decl = p.decl[2:]
  797. p.parseSrcPos()
  798. }
  799. func (p *parser) scanWord() string {
  800. i := 0
  801. loop:
  802. for ; i < len(p.decl); i++ {
  803. switch p.decl[i] {
  804. case ' ', '>', ',':
  805. break loop
  806. }
  807. }
  808. w := p.decl[:i]
  809. p.decl = p.decl[i:]
  810. for len(p.decl) > 0 && p.decl[0] == ' ' {
  811. p.decl = p.decl[1:]
  812. }
  813. return w
  814. }
  815. func initialUpper(s string) string {
  816. if s == "" {
  817. return ""
  818. }
  819. r, n := utf8.DecodeRuneInString(s)
  820. return string(unicode.ToUpper(r)) + s[n:]
  821. }
  822. func (t *Named) ObjcType() string {
  823. if t.Protocol {
  824. return fmt.Sprintf("id<%s> _Nullable", t.Name)
  825. } else {
  826. return t.Name + " * _Nullable"
  827. }
  828. }