<?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 Brian Norman on Medium]]></title>
        <description><![CDATA[Stories by Brian Norman on Medium]]></description>
        <link>https://medium.com/@bnorm?source=rss-7f717beb3f31------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*gdaNF-z9n0995nQH.</url>
            <title>Stories by Brian Norman on Medium</title>
            <link>https://medium.com/@bnorm?source=rss-7f717beb3f31------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 12:23:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bnorm/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[Writing Your Second Kotlin Compiler Plugin, Part 1 — Project Setup]]></title>
            <link>https://bnorm.medium.com/writing-your-second-kotlin-compiler-plugin-part-1-project-setup-7b05c7d93f6c?source=rss-7f717beb3f31------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b05c7d93f6c</guid>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[plugins]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[kotlin-native]]></category>
            <dc:creator><![CDATA[Brian Norman]]></dc:creator>
            <pubDate>Sat, 21 Nov 2020 20:00:55 GMT</pubDate>
            <atom:updated>2021-01-03T15:01:04.885Z</atom:updated>
            <content:encoded><![CDATA[<h3>Writing Your Second Kotlin Compiler Plugin, Part 1 — Project Setup</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*m8ICUY6DQYmu74N0" /><figcaption>Photo by <a href="https://unsplash.com/@benst287?utm_source=medium&amp;utm_medium=referral">Ben Stern</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>At the time of writing this article, <a href="https://kotlinlang.org/docs/reference/evolution/components-stability.html">Kotlin compatibility</a> for IR backend is in Alpha status and the compiler plugin API is Experimental. As such, information contained in this article about IR and compiler plugins could be out-of-date or incorrect. If official documentation exists, please refer to it first.</blockquote><p>I’ve been wanting to write this series of blog posts for a while. Inspired By Kevin Most’s 2018 KotlinConf talk — <a href="https://www.youtube.com/watch?v=w-GMlaziIyo">Writing Your First Kotlin Compiler Plugin</a> — I wanted to show how we could write our second compiler plugin, something IR based that works on all Kotlin targets.</p><p>In this first part we will go over the project setup required to build a compiler plugin. In later parts we will explore navigating and transforming Kotlin IR.</p><ul><li><a href="https://blog.bnorm.dev/writing-your-second-compiler-plugin-part-1">Part 1 — Project Setup</a></li><li><a href="https://blog.bnorm.dev/writing-your-second-compiler-plugin-part-2">Part 2 — Inspecting Kotlin IR</a></li><li><a href="https://blog.bnorm.dev/writing-your-second-compiler-plugin-part-3">Part 3 — Navigating Kotlin IR</a></li><li><a href="https://blog.bnorm.dev/writing-your-second-compiler-plugin-part-4">Part 4 — Building Kotlin IR</a></li><li><a href="https://blog.bnorm.dev/writing-your-second-compiler-plugin-part-5">Part 5 — Transforming Kotlin IR</a></li><li><a href="https://blog.bnorm.dev/writing-your-second-compiler-plugin-part-6">Part 6 — Support Libraries, Publishing, and Integration Testing</a></li></ul><h3>Setup</h3><p>There are a number pieces to a Kotlin compiler plugin. At least 3 modules are required if you want to support all Kotlin targets:</p><ul><li>Gradle plugin which adds your plugin to Kotlin compiler classpath,</li><li>Kotlin compiler plugin for non-native Kotlin platforms,</li><li>Kotlin compiler plugin for Kotlin/Native platform,</li></ul><p>Kotlin/Native requires a separate compiler plugin because certain classes used by the Kotlin compiler have a different package on Kotlin/Native. We’ll explore this oddity more in-depth later.</p><h3>Gradle Plugin</h3><p>The <a href="https://github.com/bnorm/kotlin-ir-plugin-template/tree/medium-part1/kotlin-ir-plugin-gradle">Gradle plugin</a> part of a Kotlin compiler plugin project is responsible for defining a few things:</p><ul><li>Artifact coordinates of the Kotlin compiler plugin,</li><li>ID string of the Kotlin compiler plugin,</li><li>Translation of Gradle configuration to command line options.</li></ul><p>The artifact coordinates are used to download the correct compiler plugin artifact from MavenCentral (or other location) to include on the compiler plugin classpath. The compiler plugin ID string is used to separate command line options by plugin to avoid conflicting options between multiple plugins.</p><p>The artifact coordinates and ID we’ll <a href="https://github.com/bnorm/kotlin-ir-plugin-template/blob/medium-part1/kotlin-ir-plugin-gradle/build.gradle.kts">define with Gradle</a> using the <a href="https://github.com/gmazzo/gradle-buildconfig-plugin">buildconfig</a> plugin. Since the artifact coordinates — group, name, and version — are already defined by Gradle and the Kotlin compiler plugin ID will be the Gradle plugin ID, this will make things consistent when everything is published.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1463c08189dd7cf0d85de497dcbe237a/href">https://medium.com/media/1463c08189dd7cf0d85de497dcbe237a/href</a></iframe><p>These buildconfig values are used by a <a href="https://github.com/bnorm/kotlin-ir-plugin-template/blob/medium-part1/kotlin-ir-plugin-gradle/src/main/kotlin/com/bnorm/template/TemplateGradlePlugin.kt">KotlinCompilerPluginSupportPlugin</a> implementation which is responsible for bridging between Gradle and the Kotlin compiler.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c202d9d1b005e61e6b0938b0099f88f8/href">https://medium.com/media/c202d9d1b005e61e6b0938b0099f88f8/href</a></iframe><p>Any <a href="https://github.com/bnorm/kotlin-ir-plugin-template/blob/medium-part1/kotlin-ir-plugin-gradle/src/main/kotlin/com/bnorm/template/TemplateGradleExtension.kt">custom Gradle properties</a> defined in a <a href="https://docs.gradle.org/current/userguide/custom_plugins.html">Gradle extension</a> are translated to Kotlin compiler arguments using the applyToCompilation function. These will be read by our Kotlin compiler plugin which is next!</p><h3>Kotlin Plugin</h3><p>A Kotlin compiler plugin starts with a ComponentRegistrar and CommandLineProcessor implementation. Both of these classes are loaded by the Kotlin compiler using a <a href="https://docs.oracle.com/javase/8/docs/api/java/util/ServiceLoader.html">ServiceLoader</a> so we will use the <a href="https://github.com/google/auto/tree/master/service">auto-service</a> annotation processer to automatically generate the required files.</p><p>The <a href="https://github.com/bnorm/kotlin-ir-plugin-template/blob/medium-part1/kotlin-ir-plugin/src/main/kotlin/com/bnorm/template/TemplateCommandLineProcessor.kt">CommandLineProcessor</a> is pretty easy to understand: It defines the Kotlin compiler plugin ID string (same as in Gradle plugin) and expected command line options. The processor is also responsible for parsing the command line options of the plugin and placing them in a CompilerConfiguration. It should read and process the same values defined by the Gradle plugin.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0ba254481e0bacf959f0667a5bf680b/href">https://medium.com/media/d0ba254481e0bacf959f0667a5bf680b/href</a></iframe><p>The <a href="https://github.com/bnorm/kotlin-ir-plugin-template/blob/medium-part1/kotlin-ir-plugin/src/main/kotlin/com/bnorm/template/TemplateComponentRegistrar.kt">ComponentRegistrar</a> is where the actual work of a compiler plugin actually begins. The registrar is responsible for registering extension components with the project being compiled. There are a number of extension points currently available in the Kotlin compiler, but the one we will be focusing on is IrGenerationExtension, which allows for navigating and transforming Kotlin IR.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36ab6dacc8cb65bdd13ef4bd8df85349/href">https://medium.com/media/36ab6dacc8cb65bdd13ef4bd8df85349/href</a></iframe><p>An instance of <a href="https://github.com/bnorm/kotlin-ir-plugin-template/blob/medium-part1/kotlin-ir-plugin/src/main/kotlin/com/bnorm/template/TemplateIrGenerationExtension.kt">IrGenerationExtension</a> can be created and registered within a ComponentRegistrar. This instance will be called during compilation when IR code needs to be generated (or transformed). The entry point for this extension provides an IrModuleFragment and IrPluginContext which provide everything we need to navigate and transform the module IR code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b0799cc30197f3491998cc297df63b8/href">https://medium.com/media/3b0799cc30197f3491998cc297df63b8/href</a></iframe><p>We’ll be going more into how to use the provided IrModuleFragment and IrPluginContext values in the next parts of this series. But next we need to talk about how Kotlin/Native is different.</p><h3>Kotlin Plugin — Native</h3><p>You may have noticed that the Gradle plugin defines a separate coordinate for the Kotlin/Native compiler plugin artifact. This is because Kotlin/Native compiler plugins are compiled with a different dependency than other compiler plugins. <a href="https://github.com/bnorm/kotlin-ir-plugin-template/blob/medium-part1/kotlin-ir-plugin-native/build.gradle.kts">Kotlin/Native compiler plugins</a> use the org.jetbrains.kotlin:kotlin-compiler artifact while <a href="https://github.com/bnorm/kotlin-ir-plugin-template/blob/medium-part1/kotlin-ir-plugin/build.gradle.kts">plugins for every other platform</a> use the org.jetbrains.kotlin:kotlin-compiler-embedded artifact.</p><p>The only difference I have found between these artifacts is the embedded artifact shadows some classes so their package is different. Other then that, the code between these plugins can be exactly the same. To share code, I use <a href="https://github.com/bnorm/kotlin-ir-plugin-template/blob/medium-part1/kotlin-ir-plugin-native/build.gradle.kts#L16-L27">Gradle to copy the code</a> of the non-Kotlin/Native compiler plugin over to the Kotlin/Native compiler plugin module and change the import statements as required.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42c176ff0ce2946ec55174870bb38ac9/href">https://medium.com/media/42c176ff0ce2946ec55174870bb38ac9/href</a></iframe><p>This isn’t ideal, but I’m sure this oddity will be resolved as Kotlin/Native and compiler plugins mature.</p><h3>Kotlin Plugin — Testing</h3><p>Testing Kotlin/JVM compiler plugins is really easy thanks to the <a href="https://github.com/tschuchortdev/kotlin-compile-testing">kotlin-compile-testing</a> library! This library allows you to <a href="https://github.com/bnorm/kotlin-ir-plugin-template/blob/medium-part1/kotlin-ir-plugin/src/test/kotlin/com/bnorm/template/IrPluginTest.kt">compile Kotlin source strings</a> with your ComponentRegistrar in tests which makes debugging easy. The resulting compiled files can even be loaded via a ClassLoader if you want to execute them which we will discuss later.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1978b9980490ff80ab5ca8b30310a3a7/href">https://medium.com/media/1978b9980490ff80ab5ca8b30310a3a7/href</a></iframe><p>If you execute the tests you should see the following output present in the log.</p><pre>i: Argument &#39;string&#39; = Hello, World!<br>i: Argument &#39;file&#39; = file.txt</pre><p>And with that, congrats! You now know how to set up a Kotlin compiler plugin project and are ready to start navigating and transforming IR code! If you want to avoid the manual work of setting all of this up, you can use the GitHub template I created when writing this article.</p><p><a href="https://github.com/bnorm/kotlin-ir-plugin-template">bnorm/kotlin-ir-plugin-template</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b05c7d93f6c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Soft Assertion with kotlin-power-assert]]></title>
            <link>https://bnorm.medium.com/soft-assertion-with-kotlin-power-assert-4b61fa763b61?source=rss-7f717beb3f31------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b61fa763b61</guid>
            <dc:creator><![CDATA[Brian Norman]]></dc:creator>
            <pubDate>Tue, 29 Sep 2020 01:46:40 GMT</pubDate>
            <atom:updated>2020-09-29T01:46:40.021Z</atom:updated>
            <content:encoded><![CDATA[<p>The <a href="https://github.com/bnorm/kotlin-power-assert">kotlin-power-assert</a> Kotlin compiler plugin is great (I may be biased as its author) as it enables diagramming of assert function calls. As the plugin grows and matures I’m discovering new use cases. One I wanted to try is the idea of soft assertions which <a href="https://joel-costigliola.github.io/assertj/core/api/org/assertj/core/api/SoftAssertions.html">many</a> <a href="https://www.javadoc.io/doc/org.testng/testng/6.8.8/org/testng/asserts/SoftAssert.html">assertion</a> <a href="http://spockframework.org/spock/docs/1.2-RC3/all_in_one.html#_using_code_verifyall_code_to_assert_multiple_expectations_together">libraries</a> <a href="https://truth.dev/api/latest/com/google/common/truth/Expect.html">support</a>. Let’s take a look quickly at an example of verifyAll from the <a href="http://spockframework.org/">Spock Framework</a>.</p><pre>def &quot;offered PC matches preferred configuration&quot;() {<br>  when:<br>  def pc = shop.buyPc()<br><br>  then:<br>  verifyAll(pc) {<br>    vendor == &quot;Sunny&quot;<br>    clockRate &gt;= 2333<br>    ram &gt;= 406<br>    os == &quot;Linux&quot;<br>  }<br>}</pre><p>The example above is straight from the documentation and demonstrates verifying multiple properties of a class at a single time. The nice thing here is that all failures will be reported, not just the first one. This avoids needing to run the test multiple times, discovering the next failed property after fixing the previous failed property. The verifyAll function gathers each failed assertion and only throws an exception when the scope closes.</p><h3>Complex Boolean Expressions</h3><p>kotlin-power-assert allows complex boolean expressions to be diagramed but this requires support for <a href="https://en.wikipedia.org/wiki/Short-circuit_evaluation">short-circuiting</a>. This is because smart casting allows some interesting boolean expressions like the following.</p><pre>assert(jane != null &amp;&amp; jane.firstName == &quot;Jane&quot;)</pre><pre># Example failure<br>java.lang.AssertionError: Assertion failed<br>assert(jane != null &amp;&amp; jane.firstName == &quot;Jane&quot;)<br>       |    |<br>       |    false<br>       null</pre><p>So if multiple properties of a class are included as a single boolean expression, kotlin-power-assert will only diagram up to the first failure.</p><pre>assert(jane.firstName == &quot;Jane&quot; &amp;&amp; jane.lastName == &quot;Doe&quot;)</pre><pre># Example failure<br>assert(jane.firstName == &quot;Jane&quot; &amp;&amp; jane.lastName == &quot;Doe&quot;)<br>       |    |         |<br>       |    |         false<br>       |    John<br>       Person@765cb1b3</pre><p>If the Person class had a better toString() function or was a data class that might solve this specific problem, but this exposes a general problem that needs solving.</p><h3>Scoped Assertion</h3><p>Creating something similar to Spock’s verifyAll with Kotlin and the kotlin-power-assert compiler plugin is very simple and only takes a few dozen lines of code. Kotlin supports the same higher-order function syntax as Groovy and kotlin-power-assert adds diagrammed assertion support. Here’s all it takes:</p><pre>typealias LazyMessage = () -&gt; Any<br><br>interface AssertScope {<br>  fun assert(assertion: Boolean, lazyMessage: LazyMessage? = null)<br>}<br><br>private class SoftAssertScope : AssertScope {<br>  private val assertions = mutableListOf&lt;Throwable&gt;()<br><br>  override fun assert(assertion: Boolean, lazyMessage: LazyMessage?) {<br>    if (!assertion) {<br>      assertions.add(AssertionError(lazyMessage?.invoke()?.toString()))<br>    }<br>  }<br><br>  fun close(exception: Throwable? = null) {<br>    if (assertions.isNotEmpty()) {<br>      val base = exception ?: AssertionError(&quot;Multiple failed assertions&quot;)<br>      for (assertion in assertions) {<br>        base.addSuppressed(assertion)<br>      }<br>      throw base<br>    }<br>  }<br>}<br><br>fun &lt;R&gt; assertSoftly(block: AssertScope.() -&gt; R): R {<strong><br>  </strong>val scope = SoftAssertScope()<br>  val result = runCatching <strong>{ </strong>scope.block() <strong>}<br>  </strong>scope.close(result.exceptionOrNull())<br>  return result.getOrThrow()<br>}</pre><p>A <a href="https://github.com/bnorm/kotlin-power-assert/blob/v0.5.3/sample/src/commonMain/kotlin/com/bnorm/power/AssertScope.kt">sample</a> of this was added to the kotlin-power-assert library in version 0.5.3 which fixed a bug when transforming member functions. Now you can write the following in your test!</p><pre>val jane: Person = ...<br>assertSoftly {<br>  assert(jane.firstName == &quot;Jane&quot;)<br>  assert(jane.lastName == &quot;Doe&quot;)<br>}</pre><p>Soft assertions can help pin point all failures with a single test run. kotlin-power-assert can help diagram those failures and make them easier to triage. Give them both a try and see how they work for you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b61fa763b61" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Functional Components with Kotlin/JS]]></title>
            <link>https://bnorm.medium.com/react-functional-components-with-kotlin-js-26fdda961ddb?source=rss-7f717beb3f31------2</link>
            <guid isPermaLink="false">https://medium.com/p/26fdda961ddb</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-js]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Brian Norman]]></dc:creator>
            <pubDate>Sat, 26 Sep 2020 02:01:55 GMT</pubDate>
            <atom:updated>2020-09-26T02:07:06.475Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve been playing with Kotlin/JS and React lately. I’ve been wanting to learn more about frontend development, and since I’m very familiar with Kotlin, thought Kotlin/JS and React would be a good entry point.</p><h3>React</h3><p>I’m not even going to pretend to be able to explain React. You should go read the <a href="https://reactjs.org/">official documentation</a> if you want to learn more. A quick primer: React enables the creation of <strong>Components</strong> which are reuseable and composable and built from other components and standard HTML tags using a XML-like syntax called JSX. Components can be stateful and take properties as inputs. Here’s an example component right from the home page of React:</p><pre>class HelloMessage extends React.Component {<br>  render() {<br>    return (<br>      &lt;div&gt;<br>        Hello, {this.props.name}<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><h3>React Functional Components</h3><p>More modern React uses <a href="https://reactjs.org/docs/components-and-props.html#function-and-class-components"><strong>Functional Components</strong></a>. These are just standard JavaScript functions which accept a props parameter and return a React element. Here is the functional version of the previous component example.</p><pre>function Welcome(props) {<br>  return &lt;div&gt;Hello, {props.name}&lt;/div&gt;;<br>}</pre><h3>Kotlin/JS and React</h3><p>Using the <a href="https://github.com/JetBrains/kotlin-wrappers">wrappers for React</a> provided by JetBrains, you can define React components in Kotlin/JS. Because Kotlin is a type safe language, there is a bit more boiler plate required to reproduce the original example.</p><pre>external interface WelcomeProps : RProps {<br>    var name: String<br>}<br><br>class Welcome: RComponent&lt;WelcomeProps, RState&gt;() {<br>     override fun RBuilder.render() {<br>        div {<br>            +&quot;Hello, ${props.name}&quot;<br>        }<br>    }<br>}</pre><pre>fun RBuilder.welcome(name: String) = child(Welcome::class) {<br>    attrs.name = name<br>}</pre><h3>Kotlin/JS and React Functional Components</h3><p>Also provided by the Kotlin wrappers for React is a functional component builder. Again, because of type safety, there is some builder plate and it is both similar and different from the class version of the component.</p><pre>external interface WelcomeProps : RProps {<br>    var name: String<br>}<br><br>val WELCOME = rFunction&lt;WelcomeProps&gt;(&quot;Welcome&quot;) { props -&gt; <br>    div {<br>        +&quot;Hello, ${props.name}&quot;<br>    }<br>}</pre><pre>fun RBuilder.Welcome(name: String) = WELCOME.invoke {<br>    attrs.name = name<br>}</pre><h3>Kotlin/JS React Compiler Plugin</h3><p>I’ve got some background with <a href="https://medium.com/@bnorm/exploring-kotlin-ir-bed8df167c23">Kotlin compiler plugins</a>, so I looked at the boiler plate required to build functional components in Kotlin/JS and knew it could be better. The most optimal reduction of boiler plate might look something like the following.</p><pre>fun RBuilder.Welcome(name: String) {<br>    div {<br>        +&quot;Hello, $name&quot;<br>    }<br>}</pre><p>How do we get this function to be a valid Kotlin/JS React functional component? Some things to notice:</p><ol><li>The parameters to the function are exactly the properties of the WelcomeProps interface.</li><li>The body of the function is exactly the lambda used for the call to rFunction.</li></ol><h3>Kotlin React Function Compiler Plugin</h3><p>With the new Kotlin/JS compiler plugin <a href="https://github.com/bnorm/kotlin-react-function">kotlin-react-function</a> for React functional components, the above function can be converted using a single annotation @RFunction.</p><pre>@RFunction<br>fun RBuilder.Welcome(name: String) {<br>    div {<br>        +&quot;Hello, $name&quot;<br>    }<br>}</pre><p>When the annotation is added to the function along with the kotlin-react-function Gradle plugin, the boiler plate required is automatically generated and the function is transformed to use the boiler plate.</p><p>Looking back at the JavaScript version of this functional component, this is very similar and reduces the boilerplate required significantly.</p><p>My Kotlin/JS and React journey is just beginning, but hopefully this compiler plugin will make creating React functional components in Kotlin/JS much easier for me and everyone else!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26fdda961ddb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin OptIn Annotation as a Scoping Tool]]></title>
            <link>https://bnorm.medium.com/kotlin-optin-annotation-as-a-scoping-tool-59a50ee64338?source=rss-7f717beb3f31------2</link>
            <guid isPermaLink="false">https://medium.com/p/59a50ee64338</guid>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Brian Norman]]></dc:creator>
            <pubDate>Sat, 23 May 2020 21:11:54 GMT</pubDate>
            <atom:updated>2020-05-23T21:11:54.409Z</atom:updated>
            <content:encoded><![CDATA[<p>I like to follow the <a href="https://github.com/Kotlin/kotlinx.coroutines">kotlinx.coroutines</a> library closely on GitHub. Not really because I have anything to contribute, but because there is so much to learn!</p><p>Take it’s use of the <a href="https://kotlinlang.org/docs/reference/opt-in-requirements.html">RequiresOptIn </a>annotation (previously Experimental in Kotlin pre-1.3.70). There are some really nice ways this annotation is used, especially when introducing new library features like Flow and letting you know that parts of it are still experimental with the <a href="https://github.com/Kotlin/kotlinx.coroutines/blob/1eeed509abbe8e542124841ce14884202463460b/kotlinx-coroutines-core/common/src/Annotations.kt#L40">FlowPreview</a> annotation.</p><p>However, the one that sticks out to me is the <a href="https://github.com/Kotlin/kotlinx.coroutines/blob/1eeed509abbe8e542124841ce14884202463460b/kotlinx-coroutines-core/common/src/Annotations.kt#L66">InternalCoroutinesApi</a> annotation. This annotation marks APIs that have to be public but should not be used outside the library and will result in a compiler error if the using code is not marked with @OptIn(InternalCoroutinesApi::class). This is used to <strong>scope</strong> those APIs!</p><p>How else can this be used to scope access? Let’s take inspiration from <a href="https://jakewharton.com/inline-classes-make-great-database-ids/">using inline classes for database IDs</a> and make an inline class to represent a password.</p><pre>inline class Password(<br>  private val value: String<br>) {<br>  override fun toString(): String = &quot;*****&quot;<br>}</pre><p>This gives us some protection when dealing with passwords, making sure you don’t pass a password to a function not expecting one. But what about the function that needs to hash the password before persisting? Or the function that needs to compare that password against an existing password hash? Some things still need access to the raw password. Enter RequiresOptIn!</p><pre>@RequiresOptIn(level = RequiresOptIn.Level.ERROR)<br>annotation class UnsafePassword<br><br>inline class Password(<br>  @property:UnsafePassword<br>  val value: String<br>) {<br>  override fun toString(): String = &quot;*****&quot;<br>}</pre><p>Now any code that tries to access value will get a compiler error unless it uses @OptIn(UnsafePassword::class)! The raw password has been <strong>scoped </strong>to only those functions that need it, and made that scope even more explicit!</p><pre>@OptIn(UnsafePassword::class)<br>fun hash(password: Password): String<br>  = // password.value is no longer an error</pre><p>Bonus, you can now search for usages of UnsafePassword to find everywhere that is dealing with a raw password.</p><p><em>Disclaimer: I’m not a security expert. This password example is meant to be just that, an example. Make sure you are always following best practices when dealing with sensitive information.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59a50ee64338" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Kotlin IR]]></title>
            <link>https://bnorm.medium.com/exploring-kotlin-ir-bed8df167c23?source=rss-7f717beb3f31------2</link>
            <guid isPermaLink="false">https://medium.com/p/bed8df167c23</guid>
            <dc:creator><![CDATA[Brian Norman]]></dc:creator>
            <pubDate>Mon, 10 Feb 2020 17:57:49 GMT</pubDate>
            <atom:updated>2020-02-10T17:57:49.506Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>At the time of writing this article, Kotlin IR is experimental. As such, information contained in this article about IR could be out-of-date or incorrect. If official documentation for Kotlin IR exists, please refer to it first.</blockquote><p>Ever since learning about them, I’ve been very interested in Kotlin compiler plugins. Even the <a href="https://github.com/JetBrains/kotlin/tree/master/plugins">limited list of official supported plugins</a> hint at the potential available. A plugin like kotlin-serialization shows how it is possible to generate code for <a href="https://en.wikipedia.org/wiki/Marshalling_(computer_science)">marshalling</a> a Kotlin class. A plugin like allopen shows it’s possible to transform classes to be non-final at runtime. It’s Java annotation processing; but with more power.</p><p>My adventure into this world started a few months ago when I once again looked longingly at a Groovy language feature called <a href="https://groovy-lang.org/testing.html#_power_assertions">Power Assertions</a>. If you are unfamiliar with this language feature, <a href="https://dontmindthelanguage.wordpress.com/2009/12/11/groovy-1-7-power-assert/">it was original developed by the Spock testing framework, and introduced in Groovy 1.7</a>. It’s goal is to show the value of everything involved in the assertion which failed.</p><pre>a = 10<br>b = 9<br> <br>assert 91 == a * b<br><br>// Output:             <br>//<br>// Exception thrown<br>//<br>// Assertion failed: <br>//<br>// assert 91 == a * b<br>//           |  | | |<br>//           |  10| 9<br>//           |    90<br>//           false<br>//<br>//     at ConsoleScript2.run(ConsoleScript2:4)</pre><p>This context as to why the assertion failed is indeed something to desire. Many libraries in the JVM ecosystem (AssertJ, Hamcrest, Truth, Kluent, Atrium, Strikt, etc) provide meaningful error messages but they are usually limited to the known types of the library. Many of these libraries have ways to provide custom assertion extensions so you can provide something meaningful when testing your own classes. But I’ve always seen this as boiler plate and found it tedious to write.</p><h3>Introducing: kotlin-power-assert</h3><p><a href="https://github.com/bnorm/kotlin-power-assert">kotlin-power-assert</a> is a Kotlin compiler plugin which finds every call to kotlin.assert(...) and transforms it to include all the expressions in the assertion in the error message.</p><pre>val hello = &quot;Hello&quot;<br>assert(hello.length == &quot;World&quot;.substring(1, 4).length) { &quot;Incorrect length&quot; }</pre><pre>// Output:<br>//<br>// java.lang.AssertionError: Incorrect length<br>// assert(hello.length == &quot;World&quot;.substring(1, 4).length)<br>//        |     |      |          |               |<br>//        |     |      |          |               3<br>//        |     |      |          orl<br>//        |     |      false<br>//        |     5<br>//        Hello<br>//         at &lt;stacktrace&gt;</pre><p>This is done via an IrGenerationExtension which is a specific kind of extension to the Kotlin compiler. From this extension point, you are given access to the IR layout of the file being compiled and are allowed to transform it before the Kotlin compiler continues to the next phase of compilation.</p><p>If you want to learn more about the architecture of Kotlin compiler plugins I highly recommend watching <a href="https://www.youtube.com/watch?v=w-GMlaziIyo">Kevin Most’s presentation from KotlinConf 2018</a> which goes into details not covered here.</p><h3>Kotlin IR</h3><p>Kotlin IR, or Kotlin Intermediate Representation, is the new internal representation used by the Kotlin compiler when it parses Kotlin source files. It uses this representation to than perform a series of <a href="https://github.com/JetBrains/kotlin/tree/master/compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/lower">“lowerings”</a> which transform the code.</p><p>These lowering operations include <a href="https://github.com/JetBrains/kotlin/blob/master/compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/lower/TailrecLowering.kt">tailrec transformation</a>, <a href="https://github.com/JetBrains/kotlin/blob/master/compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/lower/StringConcatenationLowering.kt">string concatenation to StringBuilder</a>, <a href="https://github.com/JetBrains/kotlin/blob/master/compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/lower/AbstractSuspendFunctionsLowering.kt">suspend function transformation</a>, and <a href="https://github.com/JetBrains/kotlin/blob/master/compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/lower/loops/ForLoopsLowering.kt">for-loop optimizations</a>. These lowerings are then performed in phases, with more general transformations performed first. Once all lowerings are complete, each compiler backend, one for each supported platform (JVM, JS, or Native), takes the IR and translates it into the platform specific representation.</p><p>By using an intermediate representation, the Kotlin compiler is able to share lowerings across all the compiler backends. It also allows developers to write a single compiler plugin which will work on all platforms. Otherwise a plugin which wants to support all Kotlin platforms would need to write a transformation for each platform specific representation.</p><h3>Transfroming Kotlin IR</h3><p>Kotlin IR is represented as a tree of elements. To navigate, you can use an IrElementVisitor which will visit each IrElement. If you want to transform the code, you can use an IrElementTransformer which will allow you to manipulate the elements visited and even return a completely different element in place of the one being visited. To create an IR tree of your own, you can use the <a href="https://github.com/JetBrains/kotlin/tree/master/compiler/ir/ir.tree/src/org/jetbrains/kotlin/ir/builders">many builder functions</a> available.</p><p>As Kotlin IR is still experimental, only a few of the official compiler plugins have been converted to also support IR. However, many lowerings are currently available which provide good examples to explore.</p><h3>Transforming assert() Calls</h3><p>So with a little background on Kotlin IR, how is the assertion function transformed to include additional information?</p><p>It all starts with an IrElementTransformer which navigates the IR tree and visits each instance of an IrCall. This represents every call to any function. If the function being called is assert(), then the call needs to be transformed.</p><p>Next, the IR tree is navigated from that point, finding every instance of an IrExpression. An expression is anything that can return a value: function calls, variable/field access, constants, if/when expressions, etc.</p><p>Then every IrExpression found is moved to a temporary variable (via irTemporary builder) and replaced with an access expression to the temporary variable (via irGet builder). This allows the error message to access the same temporary variables used by the assertion condition.</p><p>Once the assertion expressions are transformed, the assertion call is replaced with a series of if statements (using irIfThen builder) and throw statements (using irThrow builder). The constructor call to AssertionError can then include all the temporary variables, formatted appropriately and include the source code of the original assert() call.</p><p>Finally, to get the source code for the original assert() call, start with getting the source code for the entire file. This can be accessed through visiting the IrFile and using the path extension function to get the path to the source file being compiled. From there, source code range information can be retrieved from each IrElement using the fileEntry from the parent IrFile.</p><pre>override fun visitFile(declaration: IrFile): IrFile {<br>  file = declaration<br>  fileSource = File(declaration.path).readText()<br>  ...<br>}<br><br>override fun visitCall(expression: IrCall): IrExpression {<br>  val callSource = fileSource.substring(expression.startOffset, expression.endOffset)<br>  val callIndent = file.fileEntry.getSourceRangeInfo(expression.startOffset, expression.endOffset).startColumnNumber<br>  ...<br>}</pre><p>Putting all this information together, the expression temporary variables are sorted based on start column and included in the assertion message string with some “fancy” formatting (using irConcat and irString builders).</p><p>Unfortunately, in reality it is more complicated that what was just described. Boolean expressions which include &amp;&amp; or || tend to make things more complicated due to <a href="https://en.wikipedia.org/wiki/Short-circuit_evaluation">short-circuiting</a>. But hopefully this simplification helps you understand what is going on behind the scenes.</p><h3>Writing Your Own Plugin</h3><p>If you have an idea for a Kotlin compiler plugin, the first thing I recommend is to use the fantastic library <a href="https://github.com/tschuchortdev/kotlin-compile-testing">kotlin-compile-testing</a>. This library will allow you to compile code in unit tests and to even load the compiled code so you can test it’s behavior.</p><p>The second thing I recommend is to set your expectations correctly. As Kotlin IR is still experimental, there are still a number of things which do not work well. It could be a while before Kotlin IR is the default mode for the Kotlin compiler. Make sure you are comfortable with these risks before using or writing a compiler plugin based on IR.</p><p>And finally, clone and load up the Kotlin git repository. Being able to navigate through all the IR code and lowerings was incredible useful to find examples on how to perform different transformations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bed8df167c23" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Unused” Type Parameters on Kotlin Inline Classes]]></title>
            <link>https://bnorm.medium.com/unused-type-parameters-on-kotlin-inline-classes-e007710e9382?source=rss-7f717beb3f31------2</link>
            <guid isPermaLink="false">https://medium.com/p/e007710e9382</guid>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Brian Norman]]></dc:creator>
            <pubDate>Mon, 29 Jul 2019 16:12:57 GMT</pubDate>
            <atom:updated>2019-07-29T16:16:40.806Z</atom:updated>
            <content:encoded><![CDATA[<p>Kotlin introduced inline classes in 1.3 as an experimental feature. They allow wrapping of a single value which is inlined at compile time. You can use them for <a href="https://jakewharton.com/inline-classes-make-great-database-ids/">ID classes</a> and also for <a href="https://github.com/michaelbull/kotlin-inline-logger">logging implementations</a>. They are a great feature with some very interesting use cases.</p><p>“Unused” type parameters can actually be very useful on inline classes. Take the following as an example.</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttps%2Fpl.kotl.in%2Fo3utJk1Zj%3Ffrom%3D1%26to%3D2%26readOnly%3Dtrue&amp;src=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttps%2Fpl.kotl.in%2Fo3utJk1Zj%3Ffrom%3D1%26to%3D2%26readOnly%3Dtrue&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=kotl" width="800" height="300" frameborder="0" scrolling="no"><a href="https://medium.com/media/d74917f3c02e448dcb793b358c8d9af4/href">https://medium.com/media/d74917f3c02e448dcb793b358c8d9af4/href</a></iframe><p>The above defines a Key inline class which has an associated type parameter and inlines to a String. The Kotlin compiler claims this type paramter is unused but it can actually be used in function signatures.</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttps%2Fpl.kotl.in%2Fo3utJk1Zj%3Ffrom%3D4%26to%3D12%26readOnly%3Dtrue&amp;src=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttps%2Fpl.kotl.in%2Fo3utJk1Zj%3Ffrom%3D4%26to%3D12%26readOnly%3Dtrue&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=kotl" width="800" height="300" frameborder="0" scrolling="no"><a href="https://medium.com/media/33b92919f3a5613bc1307608b3f28bda/href">https://medium.com/media/33b92919f3a5613bc1307608b3f28bda/href</a></iframe><p>The above Context class is type safe at compile time but all the type parameter information is erased at runtime. Create Keys for all the information you want to store in Context and getting and setting will be type safe. Feel free to play around with the following example.</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttps%2Fpl.kotl.in%2Fo3utJk1Zj%3Ffrom%3D14%26to%3D37&amp;src=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttps%2Fpl.kotl.in%2Fo3utJk1Zj%3Ffrom%3D14%26to%3D37&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=kotl" width="800" height="300" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf983b95a1f4cbd742416c444be92ec6/href">https://medium.com/media/bf983b95a1f4cbd742416c444be92ec6/href</a></iframe><p>I’m interested to see others’ ideas on how this can be used so please share them in the comments! Enjoy!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e007710e9382" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>