一篇带给你Swift 中的反射 Mirror

开发 前端
Mirror是Swift中的反射机制,对于C#和Java开发人员来说,应该很熟悉反射这个概念。反射就是可以动态的获取类型以及成员信息,同时也可以在运行时动态的调用方法和属性等。

[[394200]]

前言

Mirror是Swift中的反射机制,对于C#和Java开发人员来说,应该很熟悉反射这个概念。反射就是可以动态的获取类型以及成员信息,同时也可以在运行时动态的调用方法和属性等。

对于iOS开发人员来说,入门时使用的Objective-C是很少强调反射概念的,因为OC的Runtime要比其他语言的反射强大的多。

1. Mirror 简介

Mirror是Swift中的反射机制的实现,它的本质是一个结构体。其部分源码(Swift 5.3.1)如下:

  1. public struct Mirror { 
  2.  
  3.   /// A suggestion of how a mirror's subject is to be interpreted. 
  4.   /// 
  5.   /// Playgrounds and the debugger will show a representation similar 
  6.   /// to the one used for instances of the kind indicated by the 
  7.   /// `DisplayStyle` case name when the mirror is used for display. 
  8.   public enum DisplayStyle { 
  9.     case `struct`, `class`, `enum`, tuple, optional, collection 
  10.     case dictionary, `set
  11.   } 
  12.      
  13.     /// The static type of the subject being reflected. 
  14.     /// 
  15.     /// This type may differ from the subject's dynamic type when this mirror 
  16.     /// is the `superclassMirror` of another mirror. 
  17.     public let subjectType: Any.Type 
  18.  
  19.     /// A collection of `Child` elements describing the structure of the 
  20.     /// reflected subject. 
  21.     public let children: Children 
  22.  
  23.     /// A suggested display style for the reflected subject. 
  24.     public let displayStyle: DisplayStyle? 
  25.  
  26.     /// A mirror of the subject's superclass, if one exists. 
  27.     public var superclassMirror: Mirror? { 
  28.       return _makeSuperclassMirror() 
  29.     } 
  • subjectType:表示类型,被反射主体的类型
  • children:子元素集合
  • displayStyle:显示类型,基本类型为 nil 枚举值: struct, class, enum, tuple, optional, collection, dictionary, set
  • superclassMirror:父类反射, 没有父类为 nil

除了这些属性还有一些初始化方法,我们最常用的就是初始化方法就是:

  1. /// Creates a mirror that reflects on the given instance. 
  2. /// 
  3. /// If the dynamic type of `subject` conforms to `CustomReflectable`, the 
  4. /// resulting mirror is determined by its `customMirror` property. 
  5. /// Otherwise, the result is generated by the language. 
  6. /// 
  7. /// If the dynamic type of `subject` has value semantics, subsequent 
  8. /// mutations of `subject` will not observable in `Mirror`.  In general, 
  9. /// though, the observability of mutations is unspecified. 
  10. /// 
  11. /// - Parameter subject: The instance for which to create a mirror. 
  12. public init(reflecting subject: Any) { 
  13.   if case let customized as CustomReflectable = subject { 
  14.     self = customized.customMirror 
  15.   } else { 
  16.     self = Mirror(internalReflecting: subject) 
  17.   } 

根据源码我们还可以看到能够使用customMirror,这个没太研究,在源码中可以看到很多CustomMirror的身影,感兴趣的可以去研究研究。对于非customMirror的统一使用Mirror(internalReflecting:)进行初始化。

关于customMirror的补充,摘抄自 swiftGG Mirror 的工作原理。

Mirror允许类型用遵循 CustomReflectable 协议的方式提供一个自定义的表示方式。这给那些想表示得比内建形式更友好的类型提供一种有效的方法。比如 Array 类型遵守 CustomReflectable 协议并且暴露其中的元素为无标签的 Children。Dictionary 使用这种方法暴露其中的键值对为带标签的 Children。

2. Mirror的简单使用

▐ 2.1 基本使用

这里我们通过使用Mirror打印对象的属性名称和属性值。

  1. class Person { 
  2.     var name: String = "xiaohei" 
  3.     var age: Int = 18 
  4.     var height = 1.85 
  5.  
  6. var p = Person() 
  7. var mirror = Mirror(reflecting: p.self) 
  8.  
  9. print("对象类型:\(mirror.subjectType)"
  10. print("对象属性个数:\(mirror.children.count)"
  11. print("对象的属性及属性值"
  12. for child in mirror.children { 
  13.     print("\(child.label!)---\(child.value)"

打印结果:

我们可以看到,属性名称和值都已经正常打印。

▐ 2.2 将对象转换为字典

首先我们来体验一下将对象转换为字典。

  1. class Animal { 
  2.     var name: String? 
  3.     var color: String? 
  4.     private var birthday: Date = Date(timeIntervalSince1970: 0) 
  5.   
  6. class Cat: Animal { 
  7.     var master = "小黑" 
  8.     var like: [String] = ["mouse""fish"
  9.      
  10.     override init() { 
  11.         super.init() 
  12.         color = "黄色" 
  13.     } 
  14.  
  15. func mapDic(mirror: Mirror) -> [String: Any] { 
  16.     var dic: [String: Any] = [:] 
  17.     for child in mirror.children { 
  18.         // 如果没有labe就会被抛弃 
  19.         if let label = child.label { 
  20.             let propertyMirror = Mirror(reflecting: child.value) 
  21.             print(propertyMirror) 
  22.             dic[label] = child.value 
  23.         } 
  24.     } 
  25.     // 添加父类属性 
  26.     if let superMirror = mirror.superclassMirror { 
  27.         let superDic = mapDic(mirror: superMirror) 
  28.         for p in superDic { 
  29.             dic[p.key] = p.value 
  30.         } 
  31.     } 
  32.     return dic 
  33.  
  34.  
  35. // Mirror使用 
  36. let cat = Cat() 
  37. cat.name = "大橘为重" 
  38. let mirror = Mirror(reflecting: cat) 
  39. let mirrorDic = mapDic(mirror: mirror) 
  40. print(mirrorDic) 

打印结果:

通过打印结果我们可以看到,对于一些基本类型,已经可选类型的数据都已经转换为字典值,对于私有属性也可以完成转换。如果里面包含类则还需要进行递归处理。

▐ 2.3 转 JSON

注:这里并没有真正的转换成json字符串,还是只转换成了字典,重要在思想,如果需要转换成json还需要很多优化,以及特殊字符串的考量。

其实提到反射我们想到最多的应该就是JSON了,这里我们利用Mirror的特性,将对象转换成字典,对基本类型和类做了相应的处理,体会一下转json的思路。

首先我们定义一个Person对象,代码如下:

  1. struct Person { 
  2.     var name: String = "xiaohei" 
  3.     var age: Int = 18 
  4.     var isMale: Bool = true 
  5.     var address: Address? = Address(street: "xizhimen North"
  6.     var height = 1.85 
  7.     var like: Array = ["eat""sleep""play"
  8.     var weight: Float = 75.0 
  9.     var someInt
  10.  
  11. struct Address { 
  12.     var street: String 
  13.  
  14. // 创建一个Person对象 
  15. let p = Person() 

为了通用性,我们可以编写一个协议,用来为所有类型提供转换的方法,只需要遵守该协议就可以使用协议中的方法。

  1. //可以转换为 Json 的协议 
  2. protocol CustomJSONProtocol { 
  3.     func toJSON() throws -> Any

协议的实现过程中会有些错误,我们也简单的定义个枚举,方便处理。为了更加详细的描述错误信息,我们添加了错误描述和错误 code。

  1. // 转 json 时的错误类型 
  2. enum JSONMapError: Error{ 
  3.     case emptyKey 
  4.     case notConformProtocol 
  5.  
  6. // 错误描述 
  7. extension JSONMapError: LocalizedError{ 
  8.     var errorDescription: String?{ 
  9.         switch self { 
  10.         case .emptyKey: 
  11.             return "key 为空" 
  12.         case .notConformProtocol: 
  13.            return "没遵守协议" 
  14.         } 
  15.     } 
  16.  
  17. // errorcode 
  18. extension JSONMapError: CustomNSError{ 
  19.     var errorCode: Int
  20.         switch self { 
  21.         case .emptyKey: 
  22.             return 100 
  23.         case .notConformProtocol: 
  24.             return 101 
  25.         } 
  26.     } 

协议实现的代码:

  1. extension CustomJSONProtocol { 
  2.     func toJSON() throws -> Any? { 
  3.          
  4.         //创建 Mirror 类型 
  5.         let mirror = Mirror(reflecting: self) 
  6.         // 如果没有属性,比如一般类型String、Int等,直接返回自己 
  7.         guard !mirror.children.isEmpty else { return self } 
  8.          
  9.         var result: [String:Any] = [:] 
  10.         // 遍历 
  11.         for children in mirror.children { 
  12.             if let value = children.value as? CustomJSONProtocol{ 
  13.                 if let key = children.label { 
  14.                     print(key
  15.                     result[key] = try value.toJSON() 
  16.                 } else { 
  17.                    throw JSONMapError.emptyKey 
  18.                 } 
  19.             } else { 
  20.                   throw JSONMapError.notConformProtocol 
  21.             } 
  22.         } 
  23.          
  24.         return result 
  25.     } 

将用到的类型都遵守协议

  1. //将一般类型都遵从 CustomJSONProtocol 协议 
  2. extension Person: CustomJSONProtocol {} 
  3. extension String: CustomJSONProtocol {} 
  4. extension Int: CustomJSONProtocol {} 
  5. extension Bool: CustomJSONProtocol {} 
  6. extension Double: CustomJSONProtocol {} 
  7. extension Float: CustomJSONProtocol {} 
  8.      
  9. extension Address: CustomJSONProtocol {} 
  10.  
  11. // 数组需要单独处理,要不然就会报错emptyKey 
  12. extension Array: CustomJSONProtocol { 
  13.     func toJSON() throws -> Any? { 
  14.         return self 
  15.     } 
  16.  
  17. //Optionai 需要特别对待,原因是如果直接返回,则会是 .Some: [...] 
  18. extension Optional: CustomJSONProtocol { 
  19.     func toJSON() throws -> Any? { 
  20.         if let x = self { 
  21.             if let value = x as? CustomJSONProtocol { 
  22.                 return try value.toJSON() 
  23.             } 
  24.             throw JSONMapError.notConformProtocol 
  25.         } 
  26.         return nil 
  27.     } 

最后我们打印一下:

  1. do { 
  2.     print(try p.toJSON()!) 
  3. } catch { 
  4.     print(error.localizedDescription) 
  5.     print((error as? JSONMapError)?.errorCode) 

打印结果:

我们看到,对于some这空值,并没有存储到字典中,因为swift中的字典对于空值是删除的意思。

如果想将其转换成json还需修改"[]"为"{}",这个对于数组和对象还不好区分,另外对于json字符串内的一些value也有可能是应一串json还需要添加转义字符等。

所以总的来说,思路是这样的,要想真正的做成通用的转json的方案还需要很多的优化,比如说,我们不可能将所有的基本类型都去遵守一个协议,这时候我们也可以考虑使用泛型去作为方法的参数。

3. Mirror 源码解析

源码版本Swift 5.3.1

在本章节我们将分析Mirror的部分源码,查看其底层实现,最后通过Swift代码使用内存重绑定的形式,仿写一下Mirror,来更好的探索Mirror的原理,理解Mirror的思想。

我们知道Swift是一门静态语言,那么在底层是如何实现的获取对应的属性值的呢?又或者说Swift的反射特性是如何实现的呢?下面我们通过对Mirror底层源码的探索来寻找答案。

▐ 3.1 代码结构

Mirror的实现是由一部分Swift代码加上另一部分C++代码。Swift代码实现在ReflectionMirror.swift文件中,C++代码实现在ReflectionMirror.mm文件中。Swift更适合用在实现更Swift的接口,但是在Swift中不能直接访问C++的类。这里使用了@_silgen_name来实现Swift调用C++中的方法。举个例子:

  1. @_silgen_name("swift_reflectionMirror_count"
  2. internal func _getChildCount<T>(_: T, type: Any.Type) -> Int 

@_silgen_name修饰符会通知Swift编译器将这个函数映射成swift_reflectionMirror_count符号,而不是Swift通常对应到的_getChildCount方法名修饰。需要注意的是,最前面的下划线表示这个修饰是被保留在标准库中的。在C++这边,这个函数是这样的。

  1. // func _getChildCount<T>(_: T, type: Any.Type) -> Int 
  2. SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_API 
  3. intptr_t swift_reflectionMirror_count(OpaqueValue *value, 
  4.                                       const Metadata *type, 
  5.                                       const Metadata *T) { 
  6.   return call(value, T, type, [](ReflectionMirrorImpl *impl) { 
  7.     return impl->count(); 
  8.   }); 

SWIFT_CC(swift)会告诉编译器这个函数使用的是Swift的调用约定,而不是C/C++的,SWIFT_RUNTIME_STDLIB_API标记这个函数,在Swift侧的一部分接口中,而且它还有标记为extern "C"的作用,从而避免C++的方法名修饰,并确保它在Swift侧会有预期的符号。同时C++的参数会去特意匹配在Swift中声明的函数调用。当Swift调用_getChildCount时,C++会用包含Swift值指针的value,包含类型参数type,包含类型响应的泛型的T的函数参数来调用此函数。

简单的说就是使用@_silgen_name("xxx")修饰符修饰的Swift方法会调用括号中的xxx的符号,不管是C++的还是C的都可以。

Mirror的在Swift和C++之间的全部接口由以下函数组成:

  1. @_silgen_name("swift_isClassType"
  2. internal func _isClassType(_: Any.Type) -> Bool 
  3.  
  4. @_silgen_name("swift_getMetadataKind"
  5. internal func _metadataKind(_: Any.Type) -> UInt 
  6.  
  7. @_silgen_name("swift_reflectionMirror_normalizedType"
  8. internal func _getNormalizedType<T>(_: T, type: Any.Type) -> Any.Type 
  9.  
  10. @_silgen_name("swift_reflectionMirror_count"
  11. internal func _getChildCount<T>(_: T, type: Any.Type) -> Int 
  12.  
  13. @_silgen_name("swift_reflectionMirror_recursiveCount"
  14. internal func _getRecursiveChildCount(_: Any.Type) -> Int 
  15.  
  16. @_silgen_name("swift_reflectionMirror_recursiveChildMetadata"
  17. internal func _getChildMetadata( 
  18.   _: Any.Type, 
  19.   indexInt
  20.   outName: UnsafeMutablePointer<UnsafePointer<CChar>?>, 
  21.   outFreeFunc: UnsafeMutablePointer<NameFreeFunc?> 
  22. ) -> Any.Type 
  23.  
  24. @_silgen_name("swift_reflectionMirror_recursiveChildOffset"
  25. internal func _getChildOffset( 
  26.   _: Any.Type, 
  27.   indexInt 
  28. ) -> Int 
  29.  
  30. internal typealias NameFreeFunc = @convention(c) (UnsafePointer<CChar>?) -> Void 
  31.  
  32. @_silgen_name("swift_reflectionMirror_subscript"
  33. internal func _getChild<T>( 
  34.   of: T, 
  35.   type: Any.Type, 
  36.   indexInt
  37.   outName: UnsafeMutablePointer<UnsafePointer<CChar>?>, 
  38.   outFreeFunc: UnsafeMutablePointer<NameFreeFunc?> 
  39. ) -> Any 
  40.  
  41. // Returns 'c' (class), 'e' (enum), 's' (struct), 't' (tuple), or '\0' (none) 
  42. @_silgen_name("swift_reflectionMirror_displayStyle"
  43. internal func _getDisplayStyle<T>(_: T) -> CChar 
  44.  
  45. internal func getChild<T>(of value: T, type: Any.Type, indexInt) -> (label: String?, value: Any) { 
  46.   var nameC: UnsafePointer<CChar>? = nil 
  47.   var freeFunc: NameFreeFunc? = nil 
  48.    
  49.   let value = _getChild(of: value, type: type, indexindex, outName: &nameC, outFreeFunc: &freeFunc) 
  50.    
  51.   let name = nameC.flatMap({ String(validatingUTF8: $0) }) 
  52.   freeFunc?(nameC) 
  53.   return (name, value) 
  54.  
  55. #if _runtime(_ObjC) 
  56. @_silgen_name("swift_reflectionMirror_quickLookObject"
  57. internal func _getQuickLookObject<T>(_: T) -> AnyObject? 
  58.  
  59. @_silgen_name("_swift_stdlib_NSObject_isKindOfClass"
  60. internal func _isImpl(_ object: AnyObject, kindOf: UnsafePointer<CChar>) -> Bool 

▐ 3.2 初始化

在一开始我们简单的介绍了Mirror的部分源码,也由此知道Mirror(reflecting:)初始化方法可以接受任意值,返回一个提供该值子元素集合Children的相关信息的实例。

通过Mirror(reflecting:)源码我们可以知道,其底层调用的是internalReflecting方法。在ReflectionMirror.swift文件的extension Mirror中我们可以找到该方法。其源码如下:

3.2.1 internalReflecting

  1. internal init(internalReflecting subject: Any
  2.              subjectType: Any.Type? = nil, 
  3.              customAncestor: Mirror? = nil) 
  4.  { 
  5.    let subjectType = subjectType ?? _getNormalizedType(subject, type: type(of: subject)) 
  6.     
  7.    let childCount = _getChildCount(subject, type: subjectType) 
  8.    let children = (0 ..< childCount).lazy.map({ 
  9.      getChild(of: subject, type: subjectType, index: $0) 
  10.    }) 
  11.    self.children = Children(children) 
  12.     
  13.    self._makeSuperclassMirror = { 
  14.      guard let subjectClass = subjectType as? AnyClass, 
  15.            let superclass = _getSuperclass(subjectClass) else { 
  16.        return nil 
  17.      } 
  18.       
  19.      // Handle custom ancestors. If we've hit the custom ancestor's subject type, 
  20.      // or descendants are suppressed, return it. Otherwise continue reflecting. 
  21.      if let customAncestor = customAncestor { 
  22.        if superclass == customAncestor.subjectType { 
  23.          return customAncestor 
  24.        } 
  25.        if customAncestor._defaultDescendantRepresentation == .suppressed { 
  26.          return customAncestor 
  27.        } 
  28.      } 
  29.      return Mirror(internalReflecting: subject, 
  30.                    subjectType: superclass, 
  31.                    customAncestor: customAncestor) 
  32.    } 
  33.     
  34.    let rawDisplayStyle = _getDisplayStyle(subject) 
  35.    switch UnicodeScalar(Int(rawDisplayStyle)) { 
  36.    case "c": self.displayStyle = .class 
  37.    case "e": self.displayStyle = .enum 
  38.    case "s": self.displayStyle = .struct 
  39.    case "t": self.displayStyle = .tuple 
  40.    case "\0": self.displayStyle = nil 
  41.    default: preconditionFailure("Unknown raw display style '\(rawDisplayStyle)'"
  42.    } 
  43.     
  44.    self.subjectType = subjectType 
  45.    self._defaultDescendantRepresentation = .generated 
  46.  } 

源码分析:

  • 首先是获取subjectType,如果传入的有值就使用传入的值,否则就通过_getNormalizedType函数去获取
  • 接下来就是通过_getChildCount获取childCount
  • 接下来是children,注意这里是懒加载的
  • 紧接着是SuperclassMirror,这里使用的是一个闭包的形式
  • 最后会获取并解析显示的样式,并设置Mirror剩下的属性。

3.2.2 _getNormalizedType

下面我们就来看看_getNormalizedType函数内部的实现。根据上面的分析我们知道实际调用是swift_reflectionMirror_normalizedType。在ReflectionMirror.mm文件中我们可以看到其源码:

  1. // func _getNormalizedType<T>(_: T, type: Any.Type) -> Any.Type 
  2. SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_API 
  3. const Metadata *swift_reflectionMirror_normalizedType(OpaqueValue *value, 
  4.                                                       const Metadata *type, 
  5.                                                       const Metadata *T) { 
  6.   return call(value, T, type, [](ReflectionMirrorImpl *impl) { return impl->type; }); 

3.2.3 call函数

我们可以看到这里调用了一个call函数,最后返回的是impl的type。首先我们看看这call函数:

  1. template<typename F> 
  2. auto call(OpaqueValue *passedValue, const Metadata *T, const Metadata *passedType, 
  3.           const F &f) -> decltype(f(nullptr)) 
  4.   const Metadata *type; 
  5.   OpaqueValue *value; 
  6.   std::tie(type, value) = unwrapExistential(T, passedValue); 
  7.    
  8.   if (passedType != nullptr) { 
  9.     type = passedType; 
  10.   } 
  11.    
  12.   auto call = [&](ReflectionMirrorImpl *impl) { 
  13.     impl->type = type; 
  14.     impl->value = value; 
  15.     auto result = f(impl); 
  16.     return result; 
  17.   }; 
  18.    
  19.   auto callClass = [&] { 
  20.     if (passedType == nullptr) { 
  21.       // Get the runtime type of the object. 
  22.       const void *obj = *reinterpret_cast<const void * const *>(value); 
  23.       auto isa = _swift_getClass(obj); 
  24.  
  25.       // Look through artificial subclasses. 
  26.       while (isa->isTypeMetadata() && isa->isArtificialSubclass()) { 
  27.         isa = isa->Superclass; 
  28.       } 
  29.       passedType = isa; 
  30.     } 
  31.  
  32.   #if SWIFT_OBJC_INTEROP 
  33.     // If this is a pure ObjC class, reflect it using ObjC's runtime facilities. 
  34.     // ForeignClass (e.g. CF classes) manifests as a NULL class object. 
  35.     auto *classObject = passedType->getClassObject(); 
  36.     if (classObject == nullptr || !classObject->isTypeMetadata()) { 
  37.       ObjCClassImpl impl; 
  38.       return call(&impl); 
  39.     } 
  40.   #endif 
  41.  
  42.     // Otherwise, use the native Swift facilities. 
  43.     ClassImpl impl; 
  44.     return call(&impl); 
  45.   }; 
  46.    
  47.   switch (type->getKind()) { 
  48.     case MetadataKind::Tuple: { 
  49.       TupleImpl impl; 
  50.       return call(&impl); 
  51.     } 
  52.  
  53.     case MetadataKind::Struct: { 
  54.       StructImpl impl; 
  55.       return call(&impl); 
  56.     } 
  57.      
  58.  
  59.     case MetadataKind::Enum: 
  60.     case MetadataKind::Optional: { 
  61.       EnumImpl impl; 
  62.       return call(&impl); 
  63.     } 
  64.        
  65.     case MetadataKind::ObjCClassWrapper: 
  66.     case MetadataKind::ForeignClass: 
  67.     case MetadataKind::Class: { 
  68.       return callClass(); 
  69.     } 
  70.  
  71.     case MetadataKind::Metatype: 
  72.     case MetadataKind::ExistentialMetatype: { 
  73.       MetatypeImpl impl; 
  74.       return call(&impl); 
  75.     } 
  76.  
  77.     case MetadataKind::Opaque: { 
  78. #if SWIFT_OBJC_INTEROP 
  79.       // If this is the AnyObject type, use the dynamic type of the 
  80.       // object reference. 
  81.       if (type == &METADATA_SYM(BO).base) { 
  82.         return callClass(); 
  83.       } 
  84. #endif 
  85.       // If this is the Builtin.NativeObject type, and the heap object is a 
  86.       // class instance, use the dynamic type of the object reference. 
  87.       if (type == &METADATA_SYM(Bo).base) { 
  88.         const HeapObject *obj 
  89.           = *reinterpret_cast<const HeapObject * const*>(value); 
  90.         if (obj->metadata->getKind() == MetadataKind::Class) { 
  91.           return callClass(); 
  92.         } 
  93.       } 
  94.       LLVM_FALLTHROUGH; 
  95.     } 
  96.  
  97.     /// TODO: Implement specialized mirror witnesses for all kinds. 
  98.     default
  99.       break; 
  100.  
  101.     // Types can't have these kinds. 
  102.     case MetadataKind::HeapLocalVariable: 
  103.     case MetadataKind::HeapGenericLocalVariable: 
  104.     case MetadataKind::ErrorObject: 
  105.       swift::crash("Swift mirror lookup failure"); 
  106.     } 
  107.  
  108.     // If we have an unknown kind of type, or a type without special handling, 
  109.     // treat it as opaque. 
  110.     OpaqueImpl impl; 
  111.     return call(&impl); 

乍一看这个call函数代码相对有点多,其实主要就是一个大型的switch声明,和一些对特殊情况的处理,这里重要的就是,它会用一个ReflectionMirrorImpl的子类实例去结束调用f,然后会调用这个实例上的方法去让真正的工作完成,这也就是为什么在swift_reflectionMirror_normalizedType函数中最后会return impl->type;感兴趣的可以通过源码去调试一下,这里我也调试了,没什么指的说的,这就就不写调试过程了,下面我们就来看看ReflectionMirrorImpl。

3.2.4 ReflectionMirrorImpl

ReflectionMirrorImpl有以下6个子类:

  • TupleImpl 元组的反射
  • StructImpl 结构体的反射
  • EnumImpl 枚举的反射
  • ClassImpl 类的反射
  • MetatypeImpl 元数据的反射
  • OpaqueImpl 不透明类型的反射

ReflectionMirrorImpl 源码:

  1. // Abstract base class for reflection implementations. 
  2. struct ReflectionMirrorImpl { 
  3.   const Metadata *type; 
  4.   OpaqueValue *value; 
  5.    
  6.   virtual char displayStyle() = 0; 
  7.   virtual intptr_t count() = 0; 
  8.   virtual intptr_t childOffset(intptr_t index) = 0; 
  9.   virtual const FieldType childMetadata(intptr_t index
  10.                                         const char **outName, 
  11.                                         void (**outFreeFunc)(const char *)) = 0; 
  12.   virtual AnyReturn subscript(intptr_t index, const char **outName, 
  13.                               void (**outFreeFunc)(const char *)) = 0; 
  14.   virtual const char *enumCaseName() { return nullptr; } 
  15.  
  16. #if SWIFT_OBJC_INTEROP 
  17.   virtual id quickLookObject() { return nil; } 
  18. #endif 
  19.    
  20.   // For class types, traverse through superclasses when providing field 
  21.   // information. The base implementations call through to their local-only 
  22.   // counterparts. 
  23.   virtual intptr_t recursiveCount() { 
  24.     return count(); 
  25.   } 
  26.   virtual intptr_t recursiveChildOffset(intptr_t index) { 
  27.     return childOffset(index); 
  28.   } 
  29.   virtual const FieldType recursiveChildMetadata(intptr_t index
  30.                                                  const char **outName, 
  31.                                                  void (**outFreeFunc)(const char *)) 
  32.     return childMetadata(index, outName, outFreeFunc); 
  33.   } 
  34.  
  35.   virtual ~ReflectionMirrorImpl() {} 
  36. }; 

ReflectionMirrorImpl源码不多,但是我们可以看到type以及count等都在其中。下面我们以结构体为例,看看其子类的源码。

3.2.5 结构体的反射

  1. // Implementation for structs. 
  2. struct StructImpl : ReflectionMirrorImpl { 
  3.   bool isReflectable() { 
  4.     const auto *Struct = static_cast<const StructMetadata *>(type); 
  5.     const auto &Description = Struct->getDescription(); 
  6.     return Description->isReflectable(); 
  7.   } 
  8.  
  9.   char displayStyle() { 
  10.     return 's'
  11.   } 
  12.    
  13.   intptr_t count() { 
  14.     if (!isReflectable()) { 
  15.       return 0; 
  16.     } 
  17.  
  18.     auto *Struct = static_cast<const StructMetadata *>(type); 
  19.     return Struct->getDescription()->NumFields; 
  20.   } 
  21.  
  22.   intptr_t childOffset(intptr_t i) { 
  23.     auto *Struct = static_cast<const StructMetadata *>(type); 
  24.  
  25.     if (i < 0 || (size_t)i > Struct->getDescription()->NumFields) 
  26.       swift::crash("Swift mirror subscript bounds check failure"); 
  27.  
  28.     // Load the offset from its respective vector. 
  29.     return Struct->getFieldOffsets()[i]; 
  30.   } 
  31.  
  32.   const FieldType childMetadata(intptr_t i, const char **outName, 
  33.                                 void (**outFreeFunc)(const char *)) { 
  34.     StringRef name
  35.     FieldType fieldInfo; 
  36.     std::tie(name, fieldInfo) = getFieldAt(type, i); 
  37.     assert(!fieldInfo.isIndirect() && "indirect struct fields not implemented"); 
  38.      
  39.     *outName = name.data(); 
  40.     *outFreeFunc = nullptr; 
  41.      
  42.     return fieldInfo; 
  43.   } 
  44.  
  45.   AnyReturn subscript(intptr_t i, const char **outName, 
  46.                       void (**outFreeFunc)(const char *)) { 
  47.     auto fieldInfo = childMetadata(i, outName, outFreeFunc); 
  48.  
  49.     auto *bytes = reinterpret_cast<char*>(value); 
  50.     auto fieldOffset = childOffset(i); 
  51.     auto *fieldData = reinterpret_cast<OpaqueValue *>(bytes + fieldOffset); 
  52.  
  53.     return copyFieldContents(fieldData, fieldInfo); 
  54.   } 
  55. }; 
  • 首先一个判断是否支持反射的方法,最中是访问的Description->isReflectable()
  • 这里使用‘s’来显式的表明这是一个结构体
  • 然后是获取属性个数
  • 紧接着是获取每个属性的偏移值
  • 然后获取了FieldType内部还可以获取到属性的名称。
  • 最后subscript方法可以获取到属性名称和属性偏移的指针,也就是属性值。

▐ 3.3 Description

在此处我们看到很多关于Description的代码,看来这个Description存储着很多信息,在获取Description的时候是从StructMetadata通过getDescription()方法获取到。所以这些信息基本确定是从MetaData中获取到的。StructMetadata是TargetStructMetadata的别名,我们以此为例。

3.3.1 TargetStructMetadata

在TargetStructMetadata我们可以看到如下代码:

  1. const TargetStructDescriptor<Runtime> *getDescription() const { 
  2.     return llvm::cast<TargetStructDescriptor<Runtime>>(this->Description); 

说明此处会返回一个TargetStructDescriptor类型的Description,但是在这里并没有找到这个属性,可能在父类中,我们可以看到TargetStructMetadata继承自TargetValueMetadata。

3.3.2 TargetValueMetadata

在这里我们可以看到如下代码:

  1. /// An out-of-line description of the type. 
  2. TargetSignedPointer<Runtime, const TargetValueTypeDescriptor<Runtime> * __ptrauth_swift_type_descriptor> Description; 
  3.    
  4. getDescription() const { 
  5.     return Description; 

这里我们便找到了:

  • Description属性,它的类型是TargetValueTypeDescriptor,应该是TargetStructDescriptor的父类。
  • getDescription()方法,在TargetStructMetadata是重写的这个方法

3.3.3 TargetStructDescriptor

跳转到TargetStructDescriptor中后,我们可以看到:

  • TargetValueTypeDescriptor果然是它的父类
  • 在其源码中我们还可以发现两个属性,分别是NumFields和FieldOffsetVectorOffset源码如下:
  1. /// The number of stored properties in the struct. 
  2.   /// If there is a field offset vector, this is its length. 
  3.   uint32_t NumFields; 
  4.   /// The offset of the field offset vector for this struct's stored 
  5.   /// properties in its metadata, if any. 0 means there is no field offset 
  6.   /// vector. 
  7.   uint32_t FieldOffsetVectorOffset; 
  • 其中NumFields主要表示结构体中属性的个数,如果只有一个字段偏移量则表示偏移量的长度
  • FieldOffsetVectorOffset表示这个结构体元数据中存储的属性的字段偏移向量的偏移量,如果是0则表示没有

3.3.4 TargetValueTypeDescriptor

源码如下,很少:

  1. template <typename Runtime> 
  2. class TargetValueTypeDescriptor 
  3.     : public TargetTypeContextDescriptor<Runtime> { 
  4. public
  5.   static bool classof(const TargetContextDescriptor<Runtime> *cd) { 
  6.     return cd->getKind() == ContextDescriptorKind::Struct || 
  7.            cd->getKind() == ContextDescriptorKind::Enum; 
  8.   } 
  9. }; 

在这里我们并没有找到太多有用的信息,我们继续向父类寻找,其继承自TargetTypeContextDescriptor

3.3.5 TargetTypeContextDescriptor

部分源码:

  1. template <typename Runtime> 
  2. class TargetTypeContextDescriptor 
  3.     : public TargetContextDescriptor<Runtime> { 
  4. public
  5.   /// The name of the type. 
  6.   TargetRelativeDirectPointer<Runtime, const char, /*nullable*/ falseName
  7.  
  8.   /// A pointer to the metadata access function for this type. 
  9.   /// 
  10.   /// The function type here is a stand-in. You should use getAccessFunction() 
  11.   /// to wrap the function pointer in an accessor that uses the proper calling 
  12.   /// convention for a given number of arguments. 
  13.   TargetRelativeDirectPointer<Runtime, MetadataResponse(...), 
  14.                               /*Nullable*/ true> AccessFunctionPtr; 
  15.    
  16.   /// A pointer to the field descriptor for the type, if any
  17.   TargetRelativeDirectPointer<Runtime, const reflection::FieldDescriptor, 
  18.                               /*nullable*/ true> Fields; 

我们可以看到:

该类继承自TargetContextDescriptor

有Name、AccessFunctionPtr、Fields三个属性

  • 其中name就是类型的名称
  • AccessFunctionPtr是该类型元数据访问函数的指针
  • Fields是一个指向该类型的字段描述符的指针

3.3.6 TargetContextDescriptor

接下来我们再看看TargetTypeContextDescriptor的父类中还有什么有用的信息。部分源码如下:

  1. /// Base class for all context descriptors. 
  2. template<typename Runtime> 
  3. struct TargetContextDescriptor { 
  4.   /// Flags describing the context, including its kind and format version. 
  5.   ContextDescriptorFlags Flags; 
  6.    
  7.   /// The parent context, or null if this is a top-level context. 
  8.   TargetRelativeContextPointer<Runtime> Parent; 

这里我们可以看到:

这就是descriptors的基类

有两个属性,分别是Flags和Parent

  • 其中Flags是描述上下文的标志,包括它的种类和格式版本。
  • Parent是记录父类上下文的,如果是顶级则为null

3.3.7 小结

至此我们对结构体Description的层级结构基本就理清楚了,现总结如下:

从上图我们可以看到,对于一个结构体的Description来说,继承链上一共四个类,7个属性。下面我们就对这些属性作进一步的分析

▐ 3.4 Description中的属性

3.4.1 Flags

Flags的类型是ContextDescriptorFlags,我们点击跳转进去,我们可以看到:

  1. /// Common flags stored in the first 32-bit word of any context descriptor. 
  2. struct ContextDescriptorFlags { 
  3. private: 
  4.   uint32_t Value; 
  5.  
  6.   explicit constexpr ContextDescriptorFlags(uint32_t Value) 
  7.     : Value(Value) {} 
  8. public
  9.   constexpr ContextDescriptorFlags() : Value(0) {} 
  10.   constexpr ContextDescriptorFlags(ContextDescriptorKind kind, 
  11.                                    bool isGeneric, 
  12.                                    bool isUnique, 
  13.                                    uint8_t version, 
  14.                                    uint16_t kindSpecificFlags) 
  15.     : ContextDescriptorFlags(ContextDescriptorFlags() 
  16.                                .withKind(kind) 
  17.                                .withGeneric(isGeneric) 
  18.                                .withUnique(isUnique) 
  19.                                .withVersion(version) 
  20.                                .withKindSpecificFlags(kindSpecificFlags)) 
  21.   {} 
  22.    
  23.   ...... 

从以上的代码中我们可以看到这个FLags实际是个uint32_t的值,按位存储着kind、isGeneric、isUnique、version等信息。

3.4.2 Parent

Parent的类型是TargetRelativeContextPointer,我们看看TargetRelativeContextPointer,点击跳转过去:

  1. using TargetRelativeContextPointer = 
  2.   RelativeIndirectablePointer<const Context<Runtime>, 
  3.                               /*nullable*/ true, int32_t, 
  4.                               TargetSignedContextPointer<Runtime, Context>>; 

我们可以看到TargetRelativeContextPointer是取自RelativeIndirectablePointer的别名,继续点击进行查看:

  1. /// A relative reference to an object stored in memory. The reference may be 
  2. /// direct or indirect, and uses the low bit of the (assumed at least 
  3. /// 2-byte-aligned) pointer to differentiate. 
  4. template<typename ValueTy, bool Nullable = false, typename Offset = int32_t, typename IndirectType = const ValueTy *> 
  5. class RelativeIndirectablePointer { 
  6.  
  7.     /// The relative offset of the pointer's memory from the `this` pointer. 
  8.     /// If the low bit is clear, this is a direct reference; otherwise, it is 
  9.     /// an indirect reference. 
  10.     Offset RelativeOffsetPlusIndirect; 
  11.    
  12.         const ValueTy *get() const & { 
  13.         static_assert(alignof(ValueTy) >= 2 && alignof(Offset) >= 2, 
  14.                       "alignment of value and offset must be at least 2 to " 
  15.                       "make room for indirectable flag"); 
  16.        
  17.         // Check for null
  18.         if (Nullable && RelativeOffsetPlusIndirect == 0) 
  19.           return nullptr; 
  20.          
  21.         Offset offsetPlusIndirect = RelativeOffsetPlusIndirect; 
  22.         uintptr_t address = detail::applyRelativeOffset(this, 
  23.                                                         offsetPlusIndirect & ~1); 
  24.      
  25.         // If the low bit is setthen this is an indirect address. Otherwise, 
  26.         // it's direct. 
  27.         if (offsetPlusIndirect & 1) { 
  28.           return *reinterpret_cast<IndirectType const *>(address); 
  29.         } else { 
  30.           return reinterpret_cast<const ValueTy *>(address); 
  31.         }    
  32.     } 

根据注释我们就可以轻松的知道这个类的主要作用是存储在内存中的对象的相对引用。这个意思在后面也有相关的解释就是在内存中引用可以是直接的也可以是间接的,直接的就是存储的绝对地址(也不一定,还有ASLR等),直接访问这个地址就可以拿到对应的数据,而这里的相对引用就是间接的,这里面通过RelativeOffsetPlusIndirect属性存储相对的地址偏移量,在通过get()函数获取,在get()函数中,会调用applyRelativeOffset函数,进行地址的偏移,applyRelativeOffset源码:

  1. /// Apply a relative offset to a base pointer. The offset is applied to the base 
  2. /// pointer using sign-extended, wrapping arithmetic. 
  3. template<typename BasePtrTy, typename Offset> 
  4. static inline uintptr_t applyRelativeOffset(BasePtrTy *basePtr, Offset offset) { 
  5.   static_assert(std::is_integral<Offset>::value && 
  6.                 std::is_signed<Offset>::value, 
  7.                 "offset type should be signed integer"); 
  8.  
  9.   auto base = reinterpret_cast<uintptr_t>(basePtr); 
  10.   // We want to do wrapping arithmetic, but with a sign-extended 
  11.   // offset. To do this in C, we need to do signed promotion to get 
  12.   // the sign extension, but we need to perform arithmetic on unsigned values
  13.   // since signed overflow is undefined behavior. 
  14.   auto extendOffset = (uintptr_t)(intptr_t)offset; 
  15.   return base + extendOffset; 

最后返回的时候我们可以看到base + extendOffset;基地址加上偏移的值,最后得到真实的地址。

3.4.2 name

name的类型是TargetRelativeDirectPointer

  1. template <typename Runtime, typename Pointee, bool Nullable = true
  2. using TargetRelativeDirectPointer 
  3.   = typename Runtime::template RelativeDirectPointer<Pointee, Nullable>; 

这里依旧是取别名,继续跳转到RelativeDirectPointer,这里有两个选择,我们选择相对引用那个(通过注释区别)。源码如下:

  1. /// A direct relative reference to an object that is not a function pointer. 
  2. template <typename T, bool Nullable, typename Offset> 
  3. class RelativeDirectPointer<T, Nullable, Offset, 
  4.     typename std::enable_if<!std::is_function<T>::value>::type> 
  5.     : private RelativeDirectPointerImpl<T, Nullable, Offset> 
  6.   using super = RelativeDirectPointerImpl<T, Nullable, Offset>; 
  7. public
  8.   using super::get; 
  9.   using super::super; 
  10.    
  11.   RelativeDirectPointer &operator=(T *absolute) & { 
  12.     super::operator=(absolute); 
  13.     return *this; 
  14.   } 
  15.  
  16.   operator typename super::PointerTy() const & { 
  17.     return this->get(); 
  18.   } 
  19.  
  20.   const typename super::ValueTy *operator->() const & { 
  21.     return this->get(); 
  22.   } 
  23.  
  24.   using super::isNull
  25. }; 

在源码中我们可以看到很多关于supper的东西,有两处都是通过get()方法返回的,分别是PointerTy和ValueTy,下面我们就来到父类方法中看看。父类是RelativeDirectPointerImpl,其部分源码如下:

  1. /// A relative reference to a function, intended to reference private metadata 
  2. /// functions for the current executable or dynamic library image from 
  3. /// position-independent constant data. 
  4. template<typename T, bool Nullable, typename Offset> 
  5. class RelativeDirectPointerImpl { 
  6. private: 
  7.   /// The relative offset of the function's entry point from *this. 
  8.   Offset RelativeOffset; 
  9.    
  10. public
  11.   using ValueTy = T; 
  12.   using PointerTy = T*; 
  13.    
  14.   PointerTy get() const & { 
  15.     // Check for null
  16.     if (Nullable && RelativeOffset == 0) 
  17.       return nullptr; 
  18.      
  19.     // The value is addressed relative to `this`. 
  20.     uintptr_t absolute = detail::applyRelativeOffset(this, RelativeOffset); 
  21.     return reinterpret_cast<PointerTy>(absolute); 
  22.   } 

这里同样有一个Offset类型RelativeOffset,以及get()方法,同样get()方法也会调用applyRelativeOffset函数进行地址的相加,关于applyRelativeOffset方法在介绍Parent的时候提到过。

这里面多了ValueTy和PointerTy,ValueTy是传入泛型的值,PointerTy是其指针。

name中还有个const char,这里是直接用const char类型存储的类型的名称。

3.4.4 AccessFunctionPtr

AccessFunctionPtr的类型是TargetRelativeDirectPointer

跟name一样的使用偏移指针TargetRelativeDirectPointer,只不过是const char替换成了MetadataResponse(...),点击MetadataResponse跳转后我们可以看到如下代码:

  1. MetadataResponse() : Metadata(nullptr) {} 
  2.  
  3. /// A metadata response that might not be dynamically complete. 
  4. explicit MetadataResponse(llvm::Value *metadata, llvm::Value *state, 
  5.                         MetadataState staticLowerBoundState) 
  6.   : Metadata(metadata), DynamicState(state), 
  7.     StaticState(staticLowerBoundState) { 
  8.     assert(metadata && "must be valid"); 

所以这里只是一个Metadata的指针。

3.4.5 Fields

Fields的类型是TargetRelativeDirectPointer

TargetRelativeDirectPointer就不多说了,这里看看FieldDescriptor点击跳转到其源码处,部分源码如下:

  1. // Field descriptors contain a collection of field records for a single 
  2. // class, struct or enum declaration. 
  3. class FieldDescriptor { 
  4.   const FieldRecord *getFieldRecordBuffer() const { 
  5.     return reinterpret_cast<const FieldRecord *>(this + 1); 
  6.   } 
  7.  
  8. public
  9.   const RelativeDirectPointer<const char> MangledTypeName; 
  10.   const RelativeDirectPointer<const char> Superclass; 
  11.  
  12.   FieldDescriptor() = delete
  13.  
  14.   const FieldDescriptorKind Kind; 
  15.   const uint16_t FieldRecordSize; 
  16.   const uint32_t NumFields; 
  17.    

这里有5个属性:

1. MangledTypeName

2. Superclass

3. kind

4. FieldRecordSize

5. NumFields

关于getFieldRecordBuffer函数的返回值FieldRecord源码如下:

  1. class FieldRecord { 
  2.   const FieldRecordFlags Flags; 
  3.  
  4. public
  5.   const RelativeDirectPointer<const char> MangledTypeName; 
  6.   const RelativeDirectPointer<const char> FieldName; 
  7. .....   

FieldRecord主要是封装了一些属性,用于存储这些值。

3.4.6 NumFields

NumFields的类型是uint32_t这就没什么好说的了,一个整形存储属性个数

3.4.7 FieldOffsetVectorOffset

FieldOffsetVectorOffset也是个uint32_t的整形,存储偏移量。

▐ 3.5 Mirror取值

对于Description分析基本很透彻了,那么我们就回到最初的位置,看看Mirror都是怎样从Description取出相应的值的。

3.5.1 type

首先我们看看type是怎么取的:

首先是调用swift_reflectionMirror_normalizedType函数

  1. // func _getNormalizedType<T>(_: T, type: Any.Type) -> Any.Type 
  2. SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_API 
  3. const Metadata *swift_reflectionMirror_normalizedType(OpaqueValue *value, 
  4.                                                       const Metadata *type, 
  5.                                                       const Metadata *T) { 
  6.   return call(value, T, type, [](ReflectionMirrorImpl *impl) { return impl->type; }); 

比如说这是个结构体,此时的impl就是个StructImpl类型,所以这里的type是StructImpl父类ReflectionMirrorImpl的属性type。

3.5.2 count

关于count的获取首先是调用swift_reflectionMirror_count函数

  1. // func _getChildCount<T>(_: T, type: Any.Type) -> Int 
  2. SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_API 
  3. intptr_t swift_reflectionMirror_count(OpaqueValue *value, 
  4.                                       const Metadata *type, 
  5.                                       const Metadata *T) { 
  6.   return call(value, T, type, [](ReflectionMirrorImpl *impl) { 
  7.     return impl->count(); 
  8.   }); 

同样还以结构体为例,此时的impl为StructImpl,内部的count()函数:

  1. intptr_t count() { 
  2.     if (!isReflectable()) { 
  3.       return 0; 
  4.     } 
  5.  
  6.     auto *Struct = static_cast<const StructMetadata *>(type); 
  7.     return Struct->getDescription()->NumFields; 

这里的Struct就是个TargetStructMetadata类型,通过getDescription()函数获取到一个TargetStructDescriptor类型的Description,然后取NumFields的值就是我们要的count。

3.5.3 属性名和属性值

我们知道在Mirror中通过其初始化方法返回一个提供该值子元素的AnyCollection类型的children集合,Child是一个元组(label: String?, value: Any),label是一个可选类型的属性名,value是属性值。

在分析internalReflecting函数的时候,我们说children是懒加载的,而加载的时候会调用getChild方法,getChild方法源码入下:

  1. internal func getChild<T>(of value: T, type: Any.Type, indexInt) -> (label: String?, value: Any) { 
  2.   var nameC: UnsafePointer<CChar>? = nil 
  3.   var freeFunc: NameFreeFunc? = nil 
  4.    
  5.   let value = _getChild(of: value, type: type, indexindex, outName: &nameC, outFreeFunc: &freeFunc) 
  6.    
  7.   let name = nameC.flatMap({ String(validatingUTF8: $0) }) 
  8.   freeFunc?(nameC) 
  9.   return (name, value) 

在getChild方法中还会调用_getChild方法,源码如下:

  1. @_silgen_name("swift_reflectionMirror_subscript"
  2. internal func _getChild<T>( 
  3.   of: T, 
  4.   type: Any.Type, 
  5.   indexInt
  6.   outName: UnsafeMutablePointer<UnsafePointer<CChar>?>, 
  7.   outFreeFunc: UnsafeMutablePointer<NameFreeFunc?> 
  8. ) -> Any 

_getChild方法同样是使用@_silgen_name修饰符最终调用的C++中的swift_reflectionMirror_subscript函数。

  1. // We intentionally use a non-POD return type with this entry point to give 
  2. // it an indirect return ABI for compatibility with Swift. 
  3. #pragma clang diagnostic push 
  4. #pragma clang diagnostic ignored "-Wreturn-type-c-linkage" 
  5. // func _getChild<T>( 
  6. //   of: T, 
  7. //   type: Any.Type, 
  8. //   indexInt
  9. //   outName: UnsafeMutablePointer<UnsafePointer<CChar>?>, 
  10. //   outFreeFunc: UnsafeMutablePointer<NameFreeFunc?> 
  11. // ) -> Any 
  12. SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_API 
  13. AnyReturn swift_reflectionMirror_subscript(OpaqueValue *value, const Metadata *type, 
  14.                                            intptr_t index
  15.                                            const char **outName, 
  16.                                            void (**outFreeFunc)(const char *), 
  17.                                            const Metadata *T) { 
  18.   return call(value, T, type, [&](ReflectionMirrorImpl *impl) { 
  19.     return impl->subscript(index, outName, outFreeFunc); 
  20.   }); 
  21. #pragma clang diagnostic pop 

这里我们可以看到是调用了impl的subscript函数,同样以结构体为例,我们在StructImpl中找到该函数,源码如下:

  1. AnyReturn subscript(intptr_t i, const char **outName, 
  2.                       void (**outFreeFunc)(const char *)) { 
  3.     auto fieldInfo = childMetadata(i, outName, outFreeFunc); 
  4.  
  5.     auto *bytes = reinterpret_cast<char*>(value); 
  6.     auto fieldOffset = childOffset(i); 
  7.     auto *fieldData = reinterpret_cast<OpaqueValue *>(bytes + fieldOffset); 
  8.  
  9.     return copyFieldContents(fieldData, fieldInfo); 
  10.   } 

通过subscript函数我们可以看到这里面还会调用childMetadata获取到fieldInfo,其实这里就是获取type,也就是属性名,通过childOffset函数和index获取到对于的偏移量,最后根据内存偏移去到属性值。

childMetadata源码:

  1. const FieldType childMetadata(intptr_t i, const char **outName, 
  2.                                 void (**outFreeFunc)(const char *)) { 
  3.     StringRef name
  4.     FieldType fieldInfo; 
  5.     std::tie(name, fieldInfo) = getFieldAt(type, i); 
  6.     assert(!fieldInfo.isIndirect() && "indirect struct fields not implemented"); 
  7.      
  8.     *outName = name.data(); 
  9.     *outFreeFunc = nullptr; 
  10.      
  11.     return fieldInfo; 
  12.   } 

这里面的关键点是调用调用getFieldAt函数获取属性名称,

getFieldAt源码:

  1. static std::pair<StringRef /*name*/, FieldType /*fieldInfo*/> 
  2. getFieldAt(const Metadata *base, unsigned index) { 
  3.   using namespace reflection; 
  4.    
  5.   // If we failed to find the field descriptor metadata for the type, fall 
  6.   // back to returning an empty tuple as a standin. 
  7.   auto failedToFindMetadata = [&]() -> std::pair<StringRef, FieldType> { 
  8.     auto typeName = swift_getTypeName(base, /*qualified*/ true); 
  9.     missing_reflection_metadata_warning( 
  10.       "warning: the Swift runtime found no field metadata for " 
  11.       "type '%*s' that claims to be reflectable. Its fields will show up as " 
  12.       "'unknown' in Mirrors\n"
  13.       (int)typeName.length, typeName.data); 
  14.     return {"unknown", FieldType(&METADATA_SYM(EMPTY_TUPLE_MANGLING))}; 
  15.   }; 
  16.  
  17.   auto *baseDesc = base->getTypeContextDescriptor(); 
  18.   if (!baseDesc) 
  19.     return failedToFindMetadata(); 
  20.  
  21.   auto *fields = baseDesc->Fields.get(); 
  22.   if (!fields) 
  23.     return failedToFindMetadata(); 
  24.    
  25.   auto &field = fields->getFields()[index]; 
  26.   // Bounds are always valid as the offset is constant. 
  27.   auto name = field.getFieldName(); 
  28.  
  29.   // Enum cases don't always have types. 
  30.   if (!field.hasMangledTypeName()) 
  31.     return {name, FieldType::untypedEnumCase(field.isIndirectCase())}; 
  32.  
  33.   auto typeName = field.getMangledTypeName(); 
  34.  
  35.   SubstGenericParametersFromMetadata substitutions(base); 
  36.   auto typeInfo = swift_getTypeByMangledName(MetadataState::Complete, 
  37.    typeName, 
  38.    substitutions.getGenericArgs(), 
  39.    [&substitutions](unsigned depth, unsigned index) { 
  40.      return substitutions.getMetadata(depth, index); 
  41.    }, 
  42.    [&substitutions](const Metadata *type, unsigned index) { 
  43.      return substitutions.getWitnessTable(type, index); 
  44.    }); 
  45.  
  46.   // If demangling the type failed, pretend it's an empty type instead with 
  47.   // a log message. 
  48.   if (!typeInfo.getMetadata()) { 
  49.     typeInfo = TypeInfo({&METADATA_SYM(EMPTY_TUPLE_MANGLING), 
  50.                          MetadataState::Complete}, {}); 
  51.     missing_reflection_metadata_warning( 
  52.       "warning: the Swift runtime was unable to demangle the type " 
  53.       "of field '%*s'. the mangled type name is '%*s'. this field will " 
  54.       "show up as an empty tuple in Mirrors\n"
  55.       (int)name.size(), name.data(), 
  56.       (int)typeName.size(), typeName.data()); 
  57.   } 
  58.  
  59.   auto fieldType = FieldType(typeInfo.getMetadata()); 
  60.   fieldType.setIndirect(field.isIndirectCase()); 
  61.   fieldType.setReferenceOwnership(typeInfo.getReferenceOwnership()); 
  62.   return {name, fieldType}; 

我们可以看到在上面这个方法中:

  • 首先通过getTypeContextDescriptor获取baseDesc,也就是我们说的Description
  • 然后通过Fields.get()获取到fields
  • 接着通过getFields()[index]或取对应的field
  • 最后通过getFieldName()函数获取到属性名称
  • getTypeContextDescriptor函数在struct TargetMetadata中,
  • 通过这个函数获取到一个TargetStructDescriptor,它的父类的父类TargetTypeContextDescriptor中的Fields属性
  • Fields属性的类型TargetRelativeDirectPointer中有get方法
  • 实际中使用的FieldDescriptor类中getFieldRecordBuffer方法返回的FieldRecord中的getFieldName函数

getFields 源码:

  1. const_iterator begin() const { 
  2.   auto Begin = getFieldRecordBuffer(); 
  3.   auto End = Begin + NumFields; 
  4.   return const_iterator { BeginEnd }; 
  5.  
  6. const_iterator end() const { 
  7.   auto Begin = getFieldRecordBuffer(); 
  8.   auto End = Begin + NumFields; 
  9.   return const_iterator { EndEnd }; 
  10.  
  11. llvm::ArrayRef<FieldRecord> getFields() const { 
  12.   return {getFieldRecordBuffer(), NumFields}; 

关于getFields我们可以看到这是一块连续的空间,在begin和end中:

  • begin就是getFieldRecordBuffer
  • getFieldRecordBuffer就是Begin + NumFields
  • 所以这就是一块连续内存的访问

childOffset 源码:

分析完了属性名的获取,我们来看看偏移量的获取

  1. intptr_t childOffset(intptr_t i) { 
  2.     auto *Struct = static_cast<const StructMetadata *>(type); 
  3.  
  4.     if (i < 0 || (size_t)i > Struct->getDescription()->NumFields) 
  5.       swift::crash("Swift mirror subscript bounds check failure"); 
  6.  
  7.     // Load the offset from its respective vector. 
  8.     return Struct->getFieldOffsets()[i]; 
  9.   } 

这里面是调用TargetStructMetadata中的getFieldOffsets函数源码如下:

  1. /// Get a pointer to the field offset vector, if present, or null
  2.   const uint32_t *getFieldOffsets() const { 
  3.     auto offset = getDescription()->FieldOffsetVectorOffset; 
  4.     if (offset == 0) 
  5.       return nullptr; 
  6.     auto asWords = reinterpret_cast<const void * const*>(this); 
  7.     return reinterpret_cast<const uint32_t *>(asWords + offset); 
  8.   } 

我们可以看到这里统一是通过获取Description中的属性,这里使用的属性是FieldOffsetVectorOffset。

获取到偏移值后通过内存偏移即可获取到属性值。

▐ 3.6 小结

至此我们对Mirror的原理基本探索完毕了,现在总结一下:

  1. Mirror通过初始化方法返回一会Mirror实例
  2. 这个实例对象根据传入对象的类型去对应的Metadata中找到Description
  3. 在Description可以获取name也就是属性的名称
  4. 通过内存偏移获取到属性值
  5. 还可以通过numFields获取属性的个数

下面通过该流程图总结一下swift中的mirror对结构体进行反射的主要流程

关于其他类型的反射也大同小异,还有元组、枚举、类、元数据以及不透明类型的反射,当然也有不完全支持反射的类型,比如结构体就是不完全支持反射的类型,感兴趣的可以继续探索一下。

swift中的type(of:)、dump(t)就是基于Mirror的反射原理来实现的

Swift中的json解析框架HandyJSON的主要原理与Mirror类似,本质上就是利用metadata中的Description,通过字段的访问,做内存的赋值。

4. 仿写 Mirror

为了加深对Mirror的理解,我们使用Swift语言仿写一下。还是以结构体为例。

▐ 4.1 TargetStructMetadata

首先我们需要拥有一个结构体的元数据结构,这里我们命名为StructMetadata,里面有继承的kind和Descriptor属性,这里的Descriptor属性是一个TargetStructDescriptor类型的指针。仿写代码如下:

  1. struct StructMetadata{ 
  2.     var kind: Int 
  3.     var Descriptor: UnsafeMutablePointer<StructDescriptor> 

▐ 4.2 TargetStructDescriptor

在4.1中我们用到的Descriptor属性的内部结构现在也来实现一下。这个是Mirror中用到很多的属性。对于结构体来说其内部有7个属性

  1. flag是个32位的整形,我们用Int32代替
  2. parent是记录父类的,类型是TargetRelativeContextPointer,这里也可以用Int32代替
  3. name记录类型的,它的类型是TargetRelativeDirectPointer,所以我们需要实现一个TargetRelativeDirectPointer
  4. AccessFunctionPtr与name类似,内部是个指针
  5. Fields也与name类似,内部是个FieldDescriptor
  6. NumFields使用Int32
  7. FieldOffsetVectorOffset也是用Int32

仿写实现如下:

  1. struct StructDescriptor { 
  2.     let flags: Int32 
  3.     let parent: Int32 
  4.     var name: RelativePointer<CChar> 
  5.     var AccessFunctionPtr: RelativePointer<UnsafeRawPointer> 
  6.     var Fields: RelativePointer<FieldDescriptor> 
  7.     var NumFields: Int32 
  8.     var FieldOffsetVectorOffset: Int32 

▐ 4.3 TargetRelativeDirectPointer

  • TargetRelativeDirectPointer是RelativeDirectPointer的别名,其内部有一个继承的RelativeOffset属性,是int32_t类型,我们可以用Int32代替。
  • 还有一个get方法。内部通过指针偏移获取值

仿写实现如下:

  1. struct RelativePointer<T> { 
  2.     var offset: Int32 
  3.  
  4.     mutating func get() -> UnsafeMutablePointer<T>{ 
  5.         let offset = self.offset 
  6.  
  7.         return withUnsafePointer(to: &self) { p in 
  8.             return UnsafeMutablePointer(mutating: UnsafeRawPointer(p).advanced(by: numericCast(offset)).assumingMemoryBound(to: T.self)) 
  9.         } 
  10.     } 

4.4 FieldDescriptor

FieldDescriptor在Mirror反射中有着很重要的作用,其内部有5个属性:

  1. MangledTypeName是RelativeDirectPointer类型,我们使用RelativePointer代替
  2. Superclass与MangledTypeName一样
  3. kind是FieldDescriptorKind类型,实际是uint16_t,这里我们使用UInt16代替
  4. fieldRecordSize是uint16_t也使用使用UInt16代替
  5. numFields使用Int32代替
  6. fields,其实从属性上看不到有这个,但是这里面有个getFieldRecordBuffer方法,通过this+1的方式一个一个的访问属性,所以这是一块连续的内存空间,我们使用fields代替

仿写代码如下:

  1. struct FieldDescriptor { 
  2.     var MangledTypeName: RelativePointer<CChar> 
  3.     var Superclass: RelativePointer<CChar> 
  4.     var kind: UInt16 
  5.     var fieldRecordSize: Int16 
  6.     var numFields: Int32 
  7.     var fields: FieldRecord //连续的存储空间 

▐ 4.5 FieldRecord

FieldRecord存储着属性的相关信息,其内部有三个属性

  1. Flags是FieldRecordFlags类型实际是uint32_t,这里我们使用Int32代替
  2. MangledTypeName使用RelativePointer代替
  3. FieldName使用RelativePointer代替

仿写带如下:

  1. struct FieldRecord { 
  2.     var Flags: Int32 
  3.     var MangledTypeName: RelativePointer<CChar> 
  4.     var FieldName: RelativePointer<CChar> 

▐ 4.6 测试

下面我们使用内存绑定的计数访问一个结构体

定义一个结构体:

  1. struct Person { 
  2.     var name: String = "xiaohei" 
  3.     var age: Int = 18 
  4.     var height = 1.85 
  5.  
  6. var p = Person() 

4.6.1 绑定结构体内存

使用unsafeBitCast按位强转,将Person绑定到StructMetadata上,这个操作非常危险,没有任何校验和修饰

  1. let ptr = unsafeBitCast(Person.self as Any.Type, to: UnsafeMutablePointer<StructMetadata>.self) 

4.6.2 打印类型和属性个数

下面我们就打印一下结构体的类型(也就是它的名称)和其中属性的个数:

  1. let namePtr = ptr.pointee.Descriptor.pointee.name.get() 
  2.  
  3. print(String(cString: namePtr)) 
  4. print(ptr.pointee.Descriptor.pointee.NumFields) 

打印结果:

这里我们就可以看到结构体的名称和其属性个数的正确打印了。

4.6.3 打印属性名称

下面我们就来打印一下属性的名称,首先是获取到FieldDescriptor的指针,然后通过内存偏移的方式访问每一个FieldRecord,最后在访问FieldRecord中的属性名。代码如下:

  1. let fieldDescriptorPtr = ptr.pointee.Descriptor.pointee.Fields.get() 
  2.  
  3. let recordPtr = withUnsafePointer(to: &fieldDescriptorPtr.pointee.fields) { 
  4.     return UnsafeMutablePointer(mutating: UnsafeRawPointer($0).assumingMemoryBound(to: FieldRecord.self).advanced(by: 2)) 
  5.  
  6. print(String(cString: recordPtr.pointee.FieldName.get())) 

打印结果:

此时我们就可以看到第三属性height的打印,如果advanced(by: 0)则打印第一个属性,以此类推。

4.6.1 打印属性值

下面我们访问一下属性值:

首先是获取属性偏移量的数组,也就是getFieldOffsets函数返回的值。根据源码:

  • 首先获取FieldOffsetVectorOffset的值
  • 然后在加上this也就是当前Metadata的指针
  • 这里我们将仿写的StructMetadata的指针ptr重绑定为Int
  • 源码中加上FieldOffsetVectorOffset,这里我们就移动FieldOffsetVectorOffset
  • 然后将上述移动后的绑定为一个Int32的指针
  • 最后使用UnsafeBufferPointer和属性个数创建一个buffer数组指针
  • 接下来我们就可以从数组中取出每个属性的偏移值
  • 然后取出结构体实例p的内存地址
  • 然后按照buffer数组中的偏移值进行偏移,重绑定为属性的类型
  • 最后就可以打印出属性值了

实现代码:

  1. var bufferPtr = UnsafeBufferPointer(start: UnsafeRawPointer(UnsafeRawPointer(ptr).assumingMemoryBound(toInt.self).advanced(by: numericCast(ptr.pointee.Descriptor.pointee.FieldOffsetVectorOffset))).assumingMemoryBound(to: Int32.self), countInt(ptr.pointee.Descriptor.pointee.NumFields)) 
  2.  
  3. var fieldOffset = bufferPtr[2] 
  4.  
  5. var valuePtr = withUnsafeMutablePointer(to: &p) { $0 } 
  6.  
  7. var bufferPtr1 = UnsafeRawPointer(UnsafeRawPointer(valuePtr).advanced(by: numericCast(bufferPtr[0]))).assumingMemoryBound(to: String.self) 
  8. print(bufferPtr1.pointee) 
  9.  
  10. var bufferPtr2 = UnsafeRawPointer(UnsafeRawPointer(valuePtr).advanced(by: numericCast(bufferPtr[1]))).assumingMemoryBound(toInt.self) 
  11. print(bufferPtr2.pointee) 
  12.  
  13. var bufferPtr3 = UnsafeRawPointer(UnsafeRawPointer(valuePtr).advanced(by: numericCast(bufferPtr[2]))).assumingMemoryBound(toDouble.self) 
  14. print(bufferPtr3.pointee) 

打印结果:

 

责任编辑:姜华 来源: Swift 社区
相关推荐

2021-04-14 07:55:45

Swift 协议Protocol

2021-05-10 07:38:09

Swift 泛型Tips

2021-04-30 09:04:11

Go 语言结构体type

2021-07-12 06:11:14

SkyWalking 仪表板UI篇

2022-07-07 08:02:49

RedisBitMap

2021-06-24 06:35:00

Go语言进程

2021-06-21 14:36:46

Vite 前端工程化工具

2022-04-29 14:38:49

class文件结构分析

2021-04-08 11:00:56

CountDownLaJava进阶开发

2021-07-21 09:48:20

etcd-wal模块解析数据库

2021-04-01 10:51:55

MySQL锁机制数据库

2021-04-14 14:16:58

HttpHttp协议网络协议

2021-01-28 08:55:48

Elasticsear数据库数据存储

2023-03-29 07:45:58

VS编辑区编程工具

2021-03-12 09:21:31

MySQL数据库逻辑架构

2022-03-22 09:09:17

HookReact前端

2022-02-17 08:53:38

ElasticSea集群部署

2021-06-09 09:08:10

LDOlowdropoutr稳压器

2020-12-24 08:07:18

SpringBootSpring SecuWeb

2022-03-03 09:05:17

索引MySQL数据查询
点赞
收藏

51CTO技术栈公众号