Swift - 實(shí)例對(duì)象調(diào)用協(xié)議方法優(yōu)先級(jí)分析/ witness_methos witness_table分析

本文主要探究:

  1. 當(dāng)一個(gè)類遵循了協(xié)議,且協(xié)議和類都有方法實(shí)現(xiàn)時(shí),實(shí)例對(duì)象調(diào)用方法的優(yōu)先順序

代碼示例1:

WX20211211-162957@2x.png

轉(zhuǎn)為SIL源碼查看:swiftc -emit-sil main.swift | xcrun swift-demangle >> ./main.sil

main函數(shù)

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: %12, %11
 %10 = alloc_stack $YRProtocol                   // users: %17, %16, %13, %11
 copy_addr %9 to [initialization] %10 : $*YRProtocol // id: %11
 end_access %9 : $*YRProtocol                    // id: %12
 %13 = open_existential_addr immutable_access %10 : $*YRProtocol to $*@opened("AE485D14-5A5E-11EC-81A7-ACDE48001122") YRProtocol // users: %15, %15, %14
 %14 = witness_method $@opened("AE485D14-5A5E-11EC-81A7-ACDE48001122") YRProtocol, #YRProtocol.teach : <Self where Self : YRProtocol> (Self) -> () -> (), %13 : $*@opened("AE485D14-5A5E-11EC-81A7-ACDE48001122") YRProtocol : $@convention(witness_method: YRProtocol) <τ_0_0 where τ_0_0 : YRProtocol> (@in_guaranteed τ_0_0) -> () // type-defs: %13; user: %15
 %15 = apply %14<@opened("AE485D14-5A5E-11EC-81A7-ACDE48001122") YRProtocol>(%13) : $@convention(witness_method: YRProtocol) <τ_0_0 where τ_0_0 : YRProtocol> (@in_guaranteed τ_0_0) -> () // type-defs: %13
 destroy_addr %10 : $*YRProtocol                 // id: %16
 dealloc_stack %10 : $*YRProtocol                // id: %17
 alloc_global @main.object2 : main.YRTeach      // id: %18
 %19 = global_addr @main.object2 : main.YRTeach : $*YRTeach // users: %23, %24
 %20 = metatype $@thick YRTeach.Type             // user: %22
 // function_ref YRTeach.__allocating_init()
 %21 = function_ref @main.YRTeach.__allocating_init() -> main.YRTeach : $@convention(method) (@thick YRTeach.Type) -> @owned YRTeach // user: %22
 %22 = apply %21(%20) : $@convention(method) (@thick YRTeach.Type) -> @owned YRTeach // user: %23
 store %22 to %19 : $*YRTeach                    // id: %23
 %24 = begin_access [read] [dynamic] %19 : $*YRTeach // users: %25, %27
 %25 = load %24 : $*YRTeach                      // users: %30, %28, %29, %26
 strong_retain %25 : $YRTeach                    // id: %26
 end_access %24 : $*YRTeach                      // id: %27
 %28 = class_method %25 : $YRTeach, #YRTeach.teach : (YRTeach) -> () -> (), $@convention(method) (@guaranteed YRTeach) -> () // user: %29
 %29 = apply %28(%25) : $@convention(method) (@guaranteed YRTeach) -> ()
 strong_release %25 : $YRTeach                   // id: %30
 %31 = integer_literal $Builtin.Word, 1          // user: %33
 // function_ref _allocateUninitializedArray<A>(_:)
 %32 = function_ref @Swift._allocateUninitializedArray<A>(Builtin.Word) -> ([A], Builtin.RawPointer) : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer) // user: %33
 %33 = apply %32<Any>(%31) : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer) // users: %35, %34
 %34 = tuple_extract %33 : $(Array<Any>, Builtin.RawPointer), 0 // user: %46
 %35 = tuple_extract %33 : $(Array<Any>, Builtin.RawPointer), 1 // user: %36
 %36 = pointer_to_address %35 : $Builtin.RawPointer to [strict] $*Any // user: %43
 %37 = string_literal utf8 "end"                 // user: %42
 %38 = integer_literal $Builtin.Word, 3          // user: %42
 %39 = integer_literal $Builtin.Int1, -1         // user: %42
 %40 = metatype $@thin String.Type               // user: %42
 // function_ref String.init(_builtinStringLiteral:utf8CodeUnitCount:isASCII:)
 %41 = 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: %42
 %42 = apply %41(%37, %38, %39, %40) : $@convention(method) (Builtin.RawPointer, Builtin.Word, Builtin.Int1, @thin String.Type) -> @owned String // user: %44
 %43 = init_existential_addr %36 : $*Any, $String // user: %44
 store %42 to %43 : $*String                     // id: %44
 // function_ref _finalizeUninitializedArray<A>(_:)
 %45 = function_ref @Swift._finalizeUninitializedArray<A>(__owned [A]) -> [A] : $@convention(thin) <τ_0_0> (@owned Array<τ_0_0>) -> @owned Array<τ_0_0> // user: %46
 %46 = apply %45<Any>(%34) : $@convention(thin) <τ_0_0> (@owned Array<τ_0_0>) -> @owned Array<τ_0_0> // users: %55, %52
 // function_ref default argument 1 of print(_:separator:terminator:)
 %47 = function_ref @default argument 1 of Swift.print(_: Any..., separator: Swift.String, terminator: Swift.String) -> () : $@convention(thin) () -> @owned String // user: %48
 %48 = apply %47() : $@convention(thin) () -> @owned String // users: %54, %52
 // function_ref default argument 2 of print(_:separator:terminator:)
 %49 = function_ref @default argument 2 of Swift.print(_: Any..., separator: Swift.String, terminator: Swift.String) -> () : $@convention(thin) () -> @owned String // user: %50
 %50 = apply %49() : $@convention(thin) () -> @owned String // users: %53, %52
 // function_ref print(_:separator:terminator:)
 %51 = function_ref @Swift.print(_: Any..., separator: Swift.String, terminator: Swift.String) -> () : $@convention(thin) (@guaranteed Array<Any>, @guaranteed String, @guaranteed String) -> () // user: %52
 %52 = apply %51(%46, %48, %50) : $@convention(thin) (@guaranteed Array<Any>, @guaranteed String, @guaranteed String) -> ()
 release_value %50 : $String                     // id: %53
 release_value %48 : $String                     // id: %54
 release_value %46 : $Array<Any>                 // id: %55
 %56 = integer_literal $Builtin.Int32, 0         // user: %57
 %57 = struct $Int32 (%56 : $Builtin.Int32)      // user: %58
 return %57 : $Int32                             // id: %58
} // end sil function 'main'

查看main源碼知道,生成的object1通過witness_method調(diào)用了YRProtocol.Teach方法

2131639212958_.pic.jpg

witness_method的官方說明:

WX20211211-170352@2x.png

witness_method 表示在witness_table中查詢協(xié)議方法的實(shí)現(xiàn)并調(diào)用

此處我們?cè)赟IL源碼中查找YRProtocol協(xié)議的witness_table方法

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中我們發(fā)現(xiàn)確實(shí)有定義YRProtocol.teach()方法

然后查看YRProtocol.teach()的具體實(shí)現(xiàn)

WX20211211-171715@2x.png

總結(jié)1. 當(dāng)protocol中聲明了方法時(shí),源碼做了如下操作:
  1. witness_table中存放協(xié)議方法
  2. 實(shí)例對(duì)象調(diào)用協(xié)議方法時(shí),編譯器會(huì)通過witness_method這個(gè)方法去 witness_m ethod表中查找對(duì)應(yīng)協(xié)議方法并調(diào)用
  3. 協(xié)議方法的實(shí)現(xiàn),本質(zhì)是調(diào)用遵循了協(xié)議的類里協(xié)議方法的實(shí)現(xiàn)(通過class_method在sil_vtable中查詢),而并不會(huì)調(diào)用協(xié)議拓展里的方法實(shí)現(xiàn)

2. 代碼示例2:

WX20211211-172619@2x.png

此時(shí)發(fā)現(xiàn)打印變了,打印了YRProtocol extension里的方法,查看SIL源碼:


WX20211211-173217@2x.png

同時(shí),源碼中也沒有witness_table中也沒有方法聲明和實(shí)現(xiàn)


WX20211211-173448@2x.png

總結(jié)2:
當(dāng)protocol中沒有聲明方法時(shí),witness_table中沒有協(xié)議方法的聲明,編譯器會(huì)調(diào)用協(xié)議 extension中的方法實(shí)現(xiàn)

總結(jié):

  1. 當(dāng)協(xié)議中有方法聲明時(shí)(witness_table有聲明),
    • 類中有方法實(shí)現(xiàn): 實(shí)例對(duì)象優(yōu)先調(diào)用類中的方法實(shí)現(xiàn)
    • 類中沒有方法實(shí)現(xiàn): 實(shí)例對(duì)象調(diào)用協(xié)議拓展中的方法實(shí)現(xiàn)
  2. 當(dāng)協(xié)議中沒有方法聲明時(shí)(witness_table沒有聲明):
    實(shí)例對(duì)象總是調(diào)用協(xié)議拓展中的方法實(shí)現(xiàn)

參考:

官方文檔:witness_method

官方文檔:witness_table

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,488評(píng)論 6 531
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,034評(píng)論 3 414
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,327評(píng)論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我,道長(zhǎng),這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,554評(píng)論 1 307
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 71,337評(píng)論 6 404
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 54,883評(píng)論 1 321
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 42,975評(píng)論 3 439
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,114評(píng)論 0 286
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,625評(píng)論 1 332
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 40,555評(píng)論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 42,737評(píng)論 1 369
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,244評(píng)論 5 355
  • 正文 年R本政府宣布,位于F島的核電站,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 43,973評(píng)論 3 345
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,362評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,615評(píng)論 1 280
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 51,343評(píng)論 3 390
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 47,699評(píng)論 2 370

推薦閱讀更多精彩內(nèi)容