<?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 Herme García on Medium]]></title>
        <description><![CDATA[Stories by Herme García on Medium]]></description>
        <link>https://medium.com/@HermeG?source=rss-59a529e44a03------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*cowvZBrVQ9IB4kCtKVWJYA@2x.jpeg</url>
            <title>Stories by Herme García on Medium</title>
            <link>https://medium.com/@HermeG?source=rss-59a529e44a03------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 07:30:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@HermeG/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[A runtime inside Rust’s type system]]></title>
            <link>https://towardsdev.com/a-runtime-inside-rusts-type-system-3b5023257735?source=rss-59a529e44a03------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b5023257735</guid>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[formal-methods]]></category>
            <category><![CDATA[type-systems]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[rust-programming-language]]></category>
            <dc:creator><![CDATA[Herme García]]></dc:creator>
            <pubDate>Fri, 06 Jan 2023 17:43:19 GMT</pubDate>
            <atom:updated>2023-01-11T14:21:55.960Z</atom:updated>
            <content:encoded><![CDATA[<p>A lot of things can be learned about a programming language by using it, even more by implementing tools for it. In this post we are going to dive into the Rust type system to find how powerful it can be. While implementing what may be one of the <strong>weirdest</strong> compilers out there.</p><h4>The programming language</h4><p>Before implementing a compiler we need to define the programming language that will be fed into it, in this case the language could not be simpler. L<em>ogica </em>is a language designed for this post and with it simple boolean expressions can be written.</p><pre>Bool &lt;- {True, False}<br>Nat &lt;- {0, 1, 2, ..}<br>program = Expression<br>Expression = <br>  | $Nat<br>  | Bool<br>  | (Not Expression)<br>  | (And Expression Expression)<br>  | (Or Expression Expression)</pre><p>A program in <em>logica</em> is just a boolean expression, being the simplest program either the constant <em>True</em> or the constant <em>False. </em>More<em> </em>complex programs can be formed by applying the boolean operators <em>And</em>, <em>Or</em> and <em>Not</em> to other expressions.</p><p>Additionally placeholders can be used to express that a boolean value must be provided by the user before evaluating the expression. The input values are called the <em>context </em>of the program and a <em>logica</em> developer can access them as if they were stored in a 0-indexed array.</p><p>As an example, the following <em>logica</em> program computes the implication of two user given values:</p><pre>(Or (Not $0) (And $0 $1))</pre><h4>A weird compiler</h4><p>Even though it is a weird compiler that is not a symptom of its complexity, there are only two stages in the compilation process of <em>logica</em>, parsing and translation<em>. </em>As always, the compiler is implemented in <a href="https://www.rust-lang.org/">Rust</a>.</p><p>This post focuses on the translation stage of the compiler, where a <em>logica</em> program is compiled into Rust’s type system. Yes that is not a typo, this compiler is going to translate a given <em>logica</em> program into a Rust program where the type of the <em>main</em> function is the result of evaluating the boolean expression. The following code is an schema of the expected output.</p><pre>/*<br>   Header, used to define the machinery needed to achieve our goal.<br>*/<br>fn main() {<br>   // Some expression whose type is the result of the logica program <br>}</pre><p>Since the main function must return the unit type when the output of the compiler program is given to <a href="https://doc.rust-lang.org/rustc/what-is-rustc.html"><em>rustc</em></a> the following compilation error will be produced as output:</p><pre>...<br>...<br>| <br>expected `()`, found struct `X`</pre><p>Where <em>X</em> will be replaced by the result of the boolean expression written as a <em>logica</em> program.</p><blockquote>A logica program is evaluated by typing the Rust program given as output.</blockquote><p>The magic that makes this crazy idea possible is found in the header part of the compiled program, where the runtime (maybe typetime?) for the generated rust code is defined.</p><h4>The type system runtime</h4><p>Even though the concept of executing <em>logica</em> programs by type-checking Rust programs is complex, the runtime is very simple. First of all the atoms of the runtime are the constants True and False, which thanks to Rust’s type system can be defined using zero-sized types.</p><pre>struct True;<br>struct False;</pre><p>Implementing logic operators in the Rust type system requires encoding their rules as type rules, which can be done using <em>traits</em>. The logic operators that need to be implemented are <em>and</em>, <em>or </em>and <em>not.</em></p><p>The unary operator <em>not</em> defines its output in terms of the only input it receives, as it is a unary operator. Rust’s type systems allows to express that logic by mixing generic types, associated types and traits.</p><pre>pub trait UnaryOp&lt;L&gt; {<br>  type Returns;<br>  fn compute(_: L) -&gt; Self::Returns {<br>    panic!()<br>  }<br>}</pre><p>Types that implement <em>UnaryOp</em> need to do so for a given type (the input) and a associated type (the output), then by calling compute the associated type is obtained. The reader will have noticed that <em>compute</em> panics every time it is called; remember that this function is not meant to be executed, but typed. Implementing <em>not </em>using <em>UnaryOp </em>is straightforward.</p><pre>struct Not; <br>impl UnaryOp&lt;True&gt; for Not {<br>  type Returns = False;<br>} <br>impl UnaryOp&lt;False&gt; for Not {<br>  type Returns = True;<br>}</pre><p>The implementation of binary operators uses the same technique, but with two generic parameters.</p><pre>pub trait BinaryOp&lt;L, R&gt; {<br>  type Returns;<br>  fn compute(_: L, _: R) -&gt; Self::Returns {<br>    panic!()<br>  }<br>}</pre><p>And implementing the binary operators is a matter of defining each case, which using blanket implementations is as simple as writing the following.</p><pre>// Or operator<br>struct Or;<br>impl BinaryOp&lt;False, False&gt; for Or {<br>  type Returns = False;<br>}<br>impl BinaryOp&lt;True, False&gt; for Or {<br>  type Returns = True;<br>}<br>impl&lt;T&gt; BinaryOp&lt;T, True&gt; for Or {<br>  type Returns = True;<br>}<br><br>// And operator<br>struct And;<br>impl BinaryOp&lt;True, True&gt; for And {<br>  type Returns = True;<br>}<br>impl BinaryOp&lt;True, False&gt; for And {<br>  type Returns = False;<br>}<br>impl&lt;T&gt; BinaryOp&lt;False, T&gt; for And {<br>  type Returns = False;<br>}</pre><p>The only thing left to do is to define the translation rules. In order to avoid the additional complexity of <a href="https://github.com/hermeGarcia/BlogWorkspace/blob/8cfade7812af2854bb39c74207f9c91552f050bd/logica/src/main.rs#L28-L56">the actual implementation</a> the following pseudocode is given.</p><pre>C = context given by the user.<br>R = Set of Rust expressions.<br>L = Set of logica expressions.<br><br>translate: L -&gt; R<br>translate True -&gt; True<br>translate False -&gt; False<br>translate $i -&gt; translate(C[i])<br>translate (Not v) -&gt; Not::compute(translate(v))<br>translate (And l r) -&gt; And::compute(translate(l), translate(r))<br>translate (Or l r) -&gt; Or::compute(translate(l), translate(r))</pre><p>If the <em>logica</em> program given at the start</p><pre>(Or (Not $0) (And $0 $1))</pre><p>is compiled with the context</p><pre>C = {True, False}:</pre><p>the output would be the following Rust expression</p><pre>Or::compute(Not::compute(True),And::compute(True,False))</pre><p>Whose type is, as expected, <em>False</em>. A <em>logica</em> program has been evaluated inside Rust’s type system!</p><h4>Try it yourself!</h4><p>As with every other post the code can be found on this <a href="https://github.com/hermeGarcia/BlogWorkspace">blog’s Github repo</a> and everyone can try the <em>logica</em> compiler written in this post.</p><p>First you will need to download the project, this can be done by running the following command:</p><pre>svn checkout  https://github.com/hermeGarcia/BlogWorkspace/trunk/logica</pre><p>Or downloading the blog’s workspace</p><pre>git clone https://github.com/hermeGarcia/BlogWorkspace.git</pre><p>And then going into the compiler folder</p><pre>cd logica</pre><p>Now, as with every Rust project, it needs to be compiled.</p><pre>cargo build --release</pre><p>The binary will be located at ./<em>target/release/logica</em> and the <em>logica</em> program used by this post can be found at <em>./implication.logica</em>.</p><p>At this point, by executing the following command</p><pre>./target/release/logica --input=./implication.logica --output=./implication.rs --context=True:False</pre><p>the file <em>implication.rs</em> would be created at the root directory. It is a Rust program that can be compiled by executing <em>rustc</em>.</p><pre>rustc implication.rs</pre><p>The output would be the following compiler error.</p><pre>error[E0308]: mismatched types<br>  --&gt; implication.rs:47:1<br>   |<br>45 |     fn main() {<br>   |               - expected `()` because of default return type<br>46 |     <br>47 | Or::compute(Not::compute(True),And::compute(True,False))<br>   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^- help: consider using a semicolon here: `;`<br>   | |<br>   | expected `()`, found struct `False`</pre><p>The Rust compiler is telling us that the result of the <em>logica</em> program is in fact <em>False</em>!</p><h4>A brief word about parsing</h4><p>Before a <em>logica</em> program is compiled to a Rust program it must be parsed, the <em>logica</em> compiler has a <a href="https://github.com/hermeGarcia/BlogWorkspace/blob/main/logica/src/lang.lalrpop">standard parser</a> implemented with the amazing tool <a href="https://lalrpop.github.io/lalrpop/index.html">LALRPOP</a>.</p><h4>Further reading</h4><p>If this post has been of interest to you I have great news, turns out that Rust’s type system is capable of much more.</p><p>There is a <a href="https://sdleffler.github.io/RustTypeSystemTuringComplete/">great post</a> where Shea Leffler shows that the Rust’s type system is Turing complete! This means that complex computations, like the ones written with <em>C</em> or <em>Go</em>, could be expressed using Rust’s type system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HmjkU1JUQRizgR7BD9iX1Q.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b5023257735" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/a-runtime-inside-rusts-type-system-3b5023257735">A runtime inside Rust’s type system</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Smart contracts: trust the code at your own risk.]]></title>
            <link>https://towardsdev.com/smart-contracts-trust-the-code-at-your-own-risk-a2934fa416b7?source=rss-59a529e44a03------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2934fa416b7</guid>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[formal-methods]]></category>
            <category><![CDATA[programing-language]]></category>
            <category><![CDATA[verification]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <dc:creator><![CDATA[Herme García]]></dc:creator>
            <pubDate>Sun, 28 Aug 2022 18:00:29 GMT</pubDate>
            <atom:updated>2022-08-30T07:45:27.361Z</atom:updated>
            <content:encoded><![CDATA[<p>This post argues that the only way to create a secure and scalable framework for writing smart contracts is through the application of formal methods.</p><h4>Problems to address</h4><p>The reality about smart contracts is that if you abstract away the underlying ecosystem (the blockchain), the remaining logic is really simple. Storage and computation come with a price on the blockchain so smart contracts are not well suited for complex algorithms and data structures. On the other hand they should be the perfect tool for simple programs that require to be ran by the impartial and reliable third party that is the blockchain. Sadly there are two problems that keep smart contracts away from being a reliable tool even in this scenario.</p><p>In most blockchains when it comes to smart contract programming <strong>the underlying ecosystem is poorly abstracted</strong>. The most common approach is to design a standard programming language with some new directives or write a framework for a existing general purpouse programming language. In either of these cases most of the complexity from the ecosystem is inherited by the smart contract, leaving to the programmer the task of dealing with it.</p><p>Assuming the ecosystem is perfectly abstracted by a good model the reality is that for the blockchain to be reliable<strong> the smart contracts that are being ran need to be correct</strong>. These programs are the only actor where blockchain users are depositing their trust (and most of the time their money), it is only fair to ask for correctness guarantees.</p><h4>The power of good abstractions</h4><p>There was a time when writing machine code was the easiest path to implementing software. This meant that people who where experts in their domains and wanted to automate some tasks suddenly needed to hire someone to do so or try to deal themselves with lots of technical details that had nothing to do with their idea. High-level programming languages where design to abstract away some of the technicalities that come with automation, opening the door for a more secure and friendly environment to write software.</p><p>Another example of a good abstraction is the amazing actor model which is an abstraction for concurrent computation. Users of this model can design parallel software without having to deal with complex concurrency details that may be the root of many bugs. The Erlang programming language adopted this model and the simplicity and speed of the parallel software that can be written on it proofs the model’s worth.</p><p>As computer scientists our best contributions come when we are able to provide good abstractions that allow non-experts on the field to enjoy the power of computation. When smart contract programming languages where design this was completely forgotten and the following code is an example of why.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e7bafcf9219c6e23d710a50b087e83a/href">https://medium.com/media/5e7bafcf9219c6e23d710a50b087e83a/href</a></iframe><p>The code is written in Solidity, a high-level programming language for the Ethereum virtual machine. <em>Payer</em> is a simple smart contract to which other addresses can subscribe (even though the logic for it is not included) and periodically the contract will send to them a compensation for doing so. The only function showed in this example is <em>payday</em> and it sends the compensation to the subscriber.</p><p>Up to this point the code seems to be correct, it iterates through the subscribers sending the compensation. The reality is that this code has at least one huge bug, the programmer has not taken into account that transactions have fixed number of gas that limits the number of operations the function may execute. If at some point in time the number of subscribers in this contract grows too much the function’s loop may never be able to finish in one transaction therefore reverting its effect and leaving the subscribers without compensation forever. The following snipped shows a pattern the programmer may follow to safely iterate through dynamically bound loops.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70833a2e0eb1af4f2a7767e55d17ddb1/href">https://medium.com/media/70833a2e0eb1af4f2a7767e55d17ddb1/href</a></iframe><p>This new implementation has fixed the problem at the cost of a lot of boiler plate logic and a new state variable that the programmer needs to take into account in further development. Clearly this example shows that Solidity is far away from providing a good model for smart contract programming, even though it is is only purpose.</p><h4>Trust is built on correctness</h4><p>Blockchain companies love to use the slogan “trust the code” when talking about smart contracts. It is true that the blockchain ensures that now one is going to tamper the code being ran, but what they do not tell you is that this should not be enough to gain your trust.</p><p>In order to trust a piece of software it must come with certain guarantees. Some software providers gain trust by doing unit testing while others require programmers to follow strict methodologies and a to do a deep testing process. A few number of software providers gain trust by mathematically proving that their code does what they claim, strategy that leaves no room for unexpected behaviour.</p><p>Smart contract programming languages correctness can not be based on testing, they are the only actor where users are depositing their trust and most of the times, their money. The good thing is that this programming languages seem to be a great use case for software verification tools, the code written in them is usually short and their logic (removing all the boiler plate code caused by bad abstraction) is not complex. Programming languages like <a href="https://dafny.org/">Dafny</a> are far more complex than what is needed for smart contracts and they managed to include a verification step in their compilation.</p><h4>Not all hope is lost</h4><p>Currently the internet is full of courses with titles like “Build your own decentralised app!” and companies seemed to be focus on the next big use case for smart contracts. Under these circumstances is fair to say that the mainstream of the blockchain industry seems to have cero concerns about correctness or safety, but not all hope is lost. <a href="https://scilla-lang.org/">Scilla</a> is a programming language for smart contracts design for safety and correctness that reminds us that people are still rowing in the right direction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GT6bYnKH5QdsvWBX97IMdA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2934fa416b7" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/smart-contracts-trust-the-code-at-your-own-risk-a2934fa416b7">Smart contracts: trust the code at your own risk.</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rust Techniques For Compiler Engineers]]></title>
            <link>https://towardsdev.com/rust-techniques-for-compiler-engineers-9a5368f7037b?source=rss-59a529e44a03------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a5368f7037b</guid>
            <category><![CDATA[rust-programming-language]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[compiler-design]]></category>
            <category><![CDATA[abstract-syntax-tree]]></category>
            <category><![CDATA[compilers]]></category>
            <dc:creator><![CDATA[Herme García]]></dc:creator>
            <pubDate>Sat, 09 Apr 2022 10:34:14 GMT</pubDate>
            <atom:updated>2022-04-13T09:32:48.134Z</atom:updated>
            <content:encoded><![CDATA[<p>I love compiler engineering as much as I like programming language research and for some time now my language of choice for development is Rust. The reason for this post is to share some of the techniques I like to use when implementing tools for programming languages in Rust.</p><h4>Arenas</h4><p>Tools for programming languages tend to have one thing in common, intermediate representations (IR). Every tool uses an internal representation of the programming language being analyzed , inspecting the file directly can be quite tedious.</p><p>The simplest way to represent these structures in Rust is to use enums and anonymous structs. This way expressions could be defined as a enum in the following way:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/983b3cf4e901e9f7369ac37bbb510ee1/href">https://medium.com/media/983b3cf4e901e9f7369ac37bbb510ee1/href</a></iframe><p>Obviously for non-leaf nodes like Add the internal expressions need to be boxed or the compiler error will get really cool… Although boxed types are a good choice for defining recursive data structures, they can have a huge impact in the ergonomics of the data structure as it gets more complex. Specially if complex, pattern matching extensive algorithms are going to be written (witch will be the case for programming language tools).</p><p>Arenas are of great use in the cases where a lot of structures of the same type need to be stored in the heap. Instead of boxing the structures the idea is to use a dynamic vector to store them and the vector’s indexes to represent instances of the structure, the naïve implementation of will be:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86011de834fbc99134af2789ab82e093/href">https://medium.com/media/86011de834fbc99134af2789ab82e093/href</a></iframe><p>Obviously this approach to arenas does not make use of the great tools Rust has. For complex IRs, where lots of arenas are used, a mistake like using one index in the wrong arena will be a runtime error. Also the Vector<em> </em>type has lots of functionality implemented most of it will be of no use for the arena.</p><p>To get control over the underlying vector the best option is to wrap it in a new struct and defining the functionality the arena should have.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c4c6a317945eba2c55f918b35204f8b/href">https://medium.com/media/9c4c6a317945eba2c55f918b35204f8b/href</a></iframe><p>This approach is an improvement, but using a raw usize<em> </em>for indirection leaves room for bad behavior like ID arithmetic . To control how ID’s should be used and to transform the runtime error of using an index in the wrong arena into a compile time error things need to get Rusty. The trick is to wrap the index into a new type and then encode the type stored in the arena into the ID type (take a look at <a href="https://towardsdev.com/exploiting-the-rusts-type-system-to-avoid-runtime-errors-37193b2aafc6">my previous post</a> to know more about this).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd12296e1791cd6b4bab8b033a6c7bb5/href">https://medium.com/media/bd12296e1791cd6b4bab8b033a6c7bb5/href</a></iframe><p>Now Arena<em> </em>can implement the following traits to gain back the great ergonomics of vectors and indexes .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44f3277d900e159d3ecf385269bc411c/href">https://medium.com/media/44f3277d900e159d3ecf385269bc411c/href</a></iframe><p>Thanks to these traits ArenaID can be used for Arena<em> </em>in the same way usize is used for Vector.</p><h4>Intermediate Representations</h4><p>Using arenas for handling indirections is a real improvement on its own, but that is not the end of the story. The initial definition of expressions did improved with arena ids, but anonymous structures have a huge impact in the ergonomics of the IR as complexity grows. For example, the only way to implement a function for Add<em> </em>nodes would be:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a120887832a553aaa2056d08f54a666/href">https://medium.com/media/4a120887832a553aaa2056d08f54a666/href</a></iframe><p>Which will get really convoluted once return values enter the equation or nodes become more complex. A better approach is to define named structs for each node type, like in the following code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b79de472ba8a7d925824191fecb68a2/href">https://medium.com/media/0b79de472ba8a7d925824191fecb68a2/href</a></iframe><p>Now defining functions for a concrete node is as simple as using that node’s data structure.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d44d321bbf079e10aaa3104599cb4e3f/href">https://medium.com/media/d44d321bbf079e10aaa3104599cb4e3f/href</a></iframe><p>Thanks to this approach if data were to be shared across all nodes the composition technique could be used. An implementation of this technique can be seen in the following example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb906c05a1014b57112d77cbf5b130b9/href">https://medium.com/media/cb906c05a1014b57112d77cbf5b130b9/href</a></iframe><p>A node type is a composition of metadata and the concrete data for the node. Since the metadata is the same for all node types using composition will reduce the complexity of including new metadata attributes.</p><p>There is one more technique to conclude that I would like to share in this post, I like to call it the visitor technique. It creates a framework where defining passes through the IR becomes really easy.</p><p>The first element of this technique is the visitor trait which gives to embed the operations that should be apply to each node type during during a pass.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13a93ef0026973a879ea96c724f522cf/href">https://medium.com/media/13a93ef0026973a879ea96c724f522cf/href</a></iframe><p>Where <em>State</em> is the structure used to store the arenas and other global data. Each node type has its own pre_visit and post_visit operation to define what should be done before and after its childs are traversed. Every operation has a default empty definition since is possible not all node types relevant to the pass.</p><p>The second element of this technique is the traverse algorithm. Thanks to the visitor trait the tedious job of writing this function needs to be done only once.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f904d6705d3471e42439c8a095ae226/href">https://medium.com/media/8f904d6705d3471e42439c8a095ae226/href</a></iframe><p>The user could implement a function for counting how many numbers are in an expression in the following way.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3bac644d5aa03b7d7f818f390c1585f/href">https://medium.com/media/f3bac644d5aa03b7d7f818f390c1585f/href</a></iframe><h4>Conclusions</h4><p>This gets us to the end of this post. These techniques may not be the best ones and I am sure they can be improved, but they are the ones I have been finding to be more useful lately. I hope this post is of use for the developers and compiler enthusiasts that are thinking about testing their skills in Rust.</p><p>A thorough use of these techniques can be found in <a href="https://github.com/hermeGarcia/BlogWorkspace/tree/main/ir_pattern">this blog’s repo</a>. Go take a look and try to implement some passes!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*7z4wv_BUvact28h1fra3Bg.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a5368f7037b" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/rust-techniques-for-compiler-engineers-9a5368f7037b">Rust Techniques For Compiler Engineers</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploiting the Rust’s type system to avoid runtime errors.]]></title>
            <link>https://towardsdev.com/exploiting-the-rusts-type-system-to-avoid-runtime-errors-37193b2aafc6?source=rss-59a529e44a03------2</link>
            <guid isPermaLink="false">https://medium.com/p/37193b2aafc6</guid>
            <category><![CDATA[rust-programming-language]]></category>
            <category><![CDATA[formal-methods]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[type-systems]]></category>
            <category><![CDATA[type-safety]]></category>
            <dc:creator><![CDATA[Herme García]]></dc:creator>
            <pubDate>Sun, 06 Mar 2022 10:52:54 GMT</pubDate>
            <atom:updated>2022-03-08T08:45:47.918Z</atom:updated>
            <content:encoded><![CDATA[<p>As a computer scientist specialised in formal methods I love the work that is being done by in Rust to create a programming language that is safe and robust. I would like to use my first post to show how we can use the Rust type system and its move semantics to transform runtime errors into compile-time errors.</p><h4>Why is this important?</h4><p>It is obvious that developers make mistakes and while unit testing is useful (and necessary) it can leave bugs undetected. As Dijkstra said:</p><blockquote>Program testing can be used to show the presence of bugs, but never to show their absence</blockquote><p>Proving the absence of bugs in a program is not an easy task, specially in common big languages like Java, C or Rust. Full program verification requires a verification engine (like <a href="https://www.microsoft.com/en-us/research/project/dafny-a-language-and-program-verifier-for-functional-correctness/">Dafny</a>), but that is a matter for another post.</p><p>A simple example of a bug that is proved absent by most compilers is the use of a undeclared variable. Almost all compilers check that all variables used in the program have been declared. More complex bugs could be detected by type systems or sophisticated static analysis.</p><h4>Using Rust’s type systems to create safer libraries</h4><p>Vec is a dynamically sized array that can be found in Rust’s standard library. It is an incredibly useful type with a lot of functionality implemented into it. If used wrong this functionality can caused errors that will not be detected by the compiler. The following snippet is an example of a bad use of Vec:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a0f888ba1de6eb527619ef231015cd8/href">https://medium.com/media/9a0f888ba1de6eb527619ef231015cd8/href</a></iframe><p>As can be seen in the previous code the Vec type has binary search method. Vec does not enforce on its users the precondition of the binary search (The vector should be sorted before calling it) causing the assertion in line 4 to fail. The following snippet shows a good use of Vec:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87187bf83ae3155129bde4761d9ef9e1/href">https://medium.com/media/87187bf83ae3155129bde4761d9ef9e1/href</a></iframe><p>Imagine you were developing a library where distinguishing sorted and unsorted vectors is crucial. Making sure your code is not performing a binary search on an unsorted vector is a complex task. Unless we use the power of Rust’s type system.</p><h4>Zero sized types</h4><p>Before getting into Vec a quick word about a Rust tool called Zero sized types. This types occupy zero space and the compiler will transform every operation that produces or stores a zero sized type into a no-op.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f0a8fc8654aa07777093f3b12aa1b90/href">https://medium.com/media/4f0a8fc8654aa07777093f3b12aa1b90/href</a></iframe><p>At first this tool may seem useless, but zero sized types are great for adding logic that should be checked only at compile.</p><h4>SafeVec: first steps</h4><p>Our goal is to use Rust’s type system to distinguish at compile time sorted vectors from unsorted ones. First of all, lets wrap Vec into a new type where we can include this new logic.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72eef697b3a38eb8476b893e550949b8/href">https://medium.com/media/72eef697b3a38eb8476b893e550949b8/href</a></iframe><p>The next step is to encode into the type if the underlying vector is sorted or not. This can be achieved by adding another parameter into SafeVec’s type.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c18d45414086c09f1b7aa5974f7dda1d/href">https://medium.com/media/c18d45414086c09f1b7aa5974f7dda1d/href</a></iframe><p>Line 5 will be a surprised for some, I encourage you to remove line 5 and compile the code. You will see that type parameters must be own in some way by the type being defined. PhantomData is a zero sized type that acts as if it owned a given type (in this case the state S). Some of you may wonder why not store the type S in state and forget about PhantomData. While this may be an alternative it will impose annoying restrictions when deriving traits for SafeVec.</p><p>Now we can define the two states in which SafeVec can be found, since states are just type logic we use zero sized types.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7358663533ef64db96f617cf50a5326a/href">https://medium.com/media/7358663533ef64db96f617cf50a5326a/href</a></iframe><p>And now thanks to the power of Rust’s type system we can implement methods for concrete instances of SafeVec’s parameters. In this case there are going to be three sets of methods:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ebc1098c42a9c47d88673b71a26dccf/href">https://medium.com/media/0ebc1098c42a9c47d88673b71a26dccf/href</a></iframe><p>Now users of SafeVec will be unable to call methods meant for sorted vectors with unsorted ones. If so, their code will not compile.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8b7c99e8330e5146c7224d9f9776d43/href">https://medium.com/media/c8b7c99e8330e5146c7224d9f9776d43/href</a></iframe><h4>Conclusions</h4><p>In this post we have seen that sometimes Rust’s type system allows us to make safer libraries and avoid runtime errors to our users. By no means this will always be an option, sometimes the logic is to complex for this approach. While type parameters were a useful tool in this case too many of them will create unusable types.</p><p>You can find the full implementation of SafeVec in <a href="https://github.com/hermeGarcia/BlogWorkspace/tree/main/type_safety">this folder of the blog’s GitHub repo.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37193b2aafc6" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/exploiting-the-rusts-type-system-to-avoid-runtime-errors-37193b2aafc6">Exploiting the Rust’s type system to avoid runtime errors.</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>