<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by kateinoigakukun on Medium]]></title>
        <description><![CDATA[Stories by kateinoigakukun on Medium]]></description>
        <link>https://medium.com/@kateinoigakukun?source=rss-ced73058857c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*KnDKvxfa-_qxx7ljrMI8yg.jpeg</url>
            <title>Stories by kateinoigakukun on Medium</title>
            <link>https://medium.com/@kateinoigakukun?source=rss-ced73058857c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 15:40:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kateinoigakukun/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[An Update on WebAssembly/WASI Support in Ruby]]></title>
            <link>https://itnext.io/final-report-webassembly-wasi-support-in-ruby-4aface7d90c9?source=rss-ced73058857c------2</link>
            <guid isPermaLink="false">https://medium.com/p/4aface7d90c9</guid>
            <category><![CDATA[webassembly]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[kateinoigakukun]]></dc:creator>
            <pubDate>Wed, 16 Mar 2022 08:18:23 GMT</pubDate>
            <atom:updated>2022-03-18T08:40:50.071Z</atom:updated>
            <content:encoded><![CDATA[<h3>Overview</h3><p>CRuby is a highly portable C application, and it runs on many platforms (You can see which platforms are tested on CI <a href="https://rubyci.org/">here</a>). However the “portability” is only at source level, and the built executable is not portable across architectures and system call interfaces.</p><p>This project made CRuby portable at executable file level by porting it to a standalone WebAssembly with WASI ABI. Furthermore, we implemented a VFS (Virtual File System) at WASI to package Ruby scripts into a single WebAssembly binary. These improvements make it easier to distribute Ruby scripts.</p><p>This is the final report required by <a href="https://www.ruby.or.jp/en/news/20211025">the 2021 Ruby Association Grant</a>.</p><h3>About WebAssembly and WASI</h3><p>WebAssembly is not only for porting existing projects to the web browser, but also for providing a sandboxed portable executable. It’s not limited to the web, and is being used in a variety of situations such as edge computing, embedded environments, and interfaces for plug-in systems.</p><p>The Ruby community has already ported CRuby to WebAssembly using Emscripten, but it depends heavily on the host JavaScript environment. It makes it difficult to use for the above applications.</p><p>WASI is an effort to define a standard set of syscalls for WebAssembly modules, allowing WebAssembly modules to not only be portable across architectures but also be portable across environments implementing this standard set of system calls. WASI does not rely on JavaScript at all.</p><p>For C and C++ users, <a href="https://github.com/WebAssembly/wasi-sdk">WASI SDK</a>, which is an LLVM compiler toolchain with musl and cloudlibc based libc <a href="https://github.com/WebAssembly/wasi-libc">wasi-libc</a> is provided.</p><h3>Implementation</h3><p>Now the master branch of CRuby supports WASI as a build target by our several patches. The initial patchset for the support was <a href="https://github.com/ruby/ruby/pull/5407">ruby/ruby#5407</a> (has been merged).</p><p>This feature is tracked on <a href="https://bugs.ruby-lang.org/issues/18462">“Proposal to merge WASI based WebAssembly support”</a>.</p><p>Today’s WASI has limited system calls, and WebAssembly itself doesn’t have context-switching mechanism. So CRuby needed some workarounds to address them. The notable changes are:</p><ul><li>Add emulation implementations for some missing functionalities using Asyncify: setjmp/longjmp for Exception, ucontext for Fiber, register scan for GC…</li><li>Support no thread environment</li></ul><p>The current master branch passes basictest, bootstraptest, and ruby/spec except for Thread and process-related tests. And also it supports extension libraries linked statically.</p><p>You can see how to build WASI target Ruby here: <a href="https://github.com/ruby/ruby/blob/master/wasm/README.md">https://github.com/ruby/ruby/blob/master/wasm/README.md</a></p><p>Also, I became a committer to maintain this feature continuously.</p><h3>Emulations powered by Asyncify</h3><p>As mentioned above, the current WebAssembly has no context switching feature, but there is a userland technique to pause and resume a WebAssembly process by binary transformation. This technique is called <a href="https://kripken.github.io/blog/wasm/2019/07/16/asyncify.html">Asyncify</a>.</p><p>Asyncify provides two operations to control program execution.</p><ol><li>Stop the current execution and unwind to the root call frame while writing out execution state and function-local registers (a.k.a Wasm locals) to memory</li><li>Rewind to the stopped call frame while restoring the saved execution state and registers.</li></ol><p>You can see these emulation implementations under <a href="https://github.com/ruby/ruby/tree/master/wasm">the </a><a href="https://github.com/ruby/ruby/tree/master/wasm">wasm directory in the ruby/ruby repository</a>.</p><h4>setjmp/longjmp</h4><p>Thanks to these magical operations, setjmp and longjmp can be simply emulated like the following procedure:</p><ol><li>setjmp saves the current stack pointer and execution state by unwinding to the main, then rewinds to the call-site of setjmp.</li><li>longjmp unwinds to the main, but discards the collected execution state and rewinds to the call-site of setjmp saved at step 1, then restores the saved stack pointer.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7v3Qda9royMX-kn1" /></figure><p>However, this setjmp emulation gets slower and slower as the call stack gets deeper! In addition, setjmp is used in the core of the Ruby VM. So we mitigated the performance penalty by avoiding rewinds to the main in the core implementation.</p><p>We’ve also considered using <a href="https://github.com/WebAssembly/exception-handling">exception-handling proposal</a> and it’s 1.88 times faster than Asyncify approach in microbenchmark. However, we found that it requires quite a few changes to rewrite all use of setjmp/longjmp with try-catch style at C level. We decided to use Asyncify approach for now to minimize the effects of our patches rather than performance gain.</p><h4>Fiber (ucontext)</h4><p>Similar to setjmp/longjmp, Fiber on WASI exploits Asyncify. It simply switches the execution state by unwinding/rewinding and swapping stack pointers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kWPXA0L_1P-qxdXx" /></figure><h4>Scanning registers (Wasm locals) for GC</h4><p>CRuby uses conservative garbage collection, which marks pointer-like values by scanning some value spaces to find living objects.</p><p>While running WebAssembly program, Ruby object ( VALUE) can be put in:</p><ol><li>Wasm Stack: Defined in Wasm spec</li><li>Function-local Registers (Wasm Locals): Defined in Wasm spec</li><li>C Stack: Allocated in linear memory</li></ol><p>Unlike the normal memory space like 3. C Stack, 1. Wasm Stack and 2. Function-local Registers cannot be scanned dynamically. Fortunately, Asyncify writes Wasm Locals and Wasm Stacks out as execution states, so GC unwinds and rewinds by Asyncify and scans the execution states stored in the linear memory.</p><h3>Virtual File System for WASI</h3><p>We implemented a VFS (Virtual File System) at WASI, named <a href="https://github.com/kateinoigakukun/wasi-vfs">wasi-vfs</a>, to package Ruby scripts into a single WebAssembly binary. It’s not only for Ruby, but also for any application using wasi-libc.</p><h4>Usage</h4><p>You can package directories with the same options as you run with wasmtime or wasmer.</p><pre># Without packing<br>$ wasmtime run ruby.wasm --mapdir /::./lib -- /irb.rb<br>irb(main):001:0&gt;<br>...<br># Packing with wasm-vfs<br>$ wasm-vfs pack ruby.wasm --mapdir /::./lib -o irb.wasm<br>$ wasmtime run irb.wasm -- /irb.rb<br>irb(main):001:0&gt;<br>...</pre><p>Note that it currently requires to link libwasi_vfs.a because it depends on linker&#39;s symbol resolution mechanism to hook WASI system calls, and also needs to merge data sections. However, this limitation will be removed after <a href="https://github.com/WebAssembly/module-linking">module-linking</a> will be in place.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*D5QQTugkoT-bwgib.png" /></figure><h4>How does it work?</h4><p>The wasi-vfs pack command is a wrapper of Wizer, which is a pre-initializer of Wasm applications. See also <a href="https://bytecodealliance.org/articles/making-javascript-run-fast-on-webassembly">Bytecode Alliance: Making JavaScript run fast on WebAssembly</a>.</p><p>The initialization process in wasi-vfs scans the mapped directories then copies them into in-memory virtual filesystem. Then Wizer takes a snapshot of that state and saves it as a Wasm file.</p><h3>Interoperation with JavaScript</h3><p>We’ve also implemented a Ruby &lt;-&gt; JavaScript interop library as <a href="https://github.com/kateinoigakukun/ruby.wasm/blob/main/packages/npm-packages/ruby-wasm-wasi/README.md">a npm package</a> for browser and Node.js. It’s already used in <a href="https://try.ruby-lang.org/playground/">try.ruby-lang.org</a>.</p><pre>const vm = await DefaultRubyVM();<br>vm.eval(`<br>  luckiness = [&quot;Lucky&quot;, &quot;Unlucky&quot;].sample<br>  JS::eval(&quot;document.body.innerText = &#39;#{luckiness}&#39;&quot;)<br>`);</pre><h3>Performance benchmark</h3><p>Here is a performance benchmark report of <a href="https://github.com/mame/optcarrot">Optcarrot</a> compared with native CRuby and other Ruby implementations. (bigger is better)</p><p>master (wasm32-wasi) and opal use Node.js v16.14.0 as their JS and Wasm runtime.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*XoJC70n9dBsHoY6wBOlplA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*Y27xFxcFRfZ3LmCL0Noi7A.png" /></figure><p>Performance profiler reports similar trends for heaviest functions, so the bottleneck is not in CRuby implementation but Wasm runtime is slower than native. Also, it includes Asyncify overheads as we mentioned above.</p><h3>Other trivial works</h3><ul><li><a href="https://github.com/kateinoigakukun/ruby.wasm">ruby.wasm</a>: Nightly release of prebuilt Wasm target Ruby</li><li><a href="https://github.com/kateinoigakukun/wasi-preset-args">wasi-preset-args</a>: A tool to preset command-line arguments to a WASI module. This is useful to set script path passed to Ruby. Some platforms like <a href="https://www.fastly.com/jp/products/edge-compute/serverless">Compute@Edge</a> cannot give arguments, so this tool is essential</li><li><a href="https://github.com/kateinoigakukun/optcarrot.wasm">optcarrot.wasm</a>: A game emulator written in Ruby on browser powered by WebAssembly</li><li><a href="https://github.com/kateinoigakukun/irb.wasm">irb.wasm</a>: IRB on browser powered by WebAssembly</li><li><a href="https://wapm.io/katei/ruby">katei/ruby</a>, <a href="https://wapm.io/katei/irb">katei/irb</a>: Unofficial WAPM packages</li></ul><h3>Future work ideas</h3><ul><li>Snapshot an initialized VM state as an executable Wasm file</li><li>Compress files embedded by wasi-vfs</li><li>RDoc integration to run sample code in browser</li><li>Extend RubyGems to allow linking extension library statically</li></ul><h3>Conclusion</h3><p>We have shown how we ported CRuby to WebAssembly with WASI ABI and introduced related tools. This achievement will promote the use of Ruby in more environments. Also, this feature will be maintained by Yuta Saito, a newbie committer of Ruby. Of course, any contribution is welcomed!</p><p>If no major issues are found, it will be shipped with Ruby 3.2.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4aface7d90c9" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/final-report-webassembly-wasi-support-in-ruby-4aface7d90c9">An Update on WebAssembly/WASI Support in Ruby</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Effective Techniques in Swift Runtime Library]]></title>
            <link>https://medium.com/@kateinoigakukun/effective-techniques-in-swift-runtime-library-492c6a97a475?source=rss-ced73058857c------2</link>
            <guid isPermaLink="false">https://medium.com/p/492c6a97a475</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swiftc]]></category>
            <category><![CDATA[compilers]]></category>
            <dc:creator><![CDATA[kateinoigakukun]]></dc:creator>
            <pubDate>Fri, 13 Dec 2019 05:03:54 GMT</pubDate>
            <atom:updated>2019-12-13T05:03:54.265Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://kateinoigakukun.hatenablog.com/entry/2019/12/13/140059">ja</a></p><p>This article describes some techniques used in the Swift language Runtime Library.</p><h3>What’s the Runtime library?</h3><p>Runtime Library for Swift language is named swiftCore which is required to execute Swift application. You might haven’t care about the library in most situations, but it’s linked to an executable file dynamically. Since ABI stability has been achieved since Swift 5.0, the runtime library is installed in /usr/lib/swift/libswiftCore.dylib after macOS 10.14.4.</p><p>The Swift runtime library includes some functions to implement Swift’s dynamic language features.</p><h4>The two aspects of language features</h4><p>Language features can be categorized into two by time of use.</p><ol><li>Static language features</li><li>Dynamic language features</li></ol><p>Static language features are used before execution. For example, syntax, type system and so on. On the other hand, Dynamic language feature are used while executing. For example, runtime type system, exception handling, binary compatibility and etc…</p><p>The main purpose of runtime library is to support these Dynamic language features. The features are inlinable in a binary swiftc generates, but since some features are complex, code size can be bigger. So these language features are separated in runtime libraries.</p><h4>Example: Memory allocation</h4><p>Let’s follow how Swift allocate memory as an example of runtime function.</p><p>Most of Swift’s struct can be fixed size, so compiler generates code to allocate fixed size memory.</p><p>In this example, pet variable is Pet type, so compiler can estimate the size.</p><pre>// 24 byte<br>struct Pet {<br>  let name: String // 16 byte<br>  let age: Int     // 8 byte<br>}</pre><pre>let pet = Pet(name: ..., age: ...) // malloc 24 byte</pre><p>On the other hand, there are some case that can’t be fixed size allocation.</p><p>Let’s see that class instance allocation.</p><pre>// 8 byte<br>class View {<br>  var point: (x: Float, y: Float) // 8 byte<br>  required init(...) { }</pre><pre>  func copy() -&gt; Self {<br>    return Self(...) // malloc n byte?<br>  } <br>}</pre><pre>// 24 byte<br>class TextView: View {<br>  var text: String // 16 byte<br>  required init(...) { }<br>}</pre><pre>let view: View = TextView(...)</pre><pre>// Can&#39;t determine the size of allocation by type<br>let anotherView: View = view.copy()</pre><p>In this example, the View type implements copy method which creates an instance from Self type. Self type can be the View or TextView type, but compiler cannot statically determine which type is used at runtime.</p><p>In order for such Self code to execute correctly, the instance itself have to have the instance&#39;s type info at runtime.</p><h3>Metadata</h3><p>The type information used at runtime are called Type Metadata in Swift. They are basically invisible to Swift users and not usable directly from Swift.</p><p>Type Metadata stores type sizes, function tables for dynamic dispatch, generic type parameters, pointer to Type Descriptors, and so on.</p><p>The runtime library implements dynamic language features using those Metadata.</p><p>In the memory allocation example, the type metadata embedded in the instance is extracted out and passed to the runtime function so that the instance size can be determined dynamically.</p><p>Type Descriptor has only info independent of a specific type instance, not affected by generic type parameters.</p><p>Generic type’s metadata can be created dynamically for specific type parameters at runtime. However, using the two-layers structure of Type Metadata and Type Descriptor, the same Type Descriptor can be reused for each generic type metadata.</p><h4>Background knowledge</h4><p><strong>TEXT segment</strong></p><p>First, I have to describe the layout of object file to tell you how effective the techniques are.</p><p>Here, I will write about only Mach-O format used in macOS. But there are not so much change with other binary file formats.</p><p>Basically, the executable file is separated into a TEXT and DATA segments. TEXT segment contains machine code and DATA segment contains global variables. The major difference between these segments is whether it is writable or not while running. The TEXT segment is read-only during execution, but the DATA segment is writable.</p><p>The read-only TEXT segment is very useful when using dynamic libraries or forking processes.</p><p>When loading the same dynamic library in two processes, a program loader can share the memory space allocated for the TEXT segment because they are read-only. In other words, the greater percentage of the TEXT segment in a binary, the more efficiently the memory space is used.</p><p>Swift uses effective methods to put as much metadata as possible in the TEXT segment.</p><h3>Data structure techniques</h3><p>Here is main part of this article!</p><h4>Relative Pointer</h4><p>Relative Pointer is a pointer that has an offset from the address of the pointer itself to the target address.</p><p>All pointers included in Swift metadata are in this Relative Pointer format.</p><pre>struct RelativePointer &lt;Pointee&gt; {<br>  var offset: Int32<br>  mutating func pointee ()-&gt; Pointee {<br>    withUnsafePointer (to: &amp; self) {[offset] pointer in<br>      let rawPointer = UnsafeRawPointer (pointer)<br>      let advanced = rawPointer.advanced (by: Int (offset))<br>      return advanced.assumingMemoryBound (to: Pointee.self)<br>    }.pointee<br>  }<br>}</pre><p>There are several advantages to use RelativePointer instead of normal pointers.</p><ol><li>Saving binary size</li><li>Reduce relocation on load time</li><li>Metadata get to be able to be included in the TEXT segment</li></ol><p>First, Relative Pointer uses a linker relocation system that calculates the address difference between two symbols. Since the result of this relocation is made on the premise that it fits into a signed 32 bit integer, a normal pointer consumes 64 bits, but a Relative Pointer can be represented by half that 32 bits.</p><p>Since normal pointers are relocated after launch, there are some overhead before the program starts. On the other hand, the calculation of the address difference between two symbols has been done at link time, so there is no overhead on load time.</p><p>And, by eliminating relocation record on load time, metadata can be position-independent data. In other words, like the executable program, it can be placed in the TEXT segment and share memory space with other processes.</p><p>Of course, there is an overhead of adding offsets when dereference the pointer, but Swift uses this method to take the above advantages.</p><h4>Indirect Pointer</h4><p>There are also several techniques used with Relative Pointer. One example is Indirect Pointer.</p><p>Indirect Pointer is a technique for expressing pointers via GOT and normal pointers in the same type. This uses lower bits that are not used due to alignment.</p><p>For example, a 32-bit numeric type is arranged so that the address is a multiple of 4.</p><p>In other words, the lower 2 bits of the address are always 0. Also, since the Relative Pointer itself is a 32-bit signed integer, the lower 2 bits of the difference value are also 0.</p><p>The Swift runtime library uses this low-order bit to store some state in the pointer.</p><p>Indirect Pointer uses lower 1 bit to express whether the pointer reference through GOT or not.</p><p>When the pointer references through GOT, dereference the pointer twice.</p><pre>struct RelativeIndirectablePointer&lt;Pointee&gt;<br>  /*  where alignof(Pointee) =&gt; 2 */<br>{<br>    let offsetWithIndirectFlag: Int32</pre><pre>    mutating func pointee() -&gt; Pointee {<br>        let offset: Int32<br>        if isIndirect {<br>            offset = offsetWithIndirectFlag &amp; ~isIndirectMask<br>        } else {<br>            offset = offsetWithIndirectFlag<br>        }<br>        return withUnsafePointer(to: &amp;self) { pointer -&gt; UnsafePointer&lt;Pointee&gt; in<br>            let rawPointer = UnsafeRawPointer(pointer)<br>            let advanced = rawPointer.advanced(by: Int(offset))<br>            if isIndirect {<br>                let got = advanced.assuimgMemoryBound(to: UnsafePointer&lt;Pointee&gt;.self)<br>                return got.assumingMemoryBound(to: Pointee.self)<br>            } else {<br>                return advanced.assumingMemoryBound(to: Pointee.self)<br>            }<br>        }.pointee<br>    }</pre><pre>    var isIndirect: Bool {<br>        offsetWithIndirectFlag &amp; isIndirectMask != 0<br>    }</pre><pre>    var isIndirectMask: Int32 { 0x01 }<br>}</pre><h4>Int Paired Pointer</h4><p>In addition, this pointer extracts unused lower bits as small integer.</p><pre>struct RelativeDirectPointerIntPair&lt;Pointee, IntTy: BinaryInteger&gt;<br>    /*  where alignof(Pointee) =&gt; 2 */<br>{<br>    let offsetWithInt: Int32</pre><pre>    mutating func pointee() -&gt; Pointee {<br>        let offset = offsetWithInt &amp; ~intMask<br>        return withUnsafePointer(to: &amp;self) { pointer in<br>            let rawPointer = UnsafeRawPointer(pointer)<br>            let advanced = rawPointer.advanced(by: Int(offset))<br>            return advanced.assumingMemoryBound(to: Pointee.self)<br>        }.pointee<br>    }</pre><pre>    var value: IntTy {<br>        IntTy(offsetWithInt &amp; intMask)<br>    }</pre><pre>    var intMask: Int32 {<br>        Int32(<br>            min(<br>                MemoryLayout&lt;Pointee&gt;.alignment,<br>                MemoryLayout&lt;Int32&gt;.alignment<br>            ) - 1<br>        )<br>    }<br>}<br></pre><h4>Symbolic Reference</h4><p>Symbolic Reference is used as one of the kinds of mangling.</p><p>Normally, when retrieving metadata from a mangled type name, the metadata is searched by demangled type name. However, if the target object exists in same module as referrer, it can be more efficient to reference it directly without demangling the mangled name.</p><p>The normal mangler mangles a type name into unique identifier, but symbolic reference embeds the address of the target object as a part of the mangled string.</p><p>Symbolic Reference starts with a control character to distinguish it from a normal mangled string, 0x01 to 0x0C are reserved for Symbolic Reference.</p><p>A 4-byte Relative Pointer is embedded after the control character and is decoded by the runtime library.</p><p>This mechanism makes it possible to refer to the metadata defined in the module without searching cost.</p><h4>__swift_instantiateConcreteTypeFromMangledName</h4><p>This function is used to get metadata from a type name. The argument is a {i32, i32} structure that caches the result of this function.</p><p>This argument structure can be expressed in C++ like below.</p><pre>union Input {<br>  struct {<br>    RelativePointer&lt;CChar&gt; typeName;               // 4byte<br>    int32_t                negativeTypeNameLength; // 4byte<br>  } nonCached;<br>  <br>  TypeMetadata *cached; // 8 byte<br>}</pre><p>There are two cache object states, no cache and cached, and the usage of 64-bit are changed for each state. Since the layout changes depending on the endian, assume that the system is little endian in this article.</p><p>When there is no cache, the first 32 bits are relative pointer to the type name, and the last 32 bits are the length of the type name with negative signed. Since the type name can be Symbolic Reference, null characters may be included as part of the address. Therefore, the length of the type name is necessary because the null character cannot be used as a terminator.</p><p>In the cached state, the cached absolute pointer to the metadata is stored using 64 bit.</p><p>These two states can be distinguished by looking at a cache object as a signed 64-bit integer: if it is negative, there is no cache, and if it is positive, there is cache. This is because the length of the type name is stored in the back 32 bits with a negative signed. The whole 64 bits as a signed integer always be a negative number when there is no cache.</p><p>It is more efficient to look at the whole 64 bits as a integer than simply comparing the back 32 bits.</p><h3>Summary</h3><p>In this way, the runtime library has many techniques for maximizing the use of memory space. On the other hand, most of the structures are based on Relative Pointer, so if you try to support more than 32bit pointer sizes, you need to adjust the runtime structure in many places. When making the adjustment, it is necessary to synchronize the layout of the metadata output by the compiler with runtime library. However, in the current implementation, there is no system for synchronization. It’s necessary to adjust them by hand.</p><p>Since this greatly affects the portability of Swift, we need to have some kind of system for centrally managing the metadata layout. For example, a code generator that generates a C structure for the runtime library from the LLVM IR output by the compiler might solve this problem. (Swift metadata may be difficult because of the variable-length layout of TrailingObjects.)</p><p>Although LLVM plays a big role as a foundation for compiler implementation, I have rarely seen a library that supports interface definitions between the runtime library and the compiler. If the technology of such a layer is enriched, it may become a world where more languages ​​can achieve ABI stability.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=492c6a97a475" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inside SwiftUI (How Hot-reloading implemented)]]></title>
            <link>https://medium.com/@kateinoigakukun/inside-swiftui-how-hot-reloading-implemented-ad107414bbbd?source=rss-ced73058857c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad107414bbbd</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swift-5]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift-programming]]></category>
            <dc:creator><![CDATA[kateinoigakukun]]></dc:creator>
            <pubDate>Sat, 13 Jul 2019 04:36:16 GMT</pubDate>
            <atom:updated>2019-07-13T04:54:36.966Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hot-reloading</h3><p>Hot-reloading is one of the most useful feature in SwiftUI. It brings us great benefits to develop components quickly.</p><h3>Playground live preview</h3><p>Before SwiftUI, we can develop our app with live preview of Playground.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PxFXQSoPoeX0tYMP49rckA@2x.jpeg" /></figure><p>It’s similar with SwiftUI one but there are some disadvantages.</p><p>Most serious problem is its unstable process.</p><p>Live preview in Playground works on iOS application process and Playground renders the screen. The app process is terminated and relaunched by playground each time when your code is changed. And it often fails and live preview won’t work until restarting Xcode.</p><p>In addition, it’s hard to integrate live preview of Playground to application project. If you want to use your app class for live preview, you need to create xcworkspace and link playground and your application project. And it’s necessary to build application project manually before using Playground because Playground can’t have linking dependencies.</p><h3>What Hot-reloading of SwiftUI solves</h3><p>SwiftUI solves performance and process stability of live preview. It works on iOS application process same as Playground but rarely terminates the process. This is the real <strong>live</strong> preview. It results fast response for re-rendering when you changes your code.</p><p>And you don’t need any additional configuration to use it.</p><h3>How Hot-reloading works</h3><p>This is the main points of this article.</p><p>As I mentioned above, Hot-reloading rarely terminates app processes, but it reflects what you changed in your source code.</p><p>How does this feature implemented?</p><p>As far as I investigated, core of SwiftUI preview is implemented using two system.</p><ul><li><a href="https://github.com/apple/swift-syntax">SwiftSyntax</a></li><li><a href="https://forums.swift.org/t/dynamic-method-replacement/16619">Dynamic method Replacement</a></li></ul><p>You can see some pieces of important clue in DerivedData. There is intermediate product for preview.</p><p>For example, ~/Library/Developer/Xcode/DerivedData/__YOUR_APP__/Build/Intermediates.noindex/Previews/__YOUR_APP__/Intermediates.noindex/__YOUR_APP__.build/Debug-iphonesimulator/__YOUR_APP__.build/Objects-normal/x86_64 contains some swift and dylib files which are produced by Xcode.</p><p>I can’t show whole contents of the files for NDA, but I can tell you that the swift file imports App module and use @_dynamicReplacement . This means that SwiftUI preview doesn’t simply launch your application process but launch an application which import your application module and control hot-reloading system.</p><p>When you change your source code, Xcode produces new preview-thunk file which replaces View.body method. Then Xcode build it as dynamic library and preview app load the preview-thunk library using dlopen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*YMub2oWFH-b6A047iE29Vw@2x.jpeg" /></figure><p>But View.body is always non dynamic in your source code though it’s necessary to be dynamic func when using @_dynamicReplacement. So I guess Xcode rewrite your source file to make View.body as dynamic func using SwiftSyntax or something like that.</p><p>And as you can see, preview-thunk file contains #sourceLocation statements and DSL strings which indicates where the view is located in source code. It’s used to highlight source code when you hover the view component.</p><p>You can attach preview process using lldb and I found XCPreviewKit.framework is in charge of hot-reloading.</p><p>If you’re interested, let’s try it out!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad107414bbbd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inside SwiftUI (How @State implemented)]]></title>
            <link>https://medium.com/@kateinoigakukun/inside-swiftui-how-state-implemented-92a51c0cb5f6?source=rss-ced73058857c------2</link>
            <guid isPermaLink="false">https://medium.com/p/92a51c0cb5f6</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift-5]]></category>
            <dc:creator><![CDATA[kateinoigakukun]]></dc:creator>
            <pubDate>Sat, 08 Jun 2019 23:18:31 GMT</pubDate>
            <atom:updated>2019-07-13T10:02:01.160Z</atom:updated>
            <content:encoded><![CDATA[<p>SwiftUI was announced at this <a href="http://d.hatena.ne.jp/keyword/WWDC">WWDC</a> and we’ve tried it for a few days. This <a href="http://d.hatena.ne.jp/keyword/WWDC">WWDC</a> was the moment everything changed for me.</p><p>But SwiftUI is still a private source software as well as UIKit and we need to develop applications while speculating the behavior of it.</p><p>There is some features which I felt is a mystery in SwiftUI. I investigated them and internal implementation of SwiftUI.</p><p>(This post is just a my prediction)</p><h3>@State</h3><pre>@State var value: Int</pre><p>You may write this many time while doing tutorials of SwiftUI. Do you understand how State works?</p><p>This feature uses <a href="https://github.com/apple/swift-evolution/blob/master/proposals/0258-property-delegates.md">Property Delegates</a> introduced from Swift5.1 and it allows to <a href="http://d.hatena.ne.jp/keyword/delegate">delegate</a> the implementation of getter and setter to another instance (In this case “another instance” means State).</p><p>State is a struct defined in SwiftUI using @propertyDelegate. If State is changed, View will be re-rendered.</p><p>First, let’s implement State by myself!</p><pre>@propertyDelegate<br>struct State&lt;Value&gt; {<br>    var storage: Value<br>    var value: Value {<br>        get { storage }<br>        set {<br>            storage = newValue<br>            renderView()<br>        }<br>    }<br>    init(initialValue value: Value) {<br>        self.storage = value<br>    }<br>    <br>    func renderView() {<br>        // ???<br>    }<br>}</pre><pre>struct ContentView: View {<br>    @State var text: String<br>}</pre><p>It’s almost easy to implement but I couldn’t figure out how re-render View. SwiftUI seems not re-render the all Views but some particular views whose state is modified. So I need to link ContentView and text: State&lt;String&gt; to update the view.</p><h3>Internal structure of State</h3><p>Let’s dump the state instance to investigate internal structure of State by using dump.</p><pre>struct ContentView: View {<br>    var text = State&lt;String&gt;(initialValue: &quot;Hello&quot;)<br>    <br>    init() {<br>        print(&quot;Init:&quot;)<br>        dump(text)<br>    }<br>    <br>    var body: some View {<br>        print(&quot;Body:&quot;)<br>        dump(text)<br>        return Text(&quot;Hello, world&quot;)<br>    }<br>}</pre><p>I dumped text in init and body but their outputs are different.</p><pre>Init:<br>▿ SwiftUI.State&lt;Swift.String&gt;<br>  - _value: &quot;Hello&quot;<br>  - _location: nil</pre><pre>Body:<br>▿ SwiftUI.State&lt;Swift.String&gt;<br>  - _value: &quot;Hello&quot;<br>  ▿ _location: Optional(SwiftUI.StoredLocation&lt;Swift.String&gt;)<br>    ▿ some: SwiftUI.StoredLocation&lt;Swift.String&gt; #0<br>      - super: SwiftUI.AnyLocation&lt;Swift.String&gt;<br>        - super: SwiftUI.AnyLocationBase<br>      ▿ viewGraph: Optional(SwiftUI.ViewGraph)<br>        ...</pre><p>This result shows ViewGraph appears after init but before body. It seems there is a way to inject ViewGraph into State outside of View.</p><p>Since ViewGraph is an internal type of SwiftUI, I can only speculate it but it seems ViewGraphmanages tree structure of View. If this ViewGraph can render View selectively, it&#39;s easy to imitate the re-rendering system.</p><p>Then, let’s fill the body of renderView.</p><pre>@propertyDelegate<br> struct State&lt;Value&gt; {<br>     var storage: Value<br>+    var viewGraph: ViewGraph?<br>     var value: Value {<br>         get { storage }<br>         set {<br>             storage = newValue<br>             renderView()<br>         }<br>     }<br>     init(initialValue value: Value) {<br>         self.storage = value<br>     }<br> <br>+    func setViewGraph(_ viewGraph: ViewGraph) {<br>+        self.viewGraph = viewGraph<br>+    }<br> <br>     func renderView() {<br>+        viewGraph.render()<br>     }<br> }</pre><p>It became clear that how re-render view but it’s still uncertain that how inject the ViewGraph into ContentView and make the relationship between State and View.</p><p>@State filed belongs to View but there is no way to <a href="http://d.hatena.ne.jp/keyword/access">access</a> text: State&lt;String&gt; through Viewprotocol because <a href="http://d.hatena.ne.jp/keyword/the%20field">the field</a> name is not bound by the protocol. For example, it can be easy to inject if State field is bound by the protocol as follows code. But actually, fields can be named freely.</p><pre>protocol ViewGraphInjectable {<br>    var state: State&lt;Value&gt; { get }<br>}</pre><pre>struct ContentView: View, ViewGraphInjectable {<br>    @State var state: String<br>}</pre><h3>Reflection <a href="http://d.hatena.ne.jp/keyword/API">API</a></h3><p>The only way to get fields without protocol I first thought is Mirror. It&#39;s very simple that getting fields of View using Mirror and if there is State, call setViewGraph.</p><p>But does SwiftUI really use Mirror? If Mirror is used, CustomReflectable.customMirrorshould be called and print &quot;Mirror is used!&quot;.</p><pre>struct ContentView: View, CustomReflectable {<br>    @State var text: String<br>    var customMirror: Mirror {<br>        print(&quot;Mirror is used!&quot;)<br>        return Mirror(reflecting: self)<br>    }<br>}</pre><p>But customMirror is not called. For checking, I tried to set breakpoint at swift_reflectionMirror_count which is runtime function used by Mirror but it also doesn&#39;t break.</p><p>This result indicates that SwiftUI get fields without using Mirror.</p><h3>Reflection without Mirror</h3><p>There is still a way to get fields without using Mirror. It&#39;s using metadata.</p><p><a href="https://twitter.com/kateinoigakukun/status/1109019101224001536">If you don’t know metadata, you can learn it by my try! Swift presentation.</a></p><p>Metadata has Field Descriptor which contains accessors for fields of the type. It’s possible to get fields by using it.</p><p>My various experiments result AttributeGraph.framework uses metadata internally. AttributeGraph.framework is a private framework that SwiftUI use internally for constructing ViewGraph.</p><p>You can see it by the symbols of the framework.</p><pre>$ nm /System/Library/PrivateFrameworks/AttributeGraph.framework/AttributeGraph</pre><p>There is AG::swift::metadata_visitor::visit_field in the list of symbols. i didn&#39;t analysis the whole of assembly code but the name implies that AttributeGraph use visitor pattern to parse metadata. If you set break point, it surely hit.</p><h3>Why not use Mirror</h3><p>So why is metadata used instead of Mirror? I think it&#39;s for performance.</p><p>Mirror.children is represented as [(label: String, value: Any)] to hold any type of <a href="http://d.hatena.ne.jp/keyword/value">value</a>. But Any wraps the actual <a href="http://d.hatena.ne.jp/keyword/value">value</a> and when you use it, Any is unwrapped every time. SwiftUI uses View many times and the <a href="http://d.hatena.ne.jp/keyword/overheads">overheads</a> can be critical problem.</p><p>On the other hand, Using raw pointer through Field Descriptor doesn&#39;t affect performance seriously.</p><h3>Flow to update View</h3><ol><li>Find State of View using Field Descriptor</li><li>Inject ViewGraph into State</li><li>Render View.body</li><li>State is changed</li><li>State notify the ViewGraph to update view</li><li>Re-render View.body</li></ol><p>Only <a href="http://d.hatena.ne.jp/keyword/Apple">Apple</a> knows the actual implementation. But it’s certain that AttributeGraph.framework has its own reflection system.</p><p>I said “I’m looking forward to your great libraries using metadata” in try! Swift but I had never thought <a href="http://d.hatena.ne.jp/keyword/Apple">Apple</a> do it, I think <a href="http://d.hatena.ne.jp/keyword/Apple">Apple</a> started to use metadata because ABI stability was built since Swift5. In fact, ABI stability brings us great benefits!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92a51c0cb5f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>