Swift - 实例对象调用协议方法优先级分析/ witness_methos witness_table分析

2021-12-11 23:16:59 浏览数 (1)

本文主要探究:

  1. 当一个类遵循了协议,且协议和类都有方法实现时,实例对象调用方法的优先顺序

代码示例1:

转为SIL源码查看:swiftc -emit-sil main.swift | xcrun swift-demangle >> ./main.sil

main函数

代码语言:javascript复制
protocol YRProtocol {
 func teach()
}

extension YRProtocol {
 func teach()
}

class YRTeach : YRProtocol {
 func teach()
 @objc deinit
 init()
}

@_hasStorage @_hasInitialValue var object1: YRProtocol { get set }

@_hasStorage @_hasInitialValue var object2: YRTeach { get set }

// object1
sil_global hidden @main.object1 : main.YRProtocol : $YRProtocol

// object2
sil_global hidden @main.object2 : main.YRTeach : $YRTeach

// main
sil @main : $@convention(c) (Int32, UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>) -> Int32 {
bb0(%0 : $Int32, %1 : $UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>):
 alloc_global @main.object1 : main.YRProtocol // id: %2
 %3 = global_addr @main.object1 : main.YRProtocol : $*YRProtocol // users: %9, %7
 %4 = metatype $@thick YRTeach.Type              // user: %6
 // function_ref YRTeach.__allocating_init()
 %5 = function_ref @main.YRTeach.__allocating_init() -> main.YRTeach : $@convention(method) (@thick YRTeach.Type) -> @owned YRTeach // user: %6
 %6 = apply %5(%4) : $@convention(method) (@thick YRTeach.Type) -> @owned YRTeach // user: %8
 %7 = init_existential_addr %3 : $*YRProtocol, $YRTeach // user: %8
 store %6 to %7 : $*YRTeach                      // id: %8
 %9 = begin_access [read] [dynamic] %3 : $*YRProtocol // users: , 
  = alloc_stack $YRProtocol                   // users: , , , 
 copy_addr %9 to [initialization]  : $*YRProtocol // id: 
 end_access %9 : $*YRProtocol                    // id: 
  = open_existential_addr immutable_access  : $*YRProtocol to $*@opened("AE485D14-5A5E-11EC-81A7-ACDE48001122") YRProtocol // users: , , 
  = witness_method $@opened("AE485D14-5A5E-11EC-81A7-ACDE48001122") YRProtocol, #YRProtocol.teach : <Self where Self : YRProtocol> (Self) -> () -> (),  : $*@opened("AE485D14-5A5E-11EC-81A7-ACDE48001122") YRProtocol : $@convention(witness_method: YRProtocol) <τ_0_0 where τ_0_0 : YRProtocol> (@in_guaranteed τ_0_0) -> () // type-defs: ; user: 
  = apply <@opened("AE485D14-5A5E-11EC-81A7-ACDE48001122") YRProtocol>() : $@convention(witness_method: YRProtocol) <τ_0_0 where τ_0_0 : YRProtocol> (@in_guaranteed τ_0_0) -> () // type-defs: 
 destroy_addr  : $*YRProtocol                 // id: 
 dealloc_stack  : $*YRProtocol                // id: 
 alloc_global @main.object2 : main.YRTeach      // id: 
  = global_addr @main.object2 : main.YRTeach : $*YRTeach // users: #, $
   = metatype $@thick YRTeach.Type             // user: "
 // function_ref YRTeach.__allocating_init()
 ! = function_ref @main.YRTeach.__allocating_init() -> main.YRTeach : $@convention(method) (@thick YRTeach.Type) -> @owned YRTeach // user: "
 " = apply !( ) : $@convention(method) (@thick YRTeach.Type) -> @owned YRTeach // user: #
 store " to  : $*YRTeach                    // id: #
 $ = begin_access [read] [dynamic]  : $*YRTeach // users: %, '
 % = load $ : $*YRTeach                      // users: 0, (, ), &
 strong_retain % : $YRTeach                    // id: &
 end_access $ : $*YRTeach                      // id: '
 ( = class_method % : $YRTeach, #YRTeach.teach : (YRTeach) -> () -> (), $@convention(method) (@guaranteed YRTeach) -> () // user: )
 ) = apply ((%) : $@convention(method) (@guaranteed YRTeach) -> ()
 strong_release % : $YRTeach                   // id: 0
 1 = integer_literal $Builtin.Word, 1          // user: 3
 // function_ref _allocateUninitializedArray<A>(_:)
 2 = function_ref @Swift._allocateUninitializedArray<A>(Builtin.Word) -> ([A], Builtin.RawPointer) : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer) // user: 3
 3 = apply 2<Any>(1) : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer) // users: 5, 4
 4 = tuple_extract 3 : $(Array<Any>, Builtin.RawPointer), 0 // user: F
 5 = tuple_extract 3 : $(Array<Any>, Builtin.RawPointer), 1 // user: 6
 6 = pointer_to_address 5 : $Builtin.RawPointer to [strict] $*Any // user: C
 7 = string_literal utf8 "end"                 // user: B
 8 = integer_literal $Builtin.Word, 3          // user: B
 9 = integer_literal $Builtin.Int1, -1         // user: B
 @ = metatype $@thin String.Type               // user: B
 // function_ref String.init(_builtinStringLiteral:utf8CodeUnitCount:isASCII:)
 A = function_ref @Swift.String.init(_builtinStringLiteral: Builtin.RawPointer, utf8CodeUnitCount: Builtin.Word, isASCII: Builtin.Int1) -> Swift.String : $@convention(method) (Builtin.RawPointer, Builtin.Word, Builtin.Int1, @thin String.Type) -> @owned String // user: B
 B = apply A(7, 8, 9, @) : $@convention(method) (Builtin.RawPointer, Builtin.Word, Builtin.Int1, @thin String.Type) -> @owned String // user: D
 C = init_existential_addr 6 : $*Any, $String // user: D
 store B to C : $*String                     // id: D
 // function_ref _finalizeUninitializedArray<A>(_:)
 E = function_ref @Swift._finalizeUninitializedArray<A>(__owned [A]) -> [A] : $@convention(thin) <τ_0_0> (@owned Array<τ_0_0>) -> @owned Array<τ_0_0> // user: F
 F = apply E<Any>(4) : $@convention(thin) <τ_0_0> (@owned Array<τ_0_0>) -> @owned Array<τ_0_0> // users: U, R
 // function_ref default argument 1 of print(_:separator:terminator:)
 G = function_ref @default argument 1 of Swift.print(_: Any..., separator: Swift.String, terminator: Swift.String) -> () : $@convention(thin) () -> @owned String // user: H
 H = apply G() : $@convention(thin) () -> @owned String // users: T, R
 // function_ref default argument 2 of print(_:separator:terminator:)
 I = function_ref @default argument 2 of Swift.print(_: Any..., separator: Swift.String, terminator: Swift.String) -> () : $@convention(thin) () -> @owned String // user: P
 P = apply I() : $@convention(thin) () -> @owned String // users: S, R
 // function_ref print(_:separator:terminator:)
 Q = function_ref @Swift.print(_: Any..., separator: Swift.String, terminator: Swift.String) -> () : $@convention(thin) (@guaranteed Array<Any>, @guaranteed String, @guaranteed String) -> () // user: R
 R = apply Q(F, H, P) : $@convention(thin) (@guaranteed Array<Any>, @guaranteed String, @guaranteed String) -> ()
 release_value P : $String                     // id: S
 release_value H : $String                     // id: T
 release_value F : $Array<Any>                 // id: U
 V = integer_literal $Builtin.Int32, 0         // user: W
 W = struct $Int32 (V : $Builtin.Int32)      // user: X
 return W : $Int32                             // id: X
} // end sil function 'main'
复制代码

查看main源码知道,生成的object1通过witness_method调用了YRProtocol.Teach方法

witness_method的官方说明:

witness_method 表示在witness_table中查询协议方法的实现并调用

此处我们在SIL源码中查找YRProtocol协议的witness_table方法

代码语言:javascript复制
sil_vtable YRTeach {
  #YRTeach.teach: (YRTeach) -> () -> () : @main.YRTeach.teach() -> ()	// YRTeach.teach()
  #YRTeach.init!allocator: (YRTeach.Type) -> () -> YRTeach : @main.YRTeach.__allocating_init() -> main.YRTeach	// YRTeach.__allocating_init()
  #YRTeach.deinit!deallocator: @main.YRTeach.__deallocating_deinit	// YRTeach.__deallocating_deinit
}

sil_witness_table hidden YRTeach: YRProtocol module main {
  method #YRProtocol.teach: <Self where Self : YRProtocol> (Self) -> () -> () : @protocol witness for main.YRProtocol.teach() -> () in conformance main.YRTeach : main.YRProtocol in main	// protocol witness for YRProtocol.teach() in conformance YRTeach
}
复制代码

从witness_table中我们发现确实有定义YRProtocol.teach()方法

然后查看YRProtocol.teach()的具体实现

总结1. 当protocol中声明了方法时,源码做了如下操作:

  1. witness_table中存放协议方法
  2. 实例对象调用协议方法时,编译器会通过witness_method这个方法去 witness_m ethod表中查找对应协议方法并调用
  3. 协议方法的实现,本质是调用遵循了协议的类里协议方法的实现(通过class_method在sil_vtable中查询),而并不会调用协议拓展里的方法实现

2. 代码示例2:

此时发现打印变了,打印了YRProtocol extension里的方法,查看SIL源码:

同时,源码中也没有witness_table中也没有方法声明和实现

总结2: 当protocol中没有声明方法时,witness_table中没有协议方法的声明,编译器会调用协议 extension中的方法实现

总结:

  1. 当协议中有方法声明时(witness_table有声明),
    • 类中有方法实现: 实例对象优先调用类中的方法实现
    • 类中没有方法实现: 实例对象调用协议拓展中的方法实现
  2. 当协议中没有方法声明时(witness_table没有声明):

实例对象总是调用协议拓展中的方法实现

参考:

官方文档:witness_method

官方文档:witness_table

0 人点赞