FieldDescriptor.swift 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. //
  2. // FieldDescriptor.swift
  3. // HandyJSON
  4. //
  5. // Created by chantu on 2019/1/31.
  6. // Copyright © 2019 aliyun. All rights reserved.
  7. //
  8. import Foundation
  9. enum FieldDescriptorKind : UInt16 {
  10. // Swift nominal types.
  11. case Struct = 0
  12. case Class
  13. case Enum
  14. // Fixed-size multi-payload enums have a special descriptor format that
  15. // encodes spare bits.
  16. //
  17. // FIXME: Actually implement this. For now, a descriptor with this kind
  18. // just means we also have a builtin descriptor from which we get the
  19. // size and alignment.
  20. case MultiPayloadEnum
  21. // A Swift opaque protocol. There are no fields, just a record for the
  22. // type itself.
  23. case `Protocol`
  24. // A Swift class-bound protocol.
  25. case ClassProtocol
  26. // An Objective-C protocol, which may be imported or defined in Swift.
  27. case ObjCProtocol
  28. // An Objective-C class, which may be imported or defined in Swift.
  29. // In the former case, field type metadata is not emitted, and
  30. // must be obtained from the Objective-C runtime.
  31. case ObjCClass
  32. }
  33. struct FieldDescriptor: PointerType {
  34. var pointer: UnsafePointer<_FieldDescriptor>
  35. var fieldRecordSize: Int {
  36. return Int(pointer.pointee.fieldRecordSize)
  37. }
  38. var numFields: Int {
  39. return Int(pointer.pointee.numFields)
  40. }
  41. var fieldRecords: [FieldRecord] {
  42. return (0..<numFields).map({ (i) -> FieldRecord in
  43. return FieldRecord(pointer: UnsafePointer<_FieldRecord>(pointer + 1) + i)
  44. })
  45. }
  46. }
  47. struct _FieldDescriptor {
  48. var mangledTypeNameOffset: Int32
  49. var superClassOffset: Int32
  50. var fieldDescriptorKind: FieldDescriptorKind
  51. var fieldRecordSize: Int16
  52. var numFields: Int32
  53. }
  54. struct FieldRecord: PointerType {
  55. var pointer: UnsafePointer<_FieldRecord>
  56. var fieldRecordFlags: Int {
  57. return Int(pointer.pointee.fieldRecordFlags)
  58. }
  59. var mangledTypeName: UnsafePointer<UInt8>? {
  60. let address = Int(bitPattern: pointer) + 1 * 4
  61. let offset = Int(pointer.pointee.mangledTypeNameOffset)
  62. let cString = UnsafePointer<UInt8>(bitPattern: address + offset)
  63. return cString
  64. }
  65. var fieldName: String {
  66. let address = Int(bitPattern: pointer) + 2 * 4
  67. let offset = Int(pointer.pointee.fieldNameOffset)
  68. if let cString = UnsafePointer<UInt8>(bitPattern: address + offset) {
  69. return String(cString: cString)
  70. }
  71. return ""
  72. }
  73. }
  74. struct _FieldRecord {
  75. var fieldRecordFlags: Int32
  76. var mangledTypeNameOffset: Int32
  77. var fieldNameOffset: Int32
  78. }