From 938c4648b102975cd73f82457544ec7dc0318bfa Mon Sep 17 00:00:00 2001 From: Akshay Date: Mon, 4 Oct 2021 08:10:24 +0530 Subject: new art: b8 --- art/b8.png | Bin 0 -> 27220 bytes docs/art/b8.png | Bin 0 -> 27220 bytes docs/art/index.html | 13 +- docs/index.html | 10 +- docs/index.xml | 834 ++++++++++----------- docs/posts/SDL2_devlog/index.html | 68 +- docs/posts/auto-currying_rust_functions/index.html | 512 ++++++------- docs/posts/gripes_with_go/index.html | 140 ++-- docs/posts/nixOS/index.html | 8 +- docs/posts/rapid_refactoring_with_vim/index.html | 50 +- docs/posts/self-hosting_git/index.html | 20 +- docs/posts/static_sites_with_bash/index.html | 36 +- 12 files changed, 851 insertions(+), 840 deletions(-) create mode 100644 art/b8.png create mode 100644 docs/art/b8.png diff --git a/art/b8.png b/art/b8.png new file mode 100644 index 0000000..8e1f79d Binary files /dev/null and b/art/b8.png differ diff --git a/docs/art/b8.png b/docs/art/b8.png new file mode 100644 index 0000000..8e1f79d Binary files /dev/null and b/docs/art/b8.png differ diff --git a/docs/art/index.html b/docs/art/index.html index eef6649..e72ec51 100644 --- a/docs/art/index.html +++ b/docs/art/index.html @@ -21,7 +21,18 @@

Art

- + +
+ +
+
+
B8
+
04/10 — 2021
+
+
+
+
+
diff --git a/docs/index.html b/docs/index.html index 1c8f5b3..c314061 100644 --- a/docs/index.html +++ b/docs/index.html @@ -78,15 +78,15 @@
- 23/08 — 2021 + 04/10 — 2021
-
- Goat + + B8 - - + + diff --git a/docs/index.xml b/docs/index.xml index f0f3f71..06bbc87 100644 --- a/docs/index.xml +++ b/docs/index.xml @@ -31,48 +31,48 @@ </figure> <h3 id="day-17">Day 17</h3> <p>I decided to give the text-only statusline a touch up, by adding a active color and dither level preview. Aligning the “widget” to the right of statusline involved a lot more than I thought, so I created a ghetto CSS-like rectangle placement system to position containers inside containers:</p> -<div class="sourceCode" id="cb1"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true"></a><span class="co">// roughly something like this</span></span> -<span id="cb1-2"><a href="#cb1-2" aria-hidden="true"></a><span class="kw">let</span> statusline <span class="op">=</span> </span> -<span id="cb1-3"><a href="#cb1-3" aria-hidden="true"></a> <span class="pp">Container::</span>new(<span class="pp">Offset::</span>Left(<span class="dv">0</span>)<span class="op">,</span> <span class="pp">Offset::</span>Bottom(<span class="dv">40</span>))</span> -<span id="cb1-4"><a href="#cb1-4" aria-hidden="true"></a> <span class="op">.</span>width(<span class="pp">Size::</span>Max)</span> -<span id="cb1-5"><a href="#cb1-5" aria-hidden="true"></a> <span class="op">.</span>height(<span class="pp">Size::</span>Absolute(<span class="dv">20</span>))<span class="op">;</span></span> -<span id="cb1-6"><a href="#cb1-6" aria-hidden="true"></a> </span> -<span id="cb1-7"><a href="#cb1-7" aria-hidden="true"></a><span class="kw">let</span> <span class="kw">mut</span> primary <span class="op">=</span> <span class="pp">Container::</span>uninit()</span> -<span id="cb1-8"><a href="#cb1-8" aria-hidden="true"></a> <span class="op">.</span>width(<span class="pp">Size::</span>Absolute(<span class="dv">16</span>))</span> -<span id="cb1-9"><a href="#cb1-9" aria-hidden="true"></a> <span class="op">.</span>height(<span class="pp">Size::</span>Absolute(<span class="dv">16</span>))<span class="op">;</span></span> -<span id="cb1-10"><a href="#cb1-10" aria-hidden="true"></a> </span> -<span id="cb1-11"><a href="#cb1-11" aria-hidden="true"></a>container<span class="op">.</span>place(</span> -<span id="cb1-12"><a href="#cb1-12" aria-hidden="true"></a> <span class="op">&amp;</span><span class="kw">mut</span> padding_box<span class="op">,</span></span> -<span id="cb1-13"><a href="#cb1-13" aria-hidden="true"></a> <span class="pp">HorAlign::</span>Right<span class="op">,</span></span> -<span id="cb1-14"><a href="#cb1-14" aria-hidden="true"></a> <span class="pp">VertAlign::</span>Center</span> -<span id="cb1-15"><a href="#cb1-15" aria-hidden="true"></a>)<span class="op">;</span></span></code></pre></div> +<div class="sourceCode" id="cb1"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="co">// roughly something like this</span></span> +<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a><span class="kw">let</span> statusline <span class="op">=</span> </span> +<span id="cb1-3"><a href="#cb1-3" aria-hidden="true" tabindex="-1"></a> <span class="pp">Container::</span>new(<span class="pp">Offset::</span>Left(<span class="dv">0</span>)<span class="op">,</span> <span class="pp">Offset::</span>Bottom(<span class="dv">40</span>))</span> +<span id="cb1-4"><a href="#cb1-4" aria-hidden="true" tabindex="-1"></a> <span class="op">.</span>width(<span class="pp">Size::</span>Max)</span> +<span id="cb1-5"><a href="#cb1-5" aria-hidden="true" tabindex="-1"></a> <span class="op">.</span>height(<span class="pp">Size::</span>Absolute(<span class="dv">20</span>))<span class="op">;</span></span> +<span id="cb1-6"><a href="#cb1-6" aria-hidden="true" tabindex="-1"></a> </span> +<span id="cb1-7"><a href="#cb1-7" aria-hidden="true" tabindex="-1"></a><span class="kw">let</span> <span class="kw">mut</span> primary <span class="op">=</span> <span class="pp">Container::</span>uninit()</span> +<span id="cb1-8"><a href="#cb1-8" aria-hidden="true" tabindex="-1"></a> <span class="op">.</span>width(<span class="pp">Size::</span>Absolute(<span class="dv">16</span>))</span> +<span id="cb1-9"><a href="#cb1-9" aria-hidden="true" tabindex="-1"></a> <span class="op">.</span>height(<span class="pp">Size::</span>Absolute(<span class="dv">16</span>))<span class="op">;</span></span> +<span id="cb1-10"><a href="#cb1-10" aria-hidden="true" tabindex="-1"></a> </span> +<span id="cb1-11"><a href="#cb1-11" aria-hidden="true" tabindex="-1"></a>container<span class="op">.</span>place(</span> +<span id="cb1-12"><a href="#cb1-12" aria-hidden="true" tabindex="-1"></a> <span class="op">&amp;</span><span class="kw">mut</span> padding_box<span class="op">,</span></span> +<span id="cb1-13"><a href="#cb1-13" aria-hidden="true" tabindex="-1"></a> <span class="pp">HorAlign::</span>Right<span class="op">,</span></span> +<span id="cb1-14"><a href="#cb1-14" aria-hidden="true" tabindex="-1"></a> <span class="pp">VertAlign::</span>Center</span> +<span id="cb1-15"><a href="#cb1-15" aria-hidden="true" tabindex="-1"></a>)<span class="op">;</span></span></code></pre></div> <p>The result (brush preview on the bottom right):</p> <figure> <video src="https://u.peppe.rs/OtU.mp4" controls=""><a href="https://u.peppe.rs/OtU.mp4">Day 17</a></video><figcaption aria-hidden="true">Day 17</figcaption> </figure> <h3 id="day-16">Day 16</h3> <p>The embedded lisp is coming along nicely, users can load a custom <code>rc.lisp</code>, which is evaluated on startup. To disable to grid on start, for example:</p> -<div class="sourceCode" id="cb2"><pre class="sourceCode scheme"><code class="sourceCode scheme"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true"></a><span class="co">;;; rc.lisp</span></span> -<span id="cb2-2"><a href="#cb2-2" aria-hidden="true"></a>(toggle-grid)</span></code></pre></div> +<div class="sourceCode" id="cb2"><pre class="sourceCode scheme"><code class="sourceCode scheme"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a><span class="co">;;; rc.lisp</span></span> +<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a>(toggle-grid)</span></code></pre></div> <p>Some aliases to switch between brushes:</p> -<div class="sourceCode" id="cb3"><pre class="sourceCode scheme"><code class="sourceCode scheme"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true"></a><span class="co">;;; rc.lisp</span></span> -<span id="cb3-2"><a href="#cb3-2" aria-hidden="true"></a>(<span class="ex">define</span><span class="fu"> </span>(brush kind)</span> -<span id="cb3-3"><a href="#cb3-3" aria-hidden="true"></a> (<span class="kw">cond</span></span> -<span id="cb3-4"><a href="#cb3-4" aria-hidden="true"></a> ((<span class="kw">eq?</span> kind &#39;f) (brush-fill))</span> -<span id="cb3-5"><a href="#cb3-5" aria-hidden="true"></a> ((<span class="kw">eq?</span> kind &#39;c) (brush-circle))</span> -<span id="cb3-6"><a href="#cb3-6" aria-hidden="true"></a> ((<span class="kw">eq?</span> kind &#39;l) (brush-line))</span> -<span id="cb3-7"><a href="#cb3-7" aria-hidden="true"></a> ((<span class="kw">eq?</span> kind &#39;l+) (brush-line-extend))</span> -<span id="cb3-8"><a href="#cb3-8" aria-hidden="true"></a> (<span class="kw">else</span> (brush-circle))))</span></code></pre></div> +<div class="sourceCode" id="cb3"><pre class="sourceCode scheme"><code class="sourceCode scheme"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a><span class="co">;;; rc.lisp</span></span> +<span id="cb3-2"><a href="#cb3-2" aria-hidden="true" tabindex="-1"></a>(<span class="ex">define</span><span class="fu"> </span>(brush kind)</span> +<span id="cb3-3"><a href="#cb3-3" aria-hidden="true" tabindex="-1"></a> (<span class="kw">cond</span></span> +<span id="cb3-4"><a href="#cb3-4" aria-hidden="true" tabindex="-1"></a> ((<span class="kw">eq?</span> kind &#39;f) (brush-fill))</span> +<span id="cb3-5"><a href="#cb3-5" aria-hidden="true" tabindex="-1"></a> ((<span class="kw">eq?</span> kind &#39;c) (brush-circle))</span> +<span id="cb3-6"><a href="#cb3-6" aria-hidden="true" tabindex="-1"></a> ((<span class="kw">eq?</span> kind &#39;l) (brush-line))</span> +<span id="cb3-7"><a href="#cb3-7" aria-hidden="true" tabindex="-1"></a> ((<span class="kw">eq?</span> kind &#39;l+) (brush-line-extend))</span> +<span id="cb3-8"><a href="#cb3-8" aria-hidden="true" tabindex="-1"></a> (<span class="kw">else</span> (brush-circle))))</span></code></pre></div> <p>The following script draws a straight line along a given axis, at a given distance from the canvas boundary:</p> <figure> <video src="https://u.peppe.rs/b3i.mp4" controls=""><a href="https://u.peppe.rs/b3i.mp4">Day 16</a></video><figcaption aria-hidden="true">Day 16</figcaption> </figure> <h3 id="day-15">Day 15</h3> <p>I began writing a standard library for the lisp, in lisp. It includes basic list operations: <code>car</code>, <code>cdr</code>, <code>null?</code>, <code>list</code>, higher order functions: <code>map</code>, <code>filter</code>, <code>fold</code>:</p> -<div class="sourceCode" id="cb4"><pre class="sourceCode lisp"><code class="sourceCode commonlisp"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true"></a>(define (member? item ls)</span> -<span id="cb4-2"><a href="#cb4-2" aria-hidden="true"></a> (fold <span class="dv">#f</span></span> -<span id="cb4-3"><a href="#cb4-3" aria-hidden="true"></a> (<span class="kw">lambda</span> (acc x) (<span class="kw">or</span> acc (eq? item x)))</span> -<span id="cb4-4"><a href="#cb4-4" aria-hidden="true"></a> ls))</span></code></pre></div> +<div class="sourceCode" id="cb4"><pre class="sourceCode lisp"><code class="sourceCode commonlisp"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a>(define (member? item ls)</span> +<span id="cb4-2"><a href="#cb4-2" aria-hidden="true" tabindex="-1"></a> (fold <span class="dv">#f</span></span> +<span id="cb4-3"><a href="#cb4-3" aria-hidden="true" tabindex="-1"></a> (<span class="kw">lambda</span> (acc x) (<span class="kw">or</span> acc (eq? item x)))</span> +<span id="cb4-4"><a href="#cb4-4" aria-hidden="true" tabindex="-1"></a> ls))</span></code></pre></div> <h3 id="day-14">Day 14</h3> <p>I attempted a <a href="https://peppe.rs/art/ramen_noodles.png">small art piece</a> using the editor, while it was largely usable, I felt a certain lack of feedback. The brushes just didn’t relay as much info as I’d have liked, for example, the approximate points of the line or the angle made by the line against the x-axis. Unfortunately, the existing infrastructure around brushes and line drawing didn’t easily allow for this either. I went ahead and reimplemented brushes, and added a new flood fill brush too:</p> <figure> @@ -105,11 +105,11 @@ </figure> <h3 id="day-8">Day 8</h3> <p>One of my favourite features of GIMP was symmetric editing. I added some coordinate geometry primitives to my pixmap abstraction, allowing for mirroring and reflecting figures about lines or points. The result was an ergonomic function that applies symmetry to any painting operation, (undo/redo works as expected):</p> -<div class="sourceCode" id="cb5"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb5-1"><a href="#cb5-1" aria-hidden="true"></a><span class="kw">let</span> line <span class="op">=</span> <span class="kw">self</span><span class="op">.</span>pixmap<span class="op">.</span>get_line(start<span class="op">,</span> end)<span class="op">;</span></span> -<span id="cb5-2"><a href="#cb5-2" aria-hidden="true"></a><span class="kw">let</span> sym_line <span class="op">=</span> <span class="kw">self</span><span class="op">.</span>symmetry<span class="op">.</span>apply(<span class="op">&amp;</span>line)<span class="op">;</span></span> -<span id="cb5-3"><a href="#cb5-3" aria-hidden="true"></a><span class="kw">for</span> point on line<span class="op">.</span>extend(sym_line) <span class="op">{</span></span> -<span id="cb5-4"><a href="#cb5-4" aria-hidden="true"></a> <span class="co">// draw to window</span></span> -<span id="cb5-5"><a href="#cb5-5" aria-hidden="true"></a><span class="op">}</span></span></code></pre></div> +<div class="sourceCode" id="cb5"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb5-1"><a href="#cb5-1" aria-hidden="true" tabindex="-1"></a><span class="kw">let</span> line <span class="op">=</span> <span class="kw">self</span><span class="op">.</span>pixmap<span class="op">.</span>get_line(start<span class="op">,</span> end)<span class="op">;</span></span> +<span id="cb5-2"><a href="#cb5-2" aria-hidden="true" tabindex="-1"></a><span class="kw">let</span> sym_line <span class="op">=</span> <span class="kw">self</span><span class="op">.</span>symmetry<span class="op">.</span>apply(<span class="op">&amp;</span>line)<span class="op">;</span></span> +<span id="cb5-3"><a href="#cb5-3" aria-hidden="true" tabindex="-1"></a><span class="kw">for</span> point on line<span class="op">.</span>extend(sym_line) <span class="op">{</span></span> +<span id="cb5-4"><a href="#cb5-4" aria-hidden="true" tabindex="-1"></a> <span class="co">// draw to window</span></span> +<span id="cb5-5"><a href="#cb5-5" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code></pre></div> <figure> <video src="https://u.peppe.rs/B1.mp4" controls=""><a href="https://u.peppe.rs/B1.mp4">Day 8</a></video><figcaption aria-hidden="true">Day 8</figcaption> </figure> @@ -159,19 +159,19 @@ <p>cgit is <em>very</em> bare bones. It is <a href="https://tools.ietf.org/html/rfc3875">cgi-based</a> web interface to git, and nothing more. You may browse repositories, view diffs, commit logs and even clone via http. If you are looking to replace Github with cgit, keep in mind that cgit does not handle issues or pull/merge requests. If people wish to contribute to your work, they would have to send you a patch via email.</p> <h3 id="setup">Setup</h3> <p>Installing cgit is fairly straightforward, if you would like to compile it from source:</p> -<div class="sourceCode" id="cb1"><pre class="sourceCode sh"><code class="sourceCode bash"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true"></a><span class="co"># fetch</span></span> -<span id="cb1-2"><a href="#cb1-2" aria-hidden="true"></a><span class="fu">git</span> clone https://git.zx2c4.com <span class="kw">&amp;&amp;</span> <span class="bu">cd</span> cgit</span> -<span id="cb1-3"><a href="#cb1-3" aria-hidden="true"></a><span class="fu">git</span> submodule init</span> -<span id="cb1-4"><a href="#cb1-4" aria-hidden="true"></a><span class="fu">git</span> submodule update</span> -<span id="cb1-5"><a href="#cb1-5" aria-hidden="true"></a></span> -<span id="cb1-6"><a href="#cb1-6" aria-hidden="true"></a><span class="co"># install</span></span> -<span id="cb1-7"><a href="#cb1-7" aria-hidden="true"></a><span class="fu">make</span> NO_LUA=1</span> -<span id="cb1-8"><a href="#cb1-8" aria-hidden="true"></a><span class="fu">sudo</span> make install</span></code></pre></div> +<div class="sourceCode" id="cb1"><pre class="sourceCode sh"><code class="sourceCode bash"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="co"># fetch</span></span> +<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a><span class="fu">git</span> clone https://git.zx2c4.com <span class="kw">&amp;&amp;</span> <span class="bu">cd</span> cgit</span> +<span id="cb1-3"><a href="#cb1-3" aria-hidden="true" tabindex="-1"></a><span class="fu">git</span> submodule init</span> +<span id="cb1-4"><a href="#cb1-4" aria-hidden="true" tabindex="-1"></a><span class="fu">git</span> submodule update</span> +<span id="cb1-5"><a href="#cb1-5" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb1-6"><a href="#cb1-6" aria-hidden="true" tabindex="-1"></a><span class="co"># install</span></span> +<span id="cb1-7"><a href="#cb1-7" aria-hidden="true" tabindex="-1"></a><span class="fu">make</span> NO_LUA=1</span> +<span id="cb1-8"><a href="#cb1-8" aria-hidden="true" tabindex="-1"></a><span class="fu">sudo</span> make install</span></code></pre></div> <p>This would drop the cgit cgi script (and the default css) into <code>/var/www/htdocs/cgit</code>. You may configure cgit by editing <code>/etc/cgitrc</code>. I specify the <code>NO_LUA</code> flag to compile without lua support, exclude that flag if you would like to extend cgit via lua scripts.</p> <h3 id="going-live">Going live</h3> <p>You might want to use, <a href="https://github.com/gnosek/fcgiwrap">fcgiwrap</a>, a <a href="http://www.nongnu.org/fastcgi">fastcgi</a> wrapper for <code>cgi</code> scripts,</p> -<div class="sourceCode" id="cb2"><pre class="sourceCode sh"><code class="sourceCode bash"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true"></a><span class="fu">sudo</span> apt install fcgiwrap</span> -<span id="cb2-2"><a href="#cb2-2" aria-hidden="true"></a><span class="fu">sudo</span> systemctl start fcgiwrap.socket</span></code></pre></div> +<div class="sourceCode" id="cb2"><pre class="sourceCode sh"><code class="sourceCode bash"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a><span class="fu">sudo</span> apt install fcgiwrap</span> +<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a><span class="fu">sudo</span> systemctl start fcgiwrap.socket</span></code></pre></div> <p>Expose the cgit cgi script to the web via <code>nginx</code>:</p> <pre><code># nginx.conf server { @@ -298,10 +298,10 @@ scp .git/description &quot;$remote/description&quot;</code></pr <p>Builds may be generated by specifying a <code>default.nix</code> file, and running <code>nix-build</code>. Conventional package managers require you to specify a dependency list, but there is no guarantee that this list is complete. The package will build on your machine even if you forget a dependency. However, with Nix, packages are installed to <code>/nix/store</code>, and not global paths such as <code>/usr/bin/...</code>, if your project builds, it means you have included every last one.</p> <p>Issues on most my projects have been “unable to build because <code>libxcb</code> is missing”, or “this version of <code>openssl</code> is too old”. Tools like <code>cargo</code> and <code>pip</code> are poor package managers. While they <em>can</em> guarantee that Rust or Python dependencies are met, they make assumptions about the target system.</p> <p>For example, <a href="https://github.com/nerdypepper/site">this website</a> is now built using Nix, anyone using Nix may simply, clone the repository and run <code>./generate.sh</code>, and it would <em>just work</em>, while keeping your global namespace clean™:</p> -<div class="sourceCode" id="cb2"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true"></a><span class="co">#! /usr/bin/env nix-shell</span></span> -<span id="cb2-2"><a href="#cb2-2" aria-hidden="true"></a><span class="co">#! nix-shell -i bash -p eva pandoc esh</span></span> -<span id="cb2-3"><a href="#cb2-3" aria-hidden="true"></a></span> -<span id="cb2-4"><a href="#cb2-4" aria-hidden="true"></a><span class="co"># some bash magic ;)</span></span></code></pre></div> +<div class="sourceCode" id="cb2"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a><span class="co">#! /usr/bin/env nix-shell</span></span> +<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a><span class="co">#! nix-shell -i bash -p eva pandoc esh</span></span> +<span id="cb2-3"><a href="#cb2-3" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb2-4"><a href="#cb2-4" aria-hidden="true" tabindex="-1"></a><span class="co"># some bash magic ;)</span></span></code></pre></div> <p>Dependencies are included with the <code>-p</code> flag, the shell script is executed with an interpreter, specified with the <code>-i</code> flag.</p> <h3 id="impressions">Impressions</h3> <p>NixOS is by no means, simple. As a newcomer, using Nix was not easy, heck, I had to learn a purely functional, lazy language to just build programs. There is a lot to be desired on the tooling front as well. A well fleshed out LSP plugin would be nice (<a href="https://github.com/nix-community/rnix-lsp">rnix-lsp looks promising</a>).</p> @@ -326,101 +326,101 @@ scp .git/description &quot;$remote/description&quot;</code></pr <h3 id="lack-of-sum-types">Lack of Sum types</h3> <p>A “Sum” type is a data type that can hold one of many states at a given time, similar to how a boolean can hold a true or a false, not too different from an <code>enum</code> type in C. Go lacks <code>enum</code> types unfortunately, and you are forced to resort to crafting your own substitute.</p> <p>A type to represent gender for example:</p> -<div class="sourceCode" id="cb1"><pre class="sourceCode go"><code class="sourceCode go"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true"></a><span class="kw">type</span> Gender <span class="dt">int</span></span> -<span id="cb1-2"><a href="#cb1-2" aria-hidden="true"></a></span> -<span id="cb1-3"><a href="#cb1-3" aria-hidden="true"></a><span class="kw">const</span> (</span> -<span id="cb1-4"><a href="#cb1-4" aria-hidden="true"></a> Male Gender = <span class="ot">iota</span> <span class="co">// assigns Male to 0</span></span> -<span id="cb1-5"><a href="#cb1-5" aria-hidden="true"></a> Female <span class="co">// assigns Female to 1</span></span> -<span id="cb1-6"><a href="#cb1-6" aria-hidden="true"></a> Other <span class="co">// assigns Other to 2</span></span> -<span id="cb1-7"><a href="#cb1-7" aria-hidden="true"></a>)</span> -<span id="cb1-8"><a href="#cb1-8" aria-hidden="true"></a></span> -<span id="cb1-9"><a href="#cb1-9" aria-hidden="true"></a>fmt.Println(<span class="st">&quot;My gender is &quot;</span>, Male)</span> -<span id="cb1-10"><a href="#cb1-10" aria-hidden="true"></a><span class="co">// My gender is 0</span></span> -<span id="cb1-11"><a href="#cb1-11" aria-hidden="true"></a><span class="co">// Oops! We have to implement String() for Gender ...</span></span> -<span id="cb1-12"><a href="#cb1-12" aria-hidden="true"></a></span> -<span id="cb1-13"><a href="#cb1-13" aria-hidden="true"></a><span class="kw">func</span> (g Gender) String() <span class="dt">string</span> {</span> -<span id="cb1-14"><a href="#cb1-14" aria-hidden="true"></a> <span class="kw">switch</span> (g) {</span> -<span id="cb1-15"><a href="#cb1-15" aria-hidden="true"></a> <span class="kw">case</span> <span class="dv">0</span>: <span class="kw">return</span> <span class="st">&quot;Male&quot;</span></span> -<span id="cb1-16"><a href="#cb1-16" aria-hidden="true"></a> <span class="kw">case</span> <span class="dv">1</span>: <span class="kw">return</span> <span class="st">&quot;Female&quot;</span></span> -<span id="cb1-17"><a href="#cb1-17" aria-hidden="true"></a> <span class="kw">default</span>: <span class="kw">return</span> <span class="st">&quot;Other&quot;</span></span> -<span id="cb1-18"><a href="#cb1-18" aria-hidden="true"></a> }</span> -<span id="cb1-19"><a href="#cb1-19" aria-hidden="true"></a>}</span> -<span id="cb1-20"><a href="#cb1-20" aria-hidden="true"></a></span> -<span id="cb1-21"><a href="#cb1-21" aria-hidden="true"></a><span class="co">// You can accidentally do stupid stuff like:</span></span> -<span id="cb1-22"><a href="#cb1-22" aria-hidden="true"></a>gender := Male + <span class="dv">1</span></span></code></pre></div> +<div class="sourceCode" id="cb1"><pre class="sourceCode go"><code class="sourceCode go"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> Gender <span class="dt">int</span></span> +<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb1-3"><a href="#cb1-3" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> <span class="op">(</span></span> +<span id="cb1-4"><a href="#cb1-4" aria-hidden="true" tabindex="-1"></a> Male Gender <span class="op">=</span> <span class="ot">iota</span> <span class="co">// assigns Male to 0</span></span> +<span id="cb1-5"><a href="#cb1-5" aria-hidden="true" tabindex="-1"></a> Female <span class="co">// assigns Female to 1</span></span> +<span id="cb1-6"><a href="#cb1-6" aria-hidden="true" tabindex="-1"></a> Other <span class="co">// assigns Other to 2</span></span> +<span id="cb1-7"><a href="#cb1-7" aria-hidden="true" tabindex="-1"></a><span class="op">)</span></span> +<span id="cb1-8"><a href="#cb1-8" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb1-9"><a href="#cb1-9" aria-hidden="true" tabindex="-1"></a>fmt<span class="op">.</span>Println<span class="op">(</span><span class="st">&quot;My gender is &quot;</span><span class="op">,</span> Male<span class="op">)</span></span> +<span id="cb1-10"><a href="#cb1-10" aria-hidden="true" tabindex="-1"></a><span class="co">// My gender is 0</span></span> +<span id="cb1-11"><a href="#cb1-11" aria-hidden="true" tabindex="-1"></a><span class="co">// Oops! We have to implement String() for Gender ...</span></span> +<span id="cb1-12"><a href="#cb1-12" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb1-13"><a href="#cb1-13" aria-hidden="true" tabindex="-1"></a><span class="kw">func</span> <span class="op">(</span>g Gender<span class="op">)</span> String<span class="op">()</span> <span class="dt">string</span> <span class="op">{</span></span> +<span id="cb1-14"><a href="#cb1-14" aria-hidden="true" tabindex="-1"></a> <span class="kw">switch</span> <span class="op">(</span>g<span class="op">)</span> <span class="op">{</span></span> +<span id="cb1-15"><a href="#cb1-15" aria-hidden="true" tabindex="-1"></a> <span class="kw">case</span> <span class="dv">0</span><span class="op">:</span> <span class="kw">return</span> <span class="st">&quot;Male&quot;</span></span> +<span id="cb1-16"><a href="#cb1-16" aria-hidden="true" tabindex="-1"></a> <span class="kw">case</span> <span class="dv">1</span><span class="op">:</span> <span class="kw">return</span> <span class="st">&quot;Female&quot;</span></span> +<span id="cb1-17"><a href="#cb1-17" aria-hidden="true" tabindex="-1"></a> <span class="kw">default</span><span class="op">:</span> <span class="kw">return</span> <span class="st">&quot;Other&quot;</span></span> +<span id="cb1-18"><a href="#cb1-18" aria-hidden="true" tabindex="-1"></a> <span class="op">}</span></span> +<span id="cb1-19"><a href="#cb1-19" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span> +<span id="cb1-20"><a href="#cb1-20" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb1-21"><a href="#cb1-21" aria-hidden="true" tabindex="-1"></a><span class="co">// You can accidentally do stupid stuff like:</span></span> +<span id="cb1-22"><a href="#cb1-22" aria-hidden="true" tabindex="-1"></a>gender <span class="op">:=</span> Male <span class="op">+</span> <span class="dv">1</span></span></code></pre></div> <p>The Haskell equivalent of the same:</p> -<div class="sourceCode" id="cb2"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true"></a><span class="kw">data</span> <span class="dt">Gender</span> <span class="ot">=</span> <span class="dt">Male</span></span> -<span id="cb2-2"><a href="#cb2-2" aria-hidden="true"></a> <span class="op">|</span> <span class="dt">Female</span></span> -<span id="cb2-3"><a href="#cb2-3" aria-hidden="true"></a> <span class="op">|</span> <span class="dt">Other</span></span> -<span id="cb2-4"><a href="#cb2-4" aria-hidden="true"></a> <span class="kw">deriving</span> (<span class="dt">Show</span>)</span> -<span id="cb2-5"><a href="#cb2-5" aria-hidden="true"></a></span> -<span id="cb2-6"><a href="#cb2-6" aria-hidden="true"></a><span class="fu">print</span> <span class="op">$</span> <span class="st">&quot;My gender is &quot;</span> <span class="op">++</span> (<span class="fu">show</span> <span class="dt">Male</span>)</span></code></pre></div> +<div class="sourceCode" id="cb2"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a><span class="kw">data</span> <span class="dt">Gender</span> <span class="ot">=</span> <span class="dt">Male</span></span> +<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a> <span class="op">|</span> <span class="dt">Female</span></span> +<span id="cb2-3"><a href="#cb2-3" aria-hidden="true" tabindex="-1"></a> <span class="op">|</span> <span class="dt">Other</span></span> +<span id="cb2-4"><a href="#cb2-4" aria-hidden="true" tabindex="-1"></a> <span class="kw">deriving</span> (<span class="dt">Show</span>)</span> +<span id="cb2-5"><a href="#cb2-5" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb2-6"><a href="#cb2-6" aria-hidden="true" tabindex="-1"></a><span class="fu">print</span> <span class="op">$</span> <span class="st">&quot;My gender is &quot;</span> <span class="op">++</span> (<span class="fu">show</span> <span class="dt">Male</span>)</span></code></pre></div> <h3 id="type-assertions">Type Assertions</h3> <p>A downcast with an optional error check? What could go wrong?</p> <p>Type assertions in Go allow you to do:</p> -<div class="sourceCode" id="cb3"><pre class="sourceCode go"><code class="sourceCode go"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true"></a><span class="kw">var</span> x <span class="kw">interface</span>{} = <span class="dv">7</span></span> -<span id="cb3-2"><a href="#cb3-2" aria-hidden="true"></a>y, goodToGo := x.(<span class="dt">int</span>)</span> -<span id="cb3-3"><a href="#cb3-3" aria-hidden="true"></a><span class="kw">if</span> goodToGo {</span> -<span id="cb3-4"><a href="#cb3-4" aria-hidden="true"></a> fmt.Println(y)</span> -<span id="cb3-5"><a href="#cb3-5" aria-hidden="true"></a>}</span></code></pre></div> +<div class="sourceCode" id="cb3"><pre class="sourceCode go"><code class="sourceCode go"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a><span class="kw">var</span> x <span class="kw">interface</span><span class="op">{}</span> <span class="op">=</span> <span class="dv">7</span></span> +<span id="cb3-2"><a href="#cb3-2" aria-hidden="true" tabindex="-1"></a>y<span class="op">,</span> goodToGo <span class="op">:=</span> x<span class="op">.(</span><span class="dt">int</span><span class="op">)</span></span> +<span id="cb3-3"><a href="#cb3-3" aria-hidden="true" tabindex="-1"></a><span class="kw">if</span> goodToGo <span class="op">{</span></span> +<span id="cb3-4"><a href="#cb3-4" aria-hidden="true" tabindex="-1"></a> fmt<span class="op">.</span>Println<span class="op">(</span>y<span class="op">)</span></span> +<span id="cb3-5"><a href="#cb3-5" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code></pre></div> <p>The error check however is optional:</p> -<div class="sourceCode" id="cb4"><pre class="sourceCode go"><code class="sourceCode go"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true"></a><span class="kw">var</span> x <span class="kw">interface</span>{} = <span class="dv">7</span></span> -<span id="cb4-2"><a href="#cb4-2" aria-hidden="true"></a><span class="kw">var</span> y := x.(<span class="dt">float64</span>)</span> -<span id="cb4-3"><a href="#cb4-3" aria-hidden="true"></a>fmt.Println(y)</span> -<span id="cb4-4"><a href="#cb4-4" aria-hidden="true"></a><span class="co">// results in a runtime error:</span></span> -<span id="cb4-5"><a href="#cb4-5" aria-hidden="true"></a><span class="co">// panic: interface conversion: interface {} is int, not float64</span></span></code></pre></div> +<div class="sourceCode" id="cb4"><pre class="sourceCode go"><code class="sourceCode go"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a><span class="kw">var</span> x <span class="kw">interface</span><span class="op">{}</span> <span class="op">=</span> <span class="dv">7</span></span> +<span id="cb4-2"><a href="#cb4-2" aria-hidden="true" tabindex="-1"></a><span class="kw">var</span> y <span class="op">:=</span> x<span class="op">.(</span><span class="dt">float64</span><span class="op">)</span></span> +<span id="cb4-3"><a href="#cb4-3" aria-hidden="true" tabindex="-1"></a>fmt<span class="op">.</span>Println<span class="op">(</span>y<span class="op">)</span></span> +<span id="cb4-4"><a href="#cb4-4" aria-hidden="true" tabindex="-1"></a><span class="co">// results in a runtime error:</span></span> +<span id="cb4-5"><a href="#cb4-5" aria-hidden="true" tabindex="-1"></a><span class="co">// panic: interface conversion: interface {} is int, not float64</span></span></code></pre></div> <h3 id="date-and-time">Date and Time</h3> <p>Anyone that has written Go previously, will probably already know what I am getting at here. For the uninitiated, parsing and formatting dates in Go requires a “layout”. This “layout” is based on magical reference date:</p> <pre><code>Mon Jan 2 15:04:05 MST 2006</code></pre> <p>Which is the date produced when you write the first seven natural numbers like so:</p> <pre><code>01/02 03:04:05 &#39;06 -0700</code></pre> <p>Parsing a string in <code>YYYY-MM-DD</code> format would look something like:</p> -<div class="sourceCode" id="cb7"><pre class="sourceCode go"><code class="sourceCode go"><span id="cb7-1"><a href="#cb7-1" aria-hidden="true"></a><span class="kw">const</span> layout = <span class="st">&quot;2006-01-02&quot;</span></span> -<span id="cb7-2"><a href="#cb7-2" aria-hidden="true"></a>time.Parse(layout, <span class="st">&quot;2020-08-01&quot;</span>)</span></code></pre></div> +<div class="sourceCode" id="cb7"><pre class="sourceCode go"><code class="sourceCode go"><span id="cb7-1"><a href="#cb7-1" aria-hidden="true" tabindex="-1"></a><span class="kw">const</span> layout <span class="op">=</span> <span class="st">&quot;2006-01-02&quot;</span></span> +<span id="cb7-2"><a href="#cb7-2" aria-hidden="true" tabindex="-1"></a>time<span class="op">.</span>Parse<span class="op">(</span>layout<span class="op">,</span> <span class="st">&quot;2020-08-01&quot;</span><span class="op">)</span></span></code></pre></div> <p>This so-called “intuitive” method of formatting dates doesn’t allow you to print <code>0000 hrs</code> as <code>2400 hrs</code>, it doesn’t allow you to omit the leading zero in 24 hour formats. It is rife with inconveniences, if only there were a <a href="https://man7.org/linux/man-pages/man3/strftime.3.html">tried and tested</a> date formatting convention …</p> <h3 id="statements-over-expressions">Statements over Expressions</h3> <p>Statements have side effects, expressions return values. More often than not, expressions are easier to understand at a glance: evaluate the LHS and assign the same to the RHS.</p> <p>Rust allows you to create local namespaces, and treats blocks (<code>{}</code>) as expressions:</p> -<div class="sourceCode" id="cb8"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true"></a><span class="kw">let</span> twenty_seven <span class="op">=</span> <span class="op">{</span></span> -<span id="cb8-2"><a href="#cb8-2" aria-hidden="true"></a> <span class="kw">let</span> three <span class="op">=</span> <span class="dv">1</span> <span class="op">+</span> <span class="dv">2</span><span class="op">;</span></span> -<span id="cb8-3"><a href="#cb8-3" aria-hidden="true"></a> <span class="kw">let</span> nine <span class="op">=</span> three <span class="op">*</span> three<span class="op">;</span></span> -<span id="cb8-4"><a href="#cb8-4" aria-hidden="true"></a> nine <span class="op">*</span> three</span> -<span id="cb8-5"><a href="#cb8-5" aria-hidden="true"></a><span class="op">};</span></span></code></pre></div> +<div class="sourceCode" id="cb8"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true" tabindex="-1"></a><span class="kw">let</span> twenty_seven <span class="op">=</span> <span class="op">{</span></span> +<span id="cb8-2"><a href="#cb8-2" aria-hidden="true" tabindex="-1"></a> <span class="kw">let</span> three <span class="op">=</span> <span class="dv">1</span> <span class="op">+</span> <span class="dv">2</span><span class="op">;</span></span> +<span id="cb8-3"><a href="#cb8-3" aria-hidden="true" tabindex="-1"></a> <span class="kw">let</span> nine <span class="op">=</span> three <span class="op">*</span> three<span class="op">;</span></span> +<span id="cb8-4"><a href="#cb8-4" aria-hidden="true" tabindex="-1"></a> nine <span class="op">*</span> three</span> +<span id="cb8-5"><a href="#cb8-5" aria-hidden="true" tabindex="-1"></a><span class="op">};</span></span></code></pre></div> <p>The Go equivalent of the same:</p> -<div class="sourceCode" id="cb9"><pre class="sourceCode go"><code class="sourceCode go"><span id="cb9-1"><a href="#cb9-1" aria-hidden="true"></a>twenty_seven := <span class="ot">nil</span></span> -<span id="cb9-2"><a href="#cb9-2" aria-hidden="true"></a></span> -<span id="cb9-3"><a href="#cb9-3" aria-hidden="true"></a>three := <span class="dv">1</span> + <span class="dv">2</span></span> -<span id="cb9-4"><a href="#cb9-4" aria-hidden="true"></a>nine := three * three</span> -<span id="cb9-5"><a href="#cb9-5" aria-hidden="true"></a>twenty_seven = nine * three</span></code></pre></div> +<div class="sourceCode" id="cb9"><pre class="sourceCode go"><code class="sourceCode go"><span id="cb9-1"><a href="#cb9-1" aria-hidden="true" tabindex="-1"></a>twenty_seven <span class="op">:=</span> <span class="ot">nil</span></span> +<span id="cb9-2"><a href="#cb9-2" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb9-3"><a href="#cb9-3" aria-hidden="true" tabindex="-1"></a>three <span class="op">:=</span> <span class="dv">1</span> <span class="op">+</span> <span class="dv">2</span></span> +<span id="cb9-4"><a href="#cb9-4" aria-hidden="true" tabindex="-1"></a>nine <span class="op">:=</span> three <span class="op">*</span> three</span> +<span id="cb9-5"><a href="#cb9-5" aria-hidden="true" tabindex="-1"></a>twenty_seven <span class="op">=</span> nine <span class="op">*</span> three</span></code></pre></div> <h3 id="erroring-out-on-unused-variables">Erroring out on unused variables</h3> <p>Want to quickly prototype something? Go says no! In all seriousness, a warning would suffice, I don’t want to have to go back and comment each unused import out, only to come back and uncomment them a few seconds later.</p> <h3 id="error-handling">Error handling</h3> -<div class="sourceCode" id="cb10"><pre class="sourceCode go"><code class="sourceCode go"><span id="cb10-1"><a href="#cb10-1" aria-hidden="true"></a><span class="kw">if</span> err != <span class="ot">nil</span> { ... }</span></code></pre></div> +<div class="sourceCode" id="cb10"><pre class="sourceCode go"><code class="sourceCode go"><span id="cb10-1"><a href="#cb10-1" aria-hidden="true" tabindex="-1"></a><span class="kw">if</span> err <span class="op">!=</span> <span class="ot">nil</span> <span class="op">{</span> <span class="op">...</span> <span class="op">}</span></span></code></pre></div> <p>Need I say more? I will, for good measure:</p> <ol type="1"> <li>Error handling is optional</li> <li>Errors are propagated via a clunky <code>if</code> + <code>return</code> statement</li> </ol> <p>I prefer Haskell’s “Monadic” error handling, which is employed by Rust as well:</p> -<div class="sourceCode" id="cb11"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb11-1"><a href="#cb11-1" aria-hidden="true"></a><span class="co">// 1. error handling is compulsory</span></span> -<span id="cb11-2"><a href="#cb11-2" aria-hidden="true"></a><span class="co">// 2. errors are propagated with the `?` operator</span></span> -<span id="cb11-3"><a href="#cb11-3" aria-hidden="true"></a><span class="kw">fn</span> foo() <span class="op">-&gt;</span> <span class="dt">Result</span><span class="op">&lt;</span><span class="dt">String</span><span class="op">,</span> <span class="pp">io::</span><span class="bu">Error</span><span class="op">&gt;</span> <span class="op">{</span></span> -<span id="cb11-4"><a href="#cb11-4" aria-hidden="true"></a> <span class="kw">let</span> <span class="kw">mut</span> f <span class="op">=</span> <span class="pp">File::</span>open(<span class="st">&quot;foo.txt&quot;</span>)<span class="op">?;</span> <span class="co">// return if error</span></span> -<span id="cb11-5"><a href="#cb11-5" aria-hidden="true"></a> <span class="kw">let</span> <span class="kw">mut</span> s <span class="op">=</span> <span class="dt">String</span><span class="pp">::</span>new()<span class="op">;</span></span> -<span id="cb11-6"><a href="#cb11-6" aria-hidden="true"></a></span> -<span id="cb11-7"><a href="#cb11-7" aria-hidden="true"></a> f<span class="op">.</span>read_to_string(<span class="op">&amp;</span><span class="kw">mut</span> s)<span class="op">?;</span> <span class="co">// return if error</span></span> -<span id="cb11-8"><a href="#cb11-8" aria-hidden="true"></a></span> -<span id="cb11-9"><a href="#cb11-9" aria-hidden="true"></a> <span class="cn">Ok</span>(s) <span class="co">// all good, return a string inside a `Result` context</span></span> -<span id="cb11-10"><a href="#cb11-10" aria-hidden="true"></a><span class="op">}</span></span> -<span id="cb11-11"><a href="#cb11-11" aria-hidden="true"></a></span> -<span id="cb11-12"><a href="#cb11-12" aria-hidden="true"></a><span class="kw">fn</span> main() <span class="op">{</span></span> -<span id="cb11-13"><a href="#cb11-13" aria-hidden="true"></a> <span class="co">// `contents` is an enum known as Result:</span></span> -<span id="cb11-14"><a href="#cb11-14" aria-hidden="true"></a> <span class="kw">let</span> contents <span class="op">=</span> foo()<span class="op">;</span></span> -<span id="cb11-15"><a href="#cb11-15" aria-hidden="true"></a> <span class="kw">match</span> contents <span class="op">{</span></span> -<span id="cb11-16"><a href="#cb11-16" aria-hidden="true"></a> <span class="cn">Ok</span>(c) <span class="op">=&gt;</span> <span class="pp">println!</span>(c)<span class="op">,</span></span> -<span id="cb11-17"><a href="#cb11-17" aria-hidden="true"></a> <span class="cn">Err</span>(e) <span class="op">=&gt;</span> <span class="pp">eprintln!</span>(e)</span> -<span id="cb11-18"><a href="#cb11-18" aria-hidden="true"></a> <span class="op">}</span></span> -<span id="cb11-19"><a href="#cb11-19" aria-hidden="true"></a><span class="op">}</span></span></code></pre></div> +<div class="sourceCode" id="cb11"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb11-1"><a href="#cb11-1" aria-hidden="true" tabindex="-1"></a><span class="co">// 1. error handling is compulsory</span></span> +<span id="cb11-2"><a href="#cb11-2" aria-hidden="true" tabindex="-1"></a><span class="co">// 2. errors are propagated with the `?` operator</span></span> +<span id="cb11-3"><a href="#cb11-3" aria-hidden="true" tabindex="-1"></a><span class="kw">fn</span> foo() <span class="op">-&gt;</span> <span class="dt">Result</span><span class="op">&lt;</span><span class="dt">String</span><span class="op">,</span> <span class="pp">io::</span><span class="bu">Error</span><span class="op">&gt;</span> <span class="op">{</span></span> +<span id="cb11-4"><a href="#cb11-4" aria-hidden="true" tabindex="-1"></a> <span class="kw">let</span> <span class="kw">mut</span> f <span class="op">=</span> <span class="pp">File::</span>open(<span class="st">&quot;foo.txt&quot;</span>)<span class="op">?;</span> <span class="co">// return if error</span></span> +<span id="cb11-5"><a href="#cb11-5" aria-hidden="true" tabindex="-1"></a> <span class="kw">let</span> <span class="kw">mut</span> s <span class="op">=</span> <span class="dt">String</span><span class="pp">::</span>new()<span class="op">;</span></span> +<span id="cb11-6"><a href="#cb11-6" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb11-7"><a href="#cb11-7" aria-hidden="true" tabindex="-1"></a> f<span class="op">.</span>read_to_string(<span class="op">&amp;</span><span class="kw">mut</span> s)<span class="op">?;</span> <span class="co">// return if error</span></span> +<span id="cb11-8"><a href="#cb11-8" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb11-9"><a href="#cb11-9" aria-hidden="true" tabindex="-1"></a> <span class="cn">Ok</span>(s) <span class="co">// all good, return a string inside a `Result` context</span></span> +<span id="cb11-10"><a href="#cb11-10" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span> +<span id="cb11-11"><a href="#cb11-11" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb11-12"><a href="#cb11-12" aria-hidden="true" tabindex="-1"></a><span class="kw">fn</span> main() <span class="op">{</span></span> +<span id="cb11-13"><a href="#cb11-13" aria-hidden="true" tabindex="-1"></a> <span class="co">// `contents` is an enum known as Result:</span></span> +<span id="cb11-14"><a href="#cb11-14" aria-hidden="true" tabindex="-1"></a> <span class="kw">let</span> contents <span class="op">=</span> foo()<span class="op">;</span></span> +<span id="cb11-15"><a href="#cb11-15" aria-hidden="true" tabindex="-1"></a> <span class="kw">match</span> contents <span class="op">{</span></span> +<span id="cb11-16"><a href="#cb11-16" aria-hidden="true" tabindex="-1"></a> <span class="cn">Ok</span>(c) <span class="op">=&gt;</span> <span class="pp">println!</span>(c)<span class="op">,</span></span> +<span id="cb11-17"><a href="#cb11-17" aria-hidden="true" tabindex="-1"></a> <span class="cn">Err</span>(e) <span class="op">=&gt;</span> <span class="pp">eprintln!</span>(e)</span> +<span id="cb11-18"><a href="#cb11-18" aria-hidden="true" tabindex="-1"></a> <span class="op">}</span></span> +<span id="cb11-19"><a href="#cb11-19" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code></pre></div> <h3 id="conclusion">Conclusion</h3> <p>I did not want to conclude without talking about stylistic choices, lack of metaprogramming, bizzare export rules, but, I am too busy converting my <code>interface{}</code> types into actual generic code for Go v2.</p> https://peppe.rs/posts/gripes_with_go/ @@ -500,17 +500,17 @@ h(x)(y)(z) = g(y)(z) = k(z) = v</code></pre> <p>We will be using Attribute macros to convert a Rust function into a curried Rust function, which we should be able to call via: <code>function(arg1)(arg2)</code>.</p> <h3 id="definitions">Definitions</h3> <p>Being respectable programmers, we define the input to and the output from our proc-macro. Here’s a good non-trivial function to start out with:</p> -<div class="sourceCode" id="cb4"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true"></a><span class="kw">fn</span> add(x<span class="op">:</span> <span class="dt">u32</span><span class="op">,</span> y<span class="op">:</span> <span class="dt">u32</span><span class="op">,</span> z<span class="op">:</span> <span class="dt">u32</span>) <span class="op">-&gt;</span> <span class="dt">u32</span> <span class="op">{</span></span> -<span id="cb4-2"><a href="#cb4-2" aria-hidden="true"></a> <span class="kw">return</span> x <span class="op">+</span> y <span class="op">+</span> z<span class="op">;</span></span> -<span id="cb4-3"><a href="#cb4-3" aria-hidden="true"></a><span class="op">}</span></span></code></pre></div> +<div class="sourceCode" id="cb4"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a><span class="kw">fn</span> add(x<span class="op">:</span> <span class="dt">u32</span><span class="op">,</span> y<span class="op">:</span> <span class="dt">u32</span><span class="op">,</span> z<span class="op">:</span> <span class="dt">u32</span>) <span class="op">-&gt;</span> <span class="dt">u32</span> <span class="op">{</span></span> +<span id="cb4-2"><a href="#cb4-2" aria-hidden="true" tabindex="-1"></a> <span class="kw">return</span> x <span class="op">+</span> y <span class="op">+</span> z<span class="op">;</span></span> +<span id="cb4-3"><a href="#cb4-3" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code></pre></div> <p>Hmm, what would our output look like? What should our proc-macro generate ideally? Well, if we understood currying correctly, we should accept an argument and return a function that accepts an argument and returns … you get the point. Something like this should do:</p> -<div class="sourceCode" id="cb5"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb5-1"><a href="#cb5-1" aria-hidden="true"></a><span class="kw">fn</span> add_curried1(x<span class="op">:</span> <span class="dt">u32</span>) <span class="op">-&gt;</span> <span class="op">?</span> <span class="op">{</span></span> -<span id="cb5-2"><a href="#cb5-2" aria-hidden="true"></a> <span class="kw">return</span> <span class="kw">fn</span> add_curried2 (y<span class="op">:</span> <span class="dt">u32</span>) <span class="op">-&gt;</span> <span class="op">?</span> <span class="op">{</span></span> -<span id="cb5-3"><a href="#cb5-3" aria-hidden="true"></a> <span class="kw">return</span> <span class="kw">fn</span> add_curried3 (z<span class="op">:</span> <span class="dt">u32</span>) <span class="op">-&gt;</span> <span class="dt">u32</span> <span class="op">{</span></span> -<span id="cb5-4"><a href="#cb5-4" aria-hidden="true"></a> <span class="kw">return</span> x <span class="op">+</span> y <span class="op">+</span> z<span class="op">;</span></span> -<span id="cb5-5"><a href="#cb5-5" aria-hidden="true"></a> <span class="op">}</span></span> -<span id="cb5-6"><a href="#cb5-6" aria-hidden="true"></a> <span class="op">}</span></span> -<span id="cb5-7"><a href="#cb5-7" aria-hidden="true"></a><span class="op">}</span></span></code></pre></div> +<div class="sourceCode" id="cb5"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb5-1"><a href="#cb5-1" aria-hidden="true" tabindex="-1"></a><span class="kw">fn</span> add_curried1(x<span class="op">:</span> <span class="dt">u32</span>) <span class="op">-&gt;</span> <span class="op">?</span> <span class="op">{</span></span> +<span id="cb5-2"><a href="#cb5-2" aria-hidden="true" tabindex="-1"></a> <span class="kw">return</span> <span class="kw">fn</span> add_curried2 (y<span class="op">:</span> <span class="dt">u32</span>) <span class="op">-&gt;</span> <span class="op">?</span> <span class="op">{</span></span> +<span id="cb5-3"><a href="#cb5-3" aria-hidden="true" tabindex="-1"></a> <span class="kw">return</span> <span class="kw">fn</span> add_curried3 (z<span class="op">:</span> <span class="dt">u32</span>) <span class="op">-&gt;</span> <span class="dt">u32</span> <span class="op">{</span></span> +<span id="cb5-4"><a href="#cb5-4" aria-hidden="true" tabindex="-1"></a> <span class="kw">return</span> x <span class="op">+</span> y <span class="op">+</span> z<span class="op">;</span></span> +<span id="cb5-5"><a href="#cb5-5" aria-hidden="true" tabindex="-1"></a> <span class="op">}</span></span> +<span id="cb5-6"><a href="#cb5-6" aria-hidden="true" tabindex="-1"></a> <span class="op">}</span></span> +<span id="cb5-7"><a href="#cb5-7" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code></pre></div> <p>A couple of things to note:</p> <p><strong>Return types</strong><br /> We have placed <code>?</code>s in place of return types. Let’s try to fix that. <code>add_curried3</code> returns the ‘value’, so <code>u32</code> is accurate. <code>add_curried2</code> returns <code>add_curried3</code>. What is the type of <code>add_curried3</code>? It is a function that takes in a <code>u32</code> and returns a <code>u32</code>. So a <code>fn(u32) -&gt; u32</code> will do right? No, I’ll explain why in the next point, but for now, we will make use of the <code>Fn</code> trait, our return type is <code>impl Fn(u32) -&gt; u32</code>. This basically tells the compiler that we will be returning something function-like, a.k.a, behaves like a <code>Fn</code>. Cool!</p> @@ -523,9 +523,9 @@ We have placed <code>?</code>s in place of return types. Let’s try A function cannot access it’s environment. Our solution will not work. <code>add_curried3</code> attempts to access <code>x</code>, which is not allowed! A closure<a href="#fn1" class="footnote-ref" id="fnref1" role="doc-noteref"><sup>1</sup></a> however, can. If we are returning a closure, our return type must be <code>impl Fn</code>, and not <code>fn</code>. The difference between the <code>Fn</code> trait and function pointers is beyond the scope of this post.</p> <h3 id="refinement">Refinement</h3> <p>Armed with knowledge, we refine our expected output, this time, employing closures:</p> -<div class="sourceCode" id="cb8"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true"></a><span class="kw">fn</span> add(x<span class="op">:</span> <span class="dt">u32</span>) <span class="op">-&gt;</span> <span class="kw">impl</span> <span class="bu">Fn</span>(<span class="dt">u32</span>) <span class="op">-&gt;</span> <span class="kw">impl</span> <span class="bu">Fn</span>(<span class="dt">u32</span>) <span class="op">-&gt;</span> <span class="dt">u32</span> <span class="op">{</span></span> -<span id="cb8-2"><a href="#cb8-2" aria-hidden="true"></a> <span class="kw">return</span> <span class="kw">move</span> <span class="op">|</span>y<span class="op">|</span> <span class="kw">move</span> <span class="op">|</span>z<span class="op">|</span> x <span class="op">+</span> y <span class="op">+</span> z<span class="op">;</span></span> -<span id="cb8-3"><a href="#cb8-3" aria-hidden="true"></a><span class="op">}</span></span></code></pre></div> +<div class="sourceCode" id="cb8"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true" tabindex="-1"></a><span class="kw">fn</span> add(x<span class="op">:</span> <span class="dt">u32</span>) <span class="op">-&gt;</span> <span class="kw">impl</span> <span class="bu">Fn</span>(<span class="dt">u32</span>) <span class="op">-&gt;</span> <span class="kw">impl</span> <span class="bu">Fn</span>(<span class="dt">u32</span>) <span class="op">-&gt;</span> <span class="dt">u32</span> <span class="op">{</span></span> +<span id="cb8-2"><a href="#cb8-2" aria-hidden="true" tabindex="-1"></a> <span class="kw">return</span> <span class="kw">move</span> <span class="op">|</span>y<span class="op">|</span> <span class="kw">move</span> <span class="op">|</span>z<span class="op">|</span> x <span class="op">+</span> y <span class="op">+</span> z<span class="op">;</span></span> +<span id="cb8-3"><a href="#cb8-3" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code></pre></div> <p>Alas, that does not compile either! It errors out with the following message:</p> <pre><code>error[E0562]: `impl Trait` not allowed outside of function and inherent method return types @@ -536,15 +536,15 @@ and inherent method return types </code></pre> <p>You are allowed to return an <code>impl Fn</code> only inside a function. We are currently returning it from another return! Or at least, that was the most I could make out of the error message.</p> <p>We are going to have to cheat a bit to fix this issue; with type aliases and a convenient nightly feature <a href="#fn2" class="footnote-ref" id="fnref2" role="doc-noteref"><sup>2</sup></a>:</p> -<div class="sourceCode" id="cb10"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb10-1"><a href="#cb10-1" aria-hidden="true"></a><span class="at">#![</span>feature<span class="at">(</span>type_alias_impl_trait<span class="at">)]</span> <span class="co">// allows us to use `impl Fn` in type aliases!</span></span> -<span id="cb10-2"><a href="#cb10-2" aria-hidden="true"></a></span> -<span id="cb10-3"><a href="#cb10-3" aria-hidden="true"></a><span class="kw">type</span> T0 <span class="op">=</span> <span class="dt">u32</span><span class="op">;</span> <span class="co">// the return value when zero args are to be applied</span></span> -<span id="cb10-4"><a href="#cb10-4" aria-hidden="true"></a><span class="kw">type</span> T1 <span class="op">=</span> <span class="kw">impl</span> <span class="bu">Fn</span>(<span class="dt">u32</span>) <span class="op">-&gt;</span> T0<span class="op">;</span> <span class="co">// the return value when one arg is to be applied</span></span> -<span id="cb10-5"><a href="#cb10-5" aria-hidden="true"></a><span class="kw">type</span> T2 <span class="op">=</span> <span class="kw">impl</span> <span class="bu">Fn</span>(<span class="dt">u32</span>) <span class="op">-&gt;</span> T1<span class="op">;</span> <span class="co">// the return value when two args are to be applied</span></span> -<span id="cb10-6"><a href="#cb10-6" aria-hidden="true"></a></span> -<span id="cb10-7"><a href="#cb10-7" aria-hidden="true"></a><span class="kw">fn</span> add(x<span class="op">:</span> <span class="dt">u32</span>) <span class="op">-&gt;</span> T2 <span class="op">{</span></span> -<span id="cb10-8"><a href="#cb10-8" aria-hidden="true"></a> <span class="kw">return</span> <span class="kw">move</span> <span class="op">|</span>y<span class="op">|</span> <span class="kw">move</span> <span class="op">|</span>z<span class="op">|</span> x <span class="op">+</span> y <span class="op">+</span> z<span class="op">;</span></span> -<span id="cb10-9"><a href="#cb10-9" aria-hidden="true"></a><span class="op">}</span></span></code></pre></div> +<div class="sourceCode" id="cb10"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb10-1"><a href="#cb10-1" aria-hidden="true" tabindex="-1"></a><span class="at">#![</span>feature<span class="at">(</span>type_alias_impl_trait<span class="at">)]</span> <span class="co">// allows us to use `impl Fn` in type aliases!</span></span> +<span id="cb10-2"><a href="#cb10-2" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb10-3"><a href="#cb10-3" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> T0 <span class="op">=</span> <span class="dt">u32</span><span class="op">;</span> <span class="co">// the return value when zero args are to be applied</span></span> +<span id="cb10-4"><a href="#cb10-4" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> T1 <span class="op">=</span> <span class="kw">impl</span> <span class="bu">Fn</span>(<span class="dt">u32</span>) <span class="op">-&gt;</span> T0<span class="op">;</span> <span class="co">// the return value when one arg is to be applied</span></span> +<span id="cb10-5"><a href="#cb10-5" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> T2 <span class="op">=</span> <span class="kw">impl</span> <span class="bu">Fn</span>(<span class="dt">u32</span>) <span class="op">-&gt;</span> T1<span class="op">;</span> <span class="co">// the return value when two args are to be applied</span></span> +<span id="cb10-6"><a href="#cb10-6" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb10-7"><a href="#cb10-7" aria-hidden="true" tabindex="-1"></a><span class="kw">fn</span> add(x<span class="op">:</span> <span class="dt">u32</span>) <span class="op">-&gt;</span> T2 <span class="op">{</span></span> +<span id="cb10-8"><a href="#cb10-8" aria-hidden="true" tabindex="-1"></a> <span class="kw">return</span> <span class="kw">move</span> <span class="op">|</span>y<span class="op">|</span> <span class="kw">move</span> <span class="op">|</span>z<span class="op">|</span> x <span class="op">+</span> y <span class="op">+</span> z<span class="op">;</span></span> +<span id="cb10-9"><a href="#cb10-9" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code></pre></div> <p>Drop that into a cargo project, call <code>add(4)(5)(6)</code>, cross your fingers, and run <code>cargo +nightly run</code>. You should see a 15 unless you forgot to print it!</p> <h3 id="the-in-betweens">The In-Betweens</h3> <p>Let us write the magical bits that take us from function to curried function.</p> @@ -578,19 +578,19 @@ proc-macro = true # this is important!</code></pre> <p>We will be using an external <code>proc-macro2</code> crate as well as an internal <code>proc-macro</code> crate. Not confusing at all!</p> <h4 id="the-attribute-macro">The attribute macro</h4> <p>Drop this into <code>src/lib.rs</code>, to get the ball rolling.</p> -<div class="sourceCode" id="cb13"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb13-1"><a href="#cb13-1" aria-hidden="true"></a><span class="co">// src/lib.rs</span></span> -<span id="cb13-2"><a href="#cb13-2" aria-hidden="true"></a></span> -<span id="cb13-3"><a href="#cb13-3" aria-hidden="true"></a><span class="kw">use</span> <span class="pp">proc_macro::</span>TokenStream<span class="op">;</span> <span class="co">// 1</span></span> -<span id="cb13-4"><a href="#cb13-4" aria-hidden="true"></a><span class="kw">use</span> <span class="pp">quote::</span>quote<span class="op">;</span></span> -<span id="cb13-5"><a href="#cb13-5" aria-hidden="true"></a><span class="kw">use</span> <span class="pp">syn::</span><span class="op">{</span>parse_macro_input<span class="op">,</span> ItemFn<span class="op">};</span></span> -<span id="cb13-6"><a href="#cb13-6" aria-hidden="true"></a></span> -<span id="cb13-7"><a href="#cb13-7" aria-hidden="true"></a><span class="at">#[</span>proc_macro_attribute<span class="at">]</span> <span class="co">// 2</span></span> -<span id="cb13-8"><a href="#cb13-8" aria-hidden="true"></a><span class="kw">pub</span> <span class="kw">fn</span> curry(_attr<span class="op">:</span> TokenStream<span class="op">,</span> item<span class="op">:</span> TokenStream) <span class="op">-&gt;</span> TokenStream <span class="op">{</span></span> -<span id="cb13-9"><a href="#cb13-9" aria-hidden="true"></a> <span class="kw">let</span> parsed <span class="op">=</span> <span class="pp">parse_macro_input!</span>(item <span class="kw">as</span> ItemFn)<span class="op">;</span> <span class="co">// 3</span></span> -<span id="cb13-10"><a href="#cb13-10" aria-hidden="true"></a> generate_curry(parsed)<span class="op">.</span>into() <span class="co">// 4</span></span> -<span id="cb13-11"><a href="#cb13-11" aria-hidden="true"></a><span class="op">}</span></span> -<span id="cb13-12"><a href="#cb13-12" aria-hidden="true"></a></span> -<span id="cb13-13"><a href="#cb13-13" aria-hidden="true"></a><span class="kw">fn</span> generate_curry(parsed<span class="op">:</span> ItemFn) <span class="op">-&gt;</span> <span class="pp">proc_macro2::</span>TokenStream <span class="op">{}</span></span></code></pre></div> +<div class="sourceCode" id="cb13"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb13-1"><a href="#cb13-1" aria-hidden="true" tabindex="-1"></a><span class="co">// src/lib.rs</span></span> +<span id="cb13-2"><a href="#cb13-2" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb13-3"><a href="#cb13-3" aria-hidden="true" tabindex="-1"></a><span class="kw">use</span> <span class="pp">proc_macro::</span>TokenStream<span class="op">;</span> <span class="co">// 1</span></span> +<span id="cb13-4"><a href="#cb13-4" aria-hidden="true" tabindex="-1"></a><span class="kw">use</span> <span class="pp">quote::</span>quote<span class="op">;</span></span> +<span id="cb13-5"><a href="#cb13-5" aria-hidden="true" tabindex="-1"></a><span class="kw">use</span> <span class="pp">syn::</span><span class="op">{</span>parse_macro_input<span class="op">,</span> ItemFn<span class="op">};</span></span> +<span id="cb13-6"><a href="#cb13-6" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb13-7"><a href="#cb13-7" aria-hidden="true" tabindex="-1"></a><span class="at">#[</span>proc_macro_attribute<span class="at">]</span> <span class="co">// 2</span></span> +<span id="cb13-8"><a href="#cb13-8" aria-hidden="true" tabindex="-1"></a><span class="kw">pub</span> <span class="kw">fn</span> curry(_attr<span class="op">:</span> TokenStream<span class="op">,</span> item<span class="op">:</span> TokenStream) <span class="op">-&gt;</span> TokenStream <span class="op">{</span></span> +<span id="cb13-9"><a href="#cb13-9" aria-hidden="true" tabindex="-1"></a> <span class="kw">let</span> parsed <span class="op">=</span> <span class="pp">parse_macro_input!</span>(item <span class="kw">as</span> ItemFn)<span class="op">;</span> <span class="co">// 3</span></span> +<span id="cb13-10"><a href="#cb13-10" aria-hidden="true" tabindex="-1"></a> generate_curry(parsed)<span class="op">.</span>into() <span class="co">// 4</span></span> +<span id="cb13-11"><a href="#cb13-11" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span> +<span id="cb13-12"><a href="#cb13-12" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb13-13"><a href="#cb13-13" aria-hidden="true" tabindex="-1"></a><span class="kw">fn</span> generate_curry(parsed<span class="op">:</span> ItemFn) <span class="op">-&gt;</span> <span class="pp">proc_macro2::</span>TokenStream <span class="op">{}</span></span></code></pre></div> <p><strong>1. Imports</strong></p> <p>A <code>Tokenstream</code> holds (hopefully valid) Rust code, this is the type of our input and output. Note that we are importing this type from <code>proc_macro</code> and not <code>proc_macro2</code>.</p> <p><code>quote!</code> from the <code>quote</code> crate is a macro that allows us to quickly produce <code>TokenStream</code>s. Much like the LISP <code>quote</code> procedure, you can use the <code>quote!</code> macro for symbolic transformations.</p> @@ -602,16 +602,16 @@ proc-macro = true # this is important!</code></pre> <p><strong>4. Returning <code>TokenStream</code>s </strong></p> <p>We haven’t filled in <code>generate_curry</code> yet, but we can see that it returns a <code>proc_macro2::TokenStream</code> and not a <code>proc_macro::TokenStream</code>, so drop a <code>.into()</code> to convert it.</p> <p>Lets move on, and fill in <code>generate_curry</code>, I would suggest keeping the documentation for <a href="https://docs.rs/syn/1.0.19/syn/struct.ItemFn.html"><code>syn::ItemFn</code></a> and <a href="https://docs.rs/syn/1.0.19/syn/struct.Signature.html"><code>syn::Signature</code></a> open.</p> -<div class="sourceCode" id="cb14"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb14-1"><a href="#cb14-1" aria-hidden="true"></a><span class="co">// src/lib.rs</span></span> -<span id="cb14-2"><a href="#cb14-2" aria-hidden="true"></a></span> -<span id="cb14-3"><a href="#cb14-3" aria-hidden="true"></a><span class="kw">fn</span> generate_curry(parsed<span class="op">:</span> ItemFn) <span class="op">-&gt;</span> <span class="pp">proc_macro2::</span>TokenStream <span class="op">{</span></span> -<span id="cb14-4"><a href="#cb14-4" aria-hidden="true"></a> <span class="kw">let</span> fn_body <span class="op">=</span> parsed<span class="op">.</span>block<span class="op">;</span> <span class="co">// function body</span></span> -<span id="cb14-5"><a href="#cb14-5" aria-hidden="true"></a> <span class="kw">let</span> sig <span class="op">=</span> parsed<span class="op">.</span>sig<span class="op">;</span> <span class="co">// function signature</span></span> -<span id="cb14-6"><a href="#cb14-6" aria-hidden="true"></a> <span class="kw">let</span> vis <span class="op">=</span> parsed<span class="op">.</span>vis<span class="op">;</span> <span class="co">// visibility, pub or not</span></span> -<span id="cb14-7"><a href="#cb14-7" aria-hidden="true"></a> <span class="kw">let</span> fn_name <span class="op">=</span> sig<span class="op">.</span>ident<span class="op">;</span> <span class="co">// function name/identifier</span></span> -<span id="cb14-8"><a href="#cb14-8" aria-hidden="true"></a> <span class="kw">let</span> fn_args <span class="op">=</span> sig<span class="op">.</span>inputs<span class="op">;</span> <span class="co">// comma separated args</span></span> -<span id="cb14-9"><a href="#cb14-9" aria-hidden="true"></a> <span class="kw">let</span> fn_return_type <span class="op">=</span> sig<span class="op">.</span>output<span class="op">;</span> <span class="co">// return type</span></span> -<span id="cb14-10"><a href="#cb14-10" aria-hidden="true"></a><span class="op">}</span></span></code></pre></div> +<div class="sourceCode" id="cb14"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb14-1"><a href="#cb14-1" aria-hidden="true" tabindex="-1"></a><span class="co">// src/lib.rs</span></span> +<span id="cb14-2"><a href="#cb14-2" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb14-3"><a href="#cb14-3" aria-hidden="true" tabindex="-1"></a><span class="kw">fn</span> generate_curry(parsed<span class="op">:</span> ItemFn) <span class="op">-&gt;</span> <span class="pp">proc_macro2::</span>TokenStream <span class="op">{</span></span> +<span id="cb14-4"><a href="#cb14-4" aria-hidden="true" tabindex="-1"></a> <span class="kw">let</span> fn_body <span class="op">=</span> parsed<span class="op">.</span>block<span class="op">;</span> <span class="co">// function body</span></span> +<span id="cb14-5"><a href="#cb14-5" aria-hidden="true" tabindex="-1"></a> <span class="kw">let</span> sig <span class="op">=</span> parsed<span class="op">.</span>sig<span class="op">;</span> <span class="co">// function signature</span></span> +<span id="cb14-6"><a href="#cb14-6" aria-hidden="true" tabindex="-1"></a> <span class="kw">let</span> vis <span class="op">=</span> parsed<span class="op">.</span>vis<span class="op">;</span> <span class="co">// visibility, pub or not</span></span> +<span id="cb14-7"><a href="#cb14-7" aria-hidden="true" tabindex="-1"></a> <span class="kw">let</span> fn_name <span class="op">=</span> sig<span class="op">.</span>ident<span class="op">;</span> <span class="co">// function name/identifier</span></span> +<span id="cb14-8"><a href="#cb14-8" aria-hidden="true" tabindex="-1"></a> <span class="kw">let</span> fn_args <span class="op">=</span> sig<span class="op">.</span>inputs<span class="op">;</span> <span class="co">// comma separated args</span></span> +<span id="cb14-9"><a href="#cb14-9" aria-hidden="true" tabindex="-1"></a> <span class="kw">let</span> fn_return_type <span class="op">=</span> sig<span class="op">.</span>output<span class="op">;</span> <span class="co">// return type</span></span> +<span id="cb14-10"><a href="#cb14-10" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code></pre></div> <p>We are simply extracting the bits of the function, we will be reusing the original function’s visibility and name. Take a look at what <code>syn::Signature</code> can tell us about a function:</p> <pre><code> .-- syn::Ident (ident) / @@ -623,220 +623,220 @@ syn::token::Fn --&#39; / \ (output) <p>Enough analysis, lets produce our first bit of Rust code.</p> <h4 id="function-body">Function Body</h4> <p>Recall that the body of a curried <code>add</code> should look like this:</p> -<div class="sourceCode" id="cb16"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb16-1"><a href="#cb16-1" aria-hidden="true"></a><span class="kw">return</span> <span class="kw">move</span> <span class="op">|</span>y<span class="op">|</span> <span class="kw">move</span> <span class="op">|</span>z<span class="op">|</span> x <span class="op">+</span> y <span class="op">+</span> z<span class="op">;</span></span></code></pre></div> +<div class="sourceCode" id="cb16"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb16-1"><a href="#cb16-1" aria-hidden="true" tabindex="-1"></a><span class="kw">return</span> <span class="kw">move</span> <span class="op">|</span>y<span class="op">|</span> <span class="kw">move</span> <span class="op">|</span>z<span class="op">|</span> x <span class="op">+</span> y <span class="op">+</span> z<span class="op">;</span></span></code></pre></div> <p>And in general:</p> -<div class="sourceCode" id="cb17"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb17-1"><a href="#cb17-1" aria-hidden="true"></a><span class="kw">return</span> <span class="kw">move</span> <span class="op">|</span>arg2<span class="op">|</span> <span class="kw">move</span> <span class="op">|</span>arg3<span class="op">|</span> <span class="op">...</span> <span class="op">|</span>argN<span class="op">|</span> <span class="op">&lt;</span>function body here<span class="op">&gt;</span></span></code></pre></div> +<div class="sourceCode" id="cb17"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb17-1"><a href="#cb17-1" aria-hidden="true" tabindex="-1"></a><span class="kw">return</span> <span class="kw">move</span> <span class="op">|</span>arg2<span class="op">|</span> <span class="kw">move</span> <span class="op">|</span>arg3<span class="op">|</span> <span class="op">...</span> <span class="op">|</span>argN<span class="op">|</span> <span class="op">&lt;</span>function body here<span class="op">&gt;</span></span></code></pre></div> <p>We already have the function’s body, provided by <code>fn_body</code>, in our <code>generate_curry</code> function. All that’s left to add is the <code>move |arg2| move |arg3| ...</code> stuff, for which we need to extract the argument identifiers (doc: <a href="https://docs.rs/syn/1.0.18/syn/punctuated/struct.Punctuated.html">Punctuated</a>, <a href="https://docs.rs/syn/1.0.18/syn/enum.FnArg.html">FnArg</a>, <a href="https://docs.rs/syn/1.0.18/syn/struct.PatType.html">PatType</a>):</p> -<div class="sourceCode" id="cb18"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb18-1"><a href="#cb18-1" aria-hidden="true"></a><span class="co">// src/lib.rs</span></span> -<span id="cb18-2"><a href="#cb18-2" aria-hidden="true"></a><span class="kw">use</span> <span class="pp">syn::punctuated::</span>Punctuated<span class="op">;</span></span> -<span id="cb18-3"><a href="#cb18-3" aria-hidden="true"></a><span class="kw">use</span> <span class="pp">syn::</span><span class="op">{</span>parse_macro_input<span class="op">,</span> FnArg<span class="op">,</span> Pat<span class="op">,</span> ItemFn<span class="op">,</span> Block<span class="op">};</span></span> -<span id="cb18-4"><a href="#cb18-4" aria-hidden="true"></a></span> -<span id="cb18-5"><a href="#cb18-5" aria-hidden="true"></a><span class="kw">fn</span> extract_arg_idents(fn_args<span class="op">:</span> Punctuated<span class="op">&lt;</span>FnArg<span class="op">,</span> <span class="pp">syn::token::</span>Comma<span class="op">&gt;</span>) <span class="op">-&gt;</span> <span class="dt">Vec</span><span class="op">&lt;</span><span class="dt">Box</span><span class="op">&lt;</span>Pat<span class="op">&gt;&gt;</span> <span class="op">{</span> </span> -<span id="cb18-6"><a href="#cb18-6" aria-hidden="true"></a> <span class="kw">return</span> fn_args<span class="op">.</span>into_iter()<span class="op">.</span>map(extract_arg_pat)<span class="op">.</span><span class="pp">collect::</span><span class="op">&lt;</span><span class="dt">Vec</span><span class="op">&lt;</span>_<span class="op">&gt;&gt;</span>()<span class="op">;</span></span> -<span id="cb18-7"><a href="#cb18-7" aria-hidden="true"></a><span class="op">}</span></span></code></pre></div> +<div class="sourceCode" id="cb18"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb18-1"><a href="#cb18-1" aria-hidden="true" tabindex="-1"></a><span class="co">// src/lib.rs</span></span> +<span id="cb18-2"><a href="#cb18-2" aria-hidden="true" tabindex="-1"></a><span class="kw">use</span> <span class="pp">syn::punctuated::</span>Punctuated<span class="op">;</span></span> +<span id="cb18-3"><a href="#cb18-3" aria-hidden="true" tabindex="-1"></a><span class="kw">use</span> <span class="pp">syn::</span><span class="op">{</span>parse_macro_input<span class="op">,</span> FnArg<span class="op">,</span> Pat<span class="op">,</span> ItemFn<span class="op">,</span> Block<span class="op">};</span></span> +<span id="cb18-4"><a href="#cb18-4" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb18-5"><a href="#cb18-5" aria-hidden="true" tabindex="-1"></a><span class="kw">fn</span> extract_arg_idents(fn_args<span class="op">:</span> Punctuated<span class="op">&lt;</span>FnArg<span class="op">,</span> <span class="pp">syn::token::</span>Comma<span class="op">&gt;</span>) <span class="op">-&gt;</span> <span class="dt">Vec</span><span class="op">&lt;</span><span class="dt">Box</span><span class="op">&lt;</span>Pat<span class="op">&gt;&gt;</span> <span class="op">{</span> </span> +<span id="cb18-6"><a href="#cb18-6" aria-hidden="true" tabindex="-1"></a> <span class="kw">return</span> fn_args<span class="op">.</span>into_iter()<span class="op">.</span>map(extract_arg_pat)<span class="op">.</span><span class="pp">collect::</span><span class="op">&lt;</span><span class="dt">Vec</span><span class="op">&lt;</span>_<span class="op">&gt;&gt;</span>()<span class="op">;</span></span> +<span id="cb18-7"><a href="#cb18-7" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code></pre></div> <p>Alright, so we are iterating over function args (<code>Punctuated</code> is a collection that you can iterate over) and mapping an <code>extract_arg_pat</code> to every item. What’s <code>extract_arg_pat</code>?</p> -<div class="sourceCode" id="cb19"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb19-1"><a href="#cb19-1" aria-hidden="true"></a><span class="co">// src/lib.rs</span></span> -<span id="cb19-2"><a href="#cb19-2" aria-hidden="true"></a></span> -<span id="cb19-3"><a href="#cb19-3" aria-hidden="true"></a><span class="kw">fn</span> extract_arg_pat(a<span class="op">:</span> FnArg) <span class="op">-&gt;</span> <span class="dt">Box</span><span class="op">&lt;</span>Pat<span class="op">&gt;</span> <span class="op">{</span></span> -<span id="cb19-4"><a href="#cb19-4" aria-hidden="true"></a> <span class="kw">match</span> a <span class="op">{</span></span> -<span id="cb19-5"><a href="#cb19-5" aria-hidden="true"></a> <span class="pp">FnArg::</span>Typed(p) <span class="op">=&gt;</span> p<span class="op">.</span>pat<span class="op">,</span></span> -<span id="cb19-6"><a href="#cb19-6" aria-hidden="true"></a> _ <span class="op">=&gt;</span> <span class="pp">panic!</span>(<span class="st">&quot;Not supported on types with `self`!&quot;</span>)<span class="op">,</span></span> -<span id="cb19-7"><a href="#cb19-7" aria-hidden="true"></a> <span class="op">}</span></span> -<span id="cb19-8"><a href="#cb19-8" aria-hidden="true"></a><span class="op">}</span></span></code></pre></div> +<div class="sourceCode" id="cb19"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb19-1"><a href="#cb19-1" aria-hidden="true" tabindex="-1"></a><span class="co">// src/lib.rs</span></span> +<span id="cb19-2"><a href="#cb19-2" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb19-3"><a href="#cb19-3" aria-hidden="true" tabindex="-1"></a><span class="kw">fn</span> extract_arg_pat(a<span class="op">:</span> FnArg) <span class="op">-&gt;</span> <span class="dt">Box</span><span class="op">&lt;</span>Pat<span class="op">&gt;</span> <span class="op">{</span></span> +<span id="cb19-4"><a href="#cb19-4" aria-hidden="true" tabindex="-1"></a> <span class="kw">match</span> a <span class="op">{</span></span> +<span id="cb19-5"><a href="#cb19-5" aria-hidden="true" tabindex="-1"></a> <span class="pp">FnArg::</span>Typed(p) <span class="op">=&gt;</span> p<span class="op">.</span>pat<span class="op">,</span></span> +<span id="cb19-6"><a href="#cb19-6" aria-hidden="true" tabindex="-1"></a> _ <span class="op">=&gt;</span> <span class="pp">panic!</span>(<span class="st">&quot;Not supported on types with `self`!&quot;</span>)<span class="op">,</span></span> +<span id="cb19-7"><a href="#cb19-7" aria-hidden="true" tabindex="-1"></a> <span class="op">}</span></span> +<span id="cb19-8"><a href="#cb19-8" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code></pre></div> <p><code>FnArg</code> is an enum type as you might have guessed. The <code>Typed</code> variant encompasses args that are written as <code>name: type</code> and the other variant, <code>Reciever</code> refers to <code>self</code> types. Ignore those for now, keep it simple.</p> <p>Every <code>FnArg::Typed</code> value contains a <code>pat</code>, which is in essence, the name of the argument. The type of the arg is accessible via <code>p.ty</code> (we will be using this later).</p> <p>With that done, we should be able to write the codegen for the function body:</p> -<div class="sourceCode" id="cb20"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb20-1"><a href="#cb20-1" aria-hidden="true"></a><span class="co">// src/lib.rs</span></span> -<span id="cb20-2"><a href="#cb20-2" aria-hidden="true"></a></span> -<span id="cb20-3"><a href="#cb20-3" aria-hidden="true"></a><span class="kw">fn</span> generate_body(fn_args<span class="op">:</span> <span class="op">&amp;</span>[<span class="dt">Box</span><span class="op">&lt;</span>Pat<span class="op">&gt;</span>]<span class="op">,</span> body<span class="op">:</span> <span class="dt">Box</span><span class="op">&lt;</span>Block<span class="op">&gt;</span>) <span class="op">-&gt;</span> <span class="pp">proc_macro2::</span>TokenStream <span class="op">{</span></span> -<span id="cb20-4"><a href="#cb20-4" aria-hidden="true"></a> <span class="pp">quote!</span> <span class="op">{</span></span> -<span id="cb20-5"><a href="#cb20-5" aria-hidden="true"></a> <span class="kw">return</span> #( <span class="kw">move</span> <span class="op">|</span>#fn_args<span class="op">|</span> )<span class="op">*</span> #body</span> -<span id="cb20-6"><a href="#cb20-6" aria-hidden="true"></a> <span class="op">}</span></span> -<span id="cb20-7"><a href="#cb20-7" aria-hidden="true"></a><span class="op">}</span></span></code></pre></div> +<div class="sourceCode" id="cb20"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb20-1"><a href="#cb20-1" aria-hidden="true" tabindex="-1"></a><span class="co">// src/lib.rs</span></span> +<span id="cb20-2"><a href="#cb20-2" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb20-3"><a href="#cb20-3" aria-hidden="true" tabindex="-1"></a><span class="kw">fn</span> generate_body(fn_args<span class="op">:</span> <span class="op">&amp;</span>[<span class="dt">Box</span><span class="op">&lt;</span>Pat<span class="op">&gt;</span>]<span class="op">,</span> body<span class="op">:</span> <span class="dt">Box</span><span class="op">&lt;</span>Block<span class="op">&gt;</span>) <span class="op">-&gt;</span> <span class="pp">proc_macro2::</span>TokenStream <span class="op">{</span></span> +<span id="cb20-4"><a href="#cb20-4" aria-hidden="true" tabindex="-1"></a> <span class="pp">quote!</span> <span class="op">{</span></span> +<span id="cb20-5"><a href="#cb20-5" aria-hidden="true" tabindex="-1"></a> <span class="kw">return</span> #( <span class="kw">move</span> <span class="op">|</span>#fn_args<span class="op">|</span> )<span class="op">*</span> #body</span> +<span id="cb20-6"><a href="#cb20-6" aria-hidden="true" tabindex="-1"></a> <span class="op">}</span></span> +<span id="cb20-7"><a href="#cb20-7" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code></pre></div> <p>That is some scary looking syntax! Allow me to explain. The <code>quote!{ ... }</code> returns a <code>proc_macro2::TokenStream</code>, if we wrote <code>quote!{ let x = 1 + 2; }</code>, it wouldn’t create a new variable <code>x</code> with value 3, it would literally produce a stream of tokens with that expression.</p> <p>The <code>#</code> enables variable interpolation. <code>#body</code> will look for <code>body</code> in the current scope, take its value, and insert it in the returned <code>TokenStream</code>. Kinda like quasi quoting in LISPs, you have written one.</p> <p>What about <code>#( move |#fn_args| )*</code>? That is repetition. <code>quote</code> iterates through <code>fn_args</code>, and drops a <code>move</code> behind each one, it then places pipes (<code>|</code>), around it.</p> <p>Let us test our first bit of codegen! Modify <code>generate_curry</code> like so:</p> -<div class="sourceCode" id="cb21"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb21-1"><a href="#cb21-1" aria-hidden="true"></a><span class="co">// src/lib.rs</span></span> -<span id="cb21-2"><a href="#cb21-2" aria-hidden="true"></a></span> -<span id="cb21-3"><a href="#cb21-3" aria-hidden="true"></a> <span class="kw">fn</span> generate_curry(parsed<span class="op">:</span> ItemFn) <span class="op">-&gt;</span> TokenStream <span class="op">{</span></span> -<span id="cb21-4"><a href="#cb21-4" aria-hidden="true"></a> <span class="kw">let</span> fn_body <span class="op">=</span> parsed<span class="op">.</span>block<span class="op">;</span></span> -<span id="cb21-5"><a href="#cb21-5" aria-hidden="true"></a> <span class="kw">let</span> sig <span class="op">=</span> parsed<span class="op">.</span>sig<span class="op">;</span></span> -<span id="cb21-6"><a href="#cb21-6" aria-hidden="true"></a> <span class="kw">let</span> vis <span class="op">=</span> parsed<span class="op">.</span>vis<span class="op">;</span></span> -<span id="cb21-7"><a href="#cb21-7" aria-hidden="true"></a> <span class="kw">let</span> fn_name <span class="op">=</span> sig<span class="op">.</span>ident<span class="op">;</span></span> -<span id="cb21-8"><a href="#cb21-8" aria-hidden="true"></a> <span class="kw">let</span> fn_args <span class="op">=</span> sig<span class="op">.</span>inputs<span class="op">;</span></span> -<span id="cb21-9"><a href="#cb21-9" aria-hidden="true"></a> <span class="kw">let</span> fn_return_type <span class="op">=</span> sig<span class="op">.</span>output<span class="op">;</span></span> -<span id="cb21-10"><a href="#cb21-10" aria-hidden="true"></a></span> -<span id="cb21-11"><a href="#cb21-11" aria-hidden="true"></a><span class="op">+</span> <span class="kw">let</span> arg_idents <span class="op">=</span> extract_arg_idents(fn_args<span class="op">.</span>clone())<span class="op">;</span></span> -<span id="cb21-12"><a href="#cb21-12" aria-hidden="true"></a><span class="op">+</span> <span class="kw">let</span> first_ident <span class="op">=</span> <span class="op">&amp;</span>arg_idents<span class="op">.</span>first()<span class="op">.</span>unwrap()<span class="op">;</span></span> -<span id="cb21-13"><a href="#cb21-13" aria-hidden="true"></a></span> -<span id="cb21-14"><a href="#cb21-14" aria-hidden="true"></a><span class="op">+</span> <span class="co">// remember, our curried body starts with the second argument!</span></span> -<span id="cb21-15"><a href="#cb21-15" aria-hidden="true"></a><span class="op">+</span> <span class="kw">let</span> curried_body <span class="op">=</span> generate_body(<span class="op">&amp;</span>arg_idents[<span class="dv">1</span><span class="op">..</span>]<span class="op">,</span> fn_body<span class="op">.</span>clone())<span class="op">;</span></span> -<span id="cb21-16"><a href="#cb21-16" aria-hidden="true"></a><span class="op">+</span> <span class="pp">println!</span>(<span class="st">&quot;{}&quot;</span><span class="op">,</span> curried_body)<span class="op">;</span></span> -<span id="cb21-17"><a href="#cb21-17" aria-hidden="true"></a></span> -<span id="cb21-18"><a href="#cb21-18" aria-hidden="true"></a> <span class="kw">return</span> <span class="pp">TokenStream::</span>new()<span class="op">;</span></span> -<span id="cb21-19"><a href="#cb21-19" aria-hidden="true"></a> <span class="op">}</span></span></code></pre></div> +<div class="sourceCode" id="cb21"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb21-1"><a href="#cb21-1" aria-hidden="true" tabindex="-1"></a><span class="co">// src/lib.rs</span></span> +<span id="cb21-2"><a href="#cb21-2" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb21-3"><a href="#cb21-3" aria-hidden="true" tabindex="-1"></a> <span class="kw">fn</span> generate_curry(parsed<span class="op">:</span> ItemFn) <span class="op">-&gt;</span> TokenStream <span class="op">{</span></span> +<span id="cb21-4"><a href="#cb21-4" aria-hidden="true" tabindex="-1"></a> <span class="kw">let</span> fn_body <span class="op">=</span> parsed<span class="op">.</span>block<span class="op">;</span></span> +<span id="cb21-5"><a href="#cb21-5" aria-hidden="true" tabindex="-1"></a> <span class="kw">let</span> sig <span class="op">=</span> parsed<span class="op">.</span>sig<span class="op">;</span></span> +<span id="cb21-6"><a href="#cb21-6" aria-hidden="true" tabindex="-1"></a> <span class="kw">let</span> vis <span class="op">=</span> parsed<span class="op">.</span>vis<span class="op">;</span></span> +<span id="cb21-7"><a href="#cb21-7" aria-hidden="true" tabindex="-1"></a> <span class="kw">let</span> fn_name <span class="op">=</span> sig<span class="op">.</span>ident<span class="op">;</span></span> +<span id="cb21-8"><a href="#cb21-8" aria-hidden="true" tabindex="-1"></a> <span class="kw">let</span> fn_args <span class="op">=</span> sig<span class="op">.</span>inputs<span class="op">;</span></span> +<span id="cb21-9"><a href="#cb21-9" aria-hidden="true" tabindex="-1"></a> <span class="kw">let</span> fn_return_type <span class="op">=</span> sig<span class="op">.</span>output<span class="op">;</span></span> +<span id="cb21-10"><a href="#cb21-10" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb21-11"><a href="#cb21-11" aria-hidden="true" tabindex="-1"></a><span class="op">+</span> <span class="kw">let</span> arg_idents <span class="op">=</span> extract_arg_idents(fn_args<span class="op">.</span>clone())<span class="op">;</span></span> +<span id="cb21-12"><a href="#cb21-12" aria-hidden="true" tabindex="-1"></a><span class="op">+</span> <span class="kw">let</span> first_ident <span class="op">=</span> <span class="op">&amp;</span>arg_idents<span class="op">.</span>first()<span class="op">.</span>unwrap()<span class="op">;</span></span> +<span id="cb21-13"><a href="#cb21-13" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb21-14"><a href="#cb21-14" aria-hidden="true" tabindex="-1"></a><span class="op">+</span> <span class="co">// remember, our curried body starts with the second argument!</span></span> +<span id="cb21-15"><a href="#cb21-15" aria-hidden="true" tabindex="-1"></a><span class="op">+</span> <span class="kw">let</span> curried_body <span class="op">=</span> generate_body(<span class="op">&amp;</span>arg_idents[<span class="dv">1</span><span class="op">..</span>]<span class="op">,</span> fn_body<span class="op">.</span>clone())<span class="op">;</span></span> +<span id="cb21-16"><a href="#cb21-16" aria-hidden="true" tabindex="-1"></a><span class="op">+</span> <span class="pp">println!</span>(<span class="st">&quot;{}&quot;</span><span class="op">,</span> curried_body)<span class="op">;</span></span> +<span id="cb21-17"><a href="#cb21-17" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb21-18"><a href="#cb21-18" aria-hidden="true" tabindex="-1"></a> <span class="kw">return</span> <span class="pp">TokenStream::</span>new()<span class="op">;</span></span> +<span id="cb21-19"><a href="#cb21-19" aria-hidden="true" tabindex="-1"></a> <span class="op">}</span></span></code></pre></div> <p>Add a little test to <code>tests/</code>:</p> -<div class="sourceCode" id="cb22"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb22-1"><a href="#cb22-1" aria-hidden="true"></a><span class="co">// tests/smoke.rs</span></span> -<span id="cb22-2"><a href="#cb22-2" aria-hidden="true"></a></span> -<span id="cb22-3"><a href="#cb22-3" aria-hidden="true"></a><span class="at">#[</span><span class="pp">currying::</span>curry<span class="at">]</span></span> -<span id="cb22-4"><a href="#cb22-4" aria-hidden="true"></a><span class="kw">fn</span> add(x<span class="op">:</span> <span class="dt">u32</span><span class="op">,</span> y<span class="op">:</span> <span class="dt">u32</span><span class="op">,</span> z<span class="op">:</span> <span class="dt">u32</span>) <span class="op">-&gt;</span> <span class="dt">u32</span> <span class="op">{</span></span> -<span id="cb22-5"><a href="#cb22-5" aria-hidden="true"></a> x <span class="op">+</span> y <span class="op">+</span> z</span> -<span id="cb22-6"><a href="#cb22-6" aria-hidden="true"></a><span class="op">}</span></span> -<span id="cb22-7"><a href="#cb22-7" aria-hidden="true"></a></span> -<span id="cb22-8"><a href="#cb22-8" aria-hidden="true"></a><span class="at">#[</span>test<span class="at">]</span></span> -<span id="cb22-9"><a href="#cb22-9" aria-hidden="true"></a><span class="kw">fn</span> works() <span class="op">{</span></span> -<span id="cb22-10"><a href="#cb22-10" aria-hidden="true"></a> <span class="pp">assert!</span>(<span class="cn">true</span>)<span class="op">;</span></span> -<span id="cb22-11"><a href="#cb22-11" aria-hidden="true"></a><span class="op">}</span></span></code></pre></div> +<div class="sourceCode" id="cb22"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb22-1"><a href="#cb22-1" aria-hidden="true" tabindex="-1"></a><span class="co">// tests/smoke.rs</span></span> +<span id="cb22-2"><a href="#cb22-2" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb22-3"><a href="#cb22-3" aria-hidden="true" tabindex="-1"></a><span class="at">#[</span><span class="pp">currying::</span>curry<span class="at">]</span></span> +<span id="cb22-4"><a href="#cb22-4" aria-hidden="true" tabindex="-1"></a><span class="kw">fn</span> add(x<span class="op">:</span> <span class="dt">u32</span><span class="op">,</span> y<span class="op">:</span> <span class="dt">u32</span><span class="op">,</span> z<span class="op">:</span> <span class="dt">u32</span>) <span class="op">-&gt;</span> <span class="dt">u32</span> <span class="op">{</span></span> +<span id="cb22-5"><a href="#cb22-5" aria-hidden="true" tabindex="-1"></a> x <span class="op">+</span> y <span class="op">+</span> z</span> +<span id="cb22-6"><a href="#cb22-6" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span> +<span id="cb22-7"><a href="#cb22-7" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb22-8"><a href="#cb22-8" aria-hidden="true" tabindex="-1"></a><span class="at">#[</span>test<span class="at">]</span></span> +<span id="cb22-9"><a href="#cb22-9" aria-hidden="true" tabindex="-1"></a><span class="kw">fn</span> works() <span class="op">{</span></span> +<span id="cb22-10"><a href="#cb22-10" aria-hidden="true" tabindex="-1"></a> <span class="pp">assert!</span>(<span class="cn">true</span>)<span class="op">;</span></span> +<span id="cb22-11"><a href="#cb22-11" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code></pre></div> <p>You should find something like this in the output of <code>cargo test</code>:</p> <pre><code>return move | y | move | z | { x + y + z }</code></pre> <p>Glorious <code>println!</code> debugging!</p> <h4 id="function-signature">Function signature</h4> <p>This section gets into the more complicated bits of the macro, generating type aliases and the function signature. By the end of this section, we should have a full working auto-currying macro!</p> <p>Recall what our generated type aliases should look like, for our <code>add</code> function:</p> -<div class="sourceCode" id="cb24"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb24-1"><a href="#cb24-1" aria-hidden="true"></a><span class="kw">type</span> T0 <span class="op">=</span> <span class="dt">u32</span><span class="op">;</span></span> -<span id="cb24-2"><a href="#cb24-2" aria-hidden="true"></a><span class="kw">type</span> T1 <span class="op">=</span> <span class="kw">impl</span> <span class="bu">Fn</span>(<span class="dt">u32</span>) <span class="op">-&gt;</span> T0<span class="op">;</span></span> -<span id="cb24-3"><a href="#cb24-3" aria-hidden="true"></a><span class="kw">type</span> T2 <span class="op">=</span> <span class="kw">impl</span> <span class="bu">Fn</span>(<span class="dt">u32</span>) <span class="op">-&gt;</span> T1<span class="op">;</span></span></code></pre></div> +<div class="sourceCode" id="cb24"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb24-1"><a href="#cb24-1" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> T0 <span class="op">=</span> <span class="dt">u32</span><span class="op">;</span></span> +<span id="cb24-2"><a href="#cb24-2" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> T1 <span class="op">=</span> <span class="kw">impl</span> <span class="bu">Fn</span>(<span class="dt">u32</span>) <span class="op">-&gt;</span> T0<span class="op">;</span></span> +<span id="cb24-3"><a href="#cb24-3" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> T2 <span class="op">=</span> <span class="kw">impl</span> <span class="bu">Fn</span>(<span class="dt">u32</span>) <span class="op">-&gt;</span> T1<span class="op">;</span></span></code></pre></div> <p>In general:</p> -<div class="sourceCode" id="cb25"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb25-1"><a href="#cb25-1" aria-hidden="true"></a><span class="kw">type</span> T0 <span class="op">=</span> <span class="op">&lt;</span><span class="kw">return</span> <span class="kw">type</span>&gt;<span class="op">;</span></span> -<span id="cb25-2"><a href="#cb25-2" aria-hidden="true"></a><span class="kw">type</span> T1 <span class="op">=</span> <span class="kw">impl</span> <span class="bu">Fn</span>(<span class="op">&lt;</span><span class="kw">type</span> of arg N&gt;) -&gt; T0<span class="op">;</span></span> -<span id="cb25-3"><a href="#cb25-3" aria-hidden="true"></a><span class="kw">type</span> T2 <span class="op">=</span> <span class="kw">impl</span> <span class="bu">Fn</span>(<span class="op">&lt;</span><span class="kw">type</span> of arg N - 1&gt;) -&gt; T1<span class="op">;</span></span> -<span id="cb25-4"><a href="#cb25-4" aria-hidden="true"></a><span class="op">.</span></span> -<span id="cb25-5"><a href="#cb25-5" aria-hidden="true"></a><span class="op">.</span></span> -<span id="cb25-6"><a href="#cb25-6" aria-hidden="true"></a><span class="op">.</span></span> -<span id="cb25-7"><a href="#cb25-7" aria-hidden="true"></a><span class="kw">type</span> T(N-1) <span class="op">=</span> <span class="kw">impl</span> <span class="bu">Fn</span>(<span class="op">&lt;</span><span class="kw">type</span> of arg 2&gt;) -&gt; T(N-2)<span class="op">;</span></span></code></pre></div> +<div class="sourceCode" id="cb25"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb25-1"><a href="#cb25-1" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> T0 <span class="op">=</span> <span class="op">&lt;</span><span class="kw">return</span> <span class="kw">type</span>&gt;<span class="op">;</span></span> +<span id="cb25-2"><a href="#cb25-2" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> T1 <span class="op">=</span> <span class="kw">impl</span> <span class="bu">Fn</span>(<span class="op">&lt;</span><span class="kw">type</span> of arg N&gt;) -&gt; T0<span class="op">;</span></span> +<span id="cb25-3"><a href="#cb25-3" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> T2 <span class="op">=</span> <span class="kw">impl</span> <span class="bu">Fn</span>(<span class="op">&lt;</span><span class="kw">type</span> of arg N - 1&gt;) -&gt; T1<span class="op">;</span></span> +<span id="cb25-4"><a href="#cb25-4" aria-hidden="true" tabindex="-1"></a><span class="op">.</span></span> +<span id="cb25-5"><a href="#cb25-5" aria-hidden="true" tabindex="-1"></a><span class="op">.</span></span> +<span id="cb25-6"><a href="#cb25-6" aria-hidden="true" tabindex="-1"></a><span class="op">.</span></span> +<span id="cb25-7"><a href="#cb25-7" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> T(N-1) <span class="op">=</span> <span class="kw">impl</span> <span class="bu">Fn</span>(<span class="op">&lt;</span><span class="kw">type</span> of arg 2&gt;) -&gt; T(N-2)<span class="op">;</span></span></code></pre></div> <p>To codegen that, we need the types of:</p> <ul> <li>all our inputs (arguments)</li> <li>the output (the return type)</li> </ul> <p>To fetch the types of all our inputs, we can simply reuse the bits we wrote to fetch the names of all our inputs! (doc: <a href="https://docs.rs/syn/1.0.18/syn/enum.Type.html">Type</a>)</p> -<div class="sourceCode" id="cb26"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb26-1"><a href="#cb26-1" aria-hidden="true"></a><span class="co">// src/lib.rs</span></span> -<span id="cb26-2"><a href="#cb26-2" aria-hidden="true"></a></span> -<span id="cb26-3"><a href="#cb26-3" aria-hidden="true"></a><span class="kw">use</span> <span class="pp">syn::</span><span class="op">{</span>parse_macro_input<span class="op">,</span> Block<span class="op">,</span> FnArg<span class="op">,</span> ItemFn<span class="op">,</span> Pat<span class="op">,</span> ReturnType<span class="op">,</span> Type<span class="op">};</span></span> -<span id="cb26-4"><a href="#cb26-4" aria-hidden="true"></a></span> -<span id="cb26-5"><a href="#cb26-5" aria-hidden="true"></a><span class="kw">fn</span> extract_type(a<span class="op">:</span> FnArg) <span class="op">-&gt;</span> <span class="dt">Box</span><span class="op">&lt;</span>Type<span class="op">&gt;</span> <span class="op">{</span></span> -<span id="cb26-6"><a href="#cb26-6" aria-hidden="true"></a> <span class="kw">match</span> a <span class="op">{</span></span> -<span id="cb26-7"><a href="#cb26-7" aria-hidden="true"></a> <span class="pp">FnArg::</span>Typed(p) <span class="op">=&gt;</span> p<span class="op">.</span>ty<span class="op">,</span> <span class="co">// notice `ty` instead of `pat`</span></span> -<span id="cb26-8"><a href="#cb26-8" aria-hidden="true"></a> _ <span class="op">=&gt;</span> <span class="pp">panic!</span>(<span class="st">&quot;Not supported on types with `self`!&quot;</span>)<span class="op">,</span></span> -<span id="cb26-9"><a href="#cb26-9" aria-hidden="true"></a> <span class="op">}</span></span> -<span id="cb26-10"><a href="#cb26-10" aria-hidden="true"></a><span class="op">}</span></span> -<span id="cb26-11"><a href="#cb26-11" aria-hidden="true"></a></span> -<span id="cb26-12"><a href="#cb26-12" aria-hidden="true"></a><span class="kw">fn</span> extract_arg_types(fn_args<span class="op">:</span> Punctuated<span class="op">&lt;</span>FnArg<span class="op">,</span> <span class="pp">syn::token::</span>Comma<span class="op">&gt;</span>) <span class="op">-&gt;</span> <span class="dt">Vec</span><span class="op">&lt;</span><span class="dt">Box</span><span class="op">&lt;</span>Type<span class="op">&gt;&gt;</span> <span class="op">{</span></span> -<span id="cb26-13"><a href="#cb26-13" aria-hidden="true"></a> <span class="kw">return</span> fn_args<span class="op">.</span>into_iter()<span class="op">.</span>map(extract_type)<span class="op">.</span><span class="pp">collect::</span><span class="op">&lt;</span><span class="dt">Vec</span><span class="op">&lt;</span>_<span class="op">&gt;&gt;</span>()<span class="op">;</span></span> -<span id="cb26-14"><a href="#cb26-14" aria-hidden="true"></a></span> -<span id="cb26-15"><a href="#cb26-15" aria-hidden="true"></a><span class="op">}</span></span></code></pre></div> +<div class="sourceCode" id="cb26"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb26-1"><a href="#cb26-1" aria-hidden="true" tabindex="-1"></a><span class="co">// src/lib.rs</span></span> +<span id="cb26-2"><a href="#cb26-2" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb26-3"><a href="#cb26-3" aria-hidden="true" tabindex="-1"></a><span class="kw">use</span> <span class="pp">syn::</span><span class="op">{</span>parse_macro_input<span class="op">,</span> Block<span class="op">,</span> FnArg<span class="op">,</span> ItemFn<span class="op">,</span> Pat<span class="op">,</span> ReturnType<span class="op">,</span> Type<span class="op">};</span></span> +<span id="cb26-4"><a href="#cb26-4" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb26-5"><a href="#cb26-5" aria-hidden="true" tabindex="-1"></a><span class="kw">fn</span> extract_type(a<span class="op">:</span> FnArg) <span class="op">-&gt;</span> <span class="dt">Box</span><span class="op">&lt;</span>Type<span class="op">&gt;</span> <span class="op">{</span></span> +<span id="cb26-6"><a href="#cb26-6" aria-hidden="true" tabindex="-1"></a> <span class="kw">match</span> a <span class="op">{</span></span> +<span id="cb26-7"><a href="#cb26-7" aria-hidden="true" tabindex="-1"></a> <span class="pp">FnArg::</span>Typed(p) <span class="op">=&gt;</span> p<span class="op">.</span>ty<span class="op">,</span> <span class="co">// notice `ty` instead of `pat`</span></span> +<span id="cb26-8"><a href="#cb26-8" aria-hidden="true" tabindex="-1"></a> _ <span class="op">=&gt;</span> <span class="pp">panic!</span>(<span class="st">&quot;Not supported on types with `self`!&quot;</span>)<span class="op">,</span></span> +<span id="cb26-9"><a href="#cb26-9" aria-hidden="true" tabindex="-1"></a> <span class="op">}</span></span> +<span id="cb26-10"><a href="#cb26-10" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span> +<span id="cb26-11"><a href="#cb26-11" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb26-12"><a href="#cb26-12" aria-hidden="true" tabindex="-1"></a><span class="kw">fn</span> extract_arg_types(fn_args<span class="op">:</span> Punctuated<span class="op">&lt;</span>FnArg<span class="op">,</span> <span class="pp">syn::token::</span>Comma<span class="op">&gt;</span>) <span class="op">-&gt;</span> <span class="dt">Vec</span><span class="op">&lt;</span><span class="dt">Box</span><span class="op">&lt;</span>Type<span class="op">&gt;&gt;</span> <span class="op">{</span></span> +<span id="cb26-13"><a href="#cb26-13" aria-hidden="true" tabindex="-1"></a> <span class="kw">return</span> fn_args<span class="op">.</span>into_iter()<span class="op">.</span>map(extract_type)<span class="op">.</span><span class="pp">collect::</span><span class="op">&lt;</span><span class="dt">Vec</span><span class="op">&lt;</span>_<span class="op">&gt;&gt;</span>()<span class="op">;</span></span> +<span id="cb26-14"><a href="#cb26-14" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb26-15"><a href="#cb26-15" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code></pre></div> <p>A good reader would have looked at the docs for output member of the <code>syn::Signature</code> struct. It has the type <code>syn::ReturnType</code>. So there is no extraction to do here right? There are actually a couple of things we have to ensure here:</p> <ol type="1"> <li><p>We need to ensure that the function returns! A function that does not return is pointless in this case, and I will tell you why, in the <a href="#notes">Notes</a> section.</p></li> <li><p>A <code>ReturnType</code> encloses the arrow of the return as well, we need to get rid of that. Recall:</p> -<div class="sourceCode" id="cb27"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb27-1"><a href="#cb27-1" aria-hidden="true"></a><span class="kw">type</span> T0 <span class="op">=</span> <span class="dt">u32</span></span> -<span id="cb27-2"><a href="#cb27-2" aria-hidden="true"></a><span class="co">// and not</span></span> -<span id="cb27-3"><a href="#cb27-3" aria-hidden="true"></a><span class="kw">type</span> T0 <span class="op">=</span> <span class="op">-&gt;</span> <span class="dt">u32</span></span></code></pre></div></li> +<div class="sourceCode" id="cb27"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb27-1"><a href="#cb27-1" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> T0 <span class="op">=</span> <span class="dt">u32</span></span> +<span id="cb27-2"><a href="#cb27-2" aria-hidden="true" tabindex="-1"></a><span class="co">// and not</span></span> +<span id="cb27-3"><a href="#cb27-3" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> T0 <span class="op">=</span> <span class="op">-&gt;</span> <span class="dt">u32</span></span></code></pre></div></li> </ol> <p>Here is the snippet that handles extraction of the return type (doc: <a href="https://docs.rs/syn/1.0.19/syn/enum.ReturnType.html">syn::ReturnType</a>):</p> -<div class="sourceCode" id="cb28"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb28-1"><a href="#cb28-1" aria-hidden="true"></a><span class="co">// src/lib.rs</span></span> -<span id="cb28-2"><a href="#cb28-2" aria-hidden="true"></a></span> -<span id="cb28-3"><a href="#cb28-3" aria-hidden="true"></a><span class="kw">fn</span> extract_return_type(a<span class="op">:</span> ReturnType) <span class="op">-&gt;</span> <span class="dt">Box</span><span class="op">&lt;</span>Type<span class="op">&gt;</span> <span class="op">{</span></span> -<span id="cb28-4"><a href="#cb28-4" aria-hidden="true"></a> <span class="kw">match</span> a <span class="op">{</span></span> -<span id="cb28-5"><a href="#cb28-5" aria-hidden="true"></a> <span class="pp">ReturnType::</span>Type(_<span class="op">,</span> p) <span class="op">=&gt;</span> p<span class="op">,</span></span> -<span id="cb28-6"><a href="#cb28-6" aria-hidden="true"></a> _ <span class="op">=&gt;</span> <span class="pp">panic!</span>(<span class="st">&quot;Not supported on functions without return types!&quot;</span>)<span class="op">,</span></span> -<span id="cb28-7"><a href="#cb28-7" aria-hidden="true"></a> <span class="op">}</span></span> -<span id="cb28-8"><a href="#cb28-8" aria-hidden="true"></a><span class="op">}</span></span></code></pre></div> +<div class="sourceCode" id="cb28"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb28-1"><a href="#cb28-1" aria-hidden="true" tabindex="-1"></a><span class="co">// src/lib.rs</span></span> +<span id="cb28-2"><a href="#cb28-2" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb28-3"><a href="#cb28-3" aria-hidden="true" tabindex="-1"></a><span class="kw">fn</span> extract_return_type(a<span class="op">:</span> ReturnType) <span class="op">-&gt;</span> <span class="dt">Box</span><span class="op">&lt;</span>Type<span class="op">&gt;</span> <span class="op">{</span></span> +<span id="cb28-4"><a href="#cb28-4" aria-hidden="true" tabindex="-1"></a> <span class="kw">match</span> a <span class="op">{</span></span> +<span id="cb28-5"><a href="#cb28-5" aria-hidden="true" tabindex="-1"></a> <span class="pp">ReturnType::</span>Type(_<span class="op">,</span> p) <span class="op">=&gt;</span> p<span class="op">,</span></span> +<span id="cb28-6"><a href="#cb28-6" aria-hidden="true" tabindex="-1"></a> _ <span class="op">=&gt;</span> <span class="pp">panic!</span>(<span class="st">&quot;Not supported on functions without return types!&quot;</span>)<span class="op">,</span></span> +<span id="cb28-7"><a href="#cb28-7" aria-hidden="true" tabindex="-1"></a> <span class="op">}</span></span> +<span id="cb28-8"><a href="#cb28-8" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code></pre></div> <p>You might notice that we are making extensive use of the <code>panic!</code> macro. Well, that is because it is a good idea to quit on receiving an unsatisfactory <code>TokenStream</code>.</p> <p>With all our types ready, we can get on with generating type aliases:</p> -<div class="sourceCode" id="cb29"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb29-1"><a href="#cb29-1" aria-hidden="true"></a><span class="co">// src/lib.rs</span></span> -<span id="cb29-2"><a href="#cb29-2" aria-hidden="true"></a></span> -<span id="cb29-3"><a href="#cb29-3" aria-hidden="true"></a><span class="kw">use</span> <span class="pp">quote::</span><span class="op">{</span>quote<span class="op">,</span> format_ident<span class="op">};</span></span> -<span id="cb29-4"><a href="#cb29-4" aria-hidden="true"></a></span> -<span id="cb29-5"><a href="#cb29-5" aria-hidden="true"></a><span class="kw">fn</span> generate_type_aliases(</span> -<span id="cb29-6"><a href="#cb29-6" aria-hidden="true"></a> fn_arg_types<span class="op">:</span> <span class="op">&amp;</span>[<span class="dt">Box</span><span class="op">&lt;</span>Type<span class="op">&gt;</span>]<span class="op">,</span></span> -<span id="cb29-7"><a href="#cb29-7" aria-hidden="true"></a> fn_return_type<span class="op">:</span> <span class="dt">Box</span><span class="op">&lt;</span>Type<span class="op">&gt;,</span></span> -<span id="cb29-8"><a href="#cb29-8" aria-hidden="true"></a> fn_name<span class="op">:</span> <span class="op">&amp;</span><span class="pp">syn::</span>Ident<span class="op">,</span></span> -<span id="cb29-9"><a href="#cb29-9" aria-hidden="true"></a>) <span class="op">-&gt;</span> <span class="dt">Vec</span><span class="op">&lt;</span><span class="pp">proc_macro2::</span>TokenStream<span class="op">&gt;</span> <span class="op">{</span> <span class="co">// 1</span></span> -<span id="cb29-10"><a href="#cb29-10" aria-hidden="true"></a></span> -<span id="cb29-11"><a href="#cb29-11" aria-hidden="true"></a> <span class="kw">let</span> type_t0 <span class="op">=</span> <span class="pp">format_ident!</span>(<span class="st">&quot;_{}_T0&quot;</span><span class="op">,</span> fn_name)<span class="op">;</span> <span class="co">// 2</span></span> -<span id="cb29-12"><a href="#cb29-12" aria-hidden="true"></a> <span class="kw">let</span> <span class="kw">mut</span> type_aliases <span class="op">=</span> <span class="pp">vec!</span>[<span class="pp">quote!</span> <span class="op">{</span> <span class="kw">type</span> #type_t0 <span class="op">=</span> #fn_return_type <span class="op">}</span>]<span class="op">;</span></span> -<span id="cb29-13"><a href="#cb29-13" aria-hidden="true"></a></span> -<span id="cb29-14"><a href="#cb29-14" aria-hidden="true"></a> <span class="co">// 3</span></span> -<span id="cb29-15"><a href="#cb29-15" aria-hidden="true"></a> <span class="kw">for</span> (i<span class="op">,</span> t) <span class="kw">in</span> (<span class="dv">1</span><span class="op">..</span>)<span class="op">.</span>zip(fn_arg_types<span class="op">.</span>into_iter()<span class="op">.</span>rev()) <span class="op">{</span></span> -<span id="cb29-16"><a href="#cb29-16" aria-hidden="true"></a> <span class="kw">let</span> p <span class="op">=</span> <span class="pp">format_ident!</span>(<span class="st">&quot;_{}_{}&quot;</span><span class="op">,</span> fn_name<span class="op">,</span> <span class="pp">format!</span>(<span class="st">&quot;T{}&quot;</span><span class="op">,</span> i <span class="op">-</span> <span class="dv">1</span>))<span class="op">;</span></span> -<span id="cb29-17"><a href="#cb29-17" aria-hidden="true"></a> <span class="kw">let</span> n <span class="op">=</span> <span class="pp">format_ident!</span>(<span class="st">&quot;_{}_{}&quot;</span><span class="op">,</span> fn_name<span class="op">,</span> <span class="pp">format!</span>(<span class="st">&quot;T{}&quot;</span><span class="op">,</span> i))<span class="op">;</span></span> -<span id="cb29-18"><a href="#cb29-18" aria-hidden="true"></a></span> -<span id="cb29-19"><a href="#cb29-19" aria-hidden="true"></a> type_aliases<span class="op">.</span>push(<span class="pp">quote!</span> <span class="op">{</span></span> -<span id="cb29-20"><a href="#cb29-20" aria-hidden="true"></a> <span class="kw">type</span> #n <span class="op">=</span> <span class="kw">impl</span> <span class="bu">Fn</span>(#t) <span class="op">-&gt;</span> #p</span> -<span id="cb29-21"><a href="#cb29-21" aria-hidden="true"></a> <span class="op">}</span>)<span class="op">;</span></span> -<span id="cb29-22"><a href="#cb29-22" aria-hidden="true"></a> <span class="op">}</span></span> -<span id="cb29-23"><a href="#cb29-23" aria-hidden="true"></a></span> -<span id="cb29-24"><a href="#cb29-24" aria-hidden="true"></a> <span class="kw">return</span> type_aliases<span class="op">;</span></span> -<span id="cb29-25"><a href="#cb29-25" aria-hidden="true"></a><span class="op">}</span></span></code></pre></div> +<div class="sourceCode" id="cb29"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb29-1"><a href="#cb29-1" aria-hidden="true" tabindex="-1"></a><span class="co">// src/lib.rs</span></span> +<span id="cb29-2"><a href="#cb29-2" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb29-3"><a href="#cb29-3" aria-hidden="true" tabindex="-1"></a><span class="kw">use</span> <span class="pp">quote::</span><span class="op">{</span>quote<span class="op">,</span> format_ident<span class="op">};</span></span> +<span id="cb29-4"><a href="#cb29-4" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb29-5"><a href="#cb29-5" aria-hidden="true" tabindex="-1"></a><span class="kw">fn</span> generate_type_aliases(</span> +<span id="cb29-6"><a href="#cb29-6" aria-hidden="true" tabindex="-1"></a> fn_arg_types<span class="op">:</span> <span class="op">&amp;</span>[<span class="dt">Box</span><span class="op">&lt;</span>Type<span class="op">&gt;</span>]<span class="op">,</span></span> +<span id="cb29-7"><a href="#cb29-7" aria-hidden="true" tabindex="-1"></a> fn_return_type<span class="op">:</span> <span class="dt">Box</span><span class="op">&lt;</span>Type<span class="op">&gt;,</span></span> +<span id="cb29-8"><a href="#cb29-8" aria-hidden="true" tabindex="-1"></a> fn_name<span class="op">:</span> <span class="op">&amp;</span><span class="pp">syn::</span>Ident<span class="op">,</span></span> +<span id="cb29-9"><a href="#cb29-9" aria-hidden="true" tabindex="-1"></a>) <span class="op">-&gt;</span> <span class="dt">Vec</span><span class="op">&lt;</span><span class="pp">proc_macro2::</span>TokenStream<span class="op">&gt;</span> <span class="op">{</span> <span class="co">// 1</span></span> +<span id="cb29-10"><a href="#cb29-10" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb29-11"><a href="#cb29-11" aria-hidden="true" tabindex="-1"></a> <span class="kw">let</span> type_t0 <span class="op">=</span> <span class="pp">format_ident!</span>(<span class="st">&quot;_{}_T0&quot;</span><span class="op">,</span> fn_name)<span class="op">;</span> <span class="co">// 2</span></span> +<span id="cb29-12"><a href="#cb29-12" aria-hidden="true" tabindex="-1"></a> <span class="kw">let</span> <span class="kw">mut</span> type_aliases <span class="op">=</span> <span class="pp">vec!</span>[<span class="pp">quote!</span> <span class="op">{</span> <span class="kw">type</span> #type_t0 <span class="op">=</span> #fn_return_type <span class="op">}</span>]<span class="op">;</span></span> +<span id="cb29-13"><a href="#cb29-13" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb29-14"><a href="#cb29-14" aria-hidden="true" tabindex="-1"></a> <span class="co">// 3</span></span> +<span id="cb29-15"><a href="#cb29-15" aria-hidden="true" tabindex="-1"></a> <span class="kw">for</span> (i<span class="op">,</span> t) <span class="kw">in</span> (<span class="dv">1</span><span class="op">..</span>)<span class="op">.</span>zip(fn_arg_types<span class="op">.</span>into_iter()<span class="op">.</span>rev()) <span class="op">{</span></span> +<span id="cb29-16"><a href="#cb29-16" aria-hidden="true" tabindex="-1"></a> <span class="kw">let</span> p <span class="op">=</span> <span class="pp">format_ident!</span>(<span class="st">&quot;_{}_{}&quot;</span><span class="op">,</span> fn_name<span class="op">,</span> <span class="pp">format!</span>(<span class="st">&quot;T{}&quot;</span><span class="op">,</span> i <span class="op">-</span> <span class="dv">1</span>))<span class="op">;</span></span> +<span id="cb29-17"><a href="#cb29-17" aria-hidden="true" tabindex="-1"></a> <span class="kw">let</span> n <span class="op">=</span> <span class="pp">format_ident!</span>(<span class="st">&quot;_{}_{}&quot;</span><span class="op">,</span> fn_name<span class="op">,</span> <span class="pp">format!</span>(<span class="st">&quot;T{}&quot;</span><span class="op">,</span> i))<span class="op">;</span></span> +<span id="cb29-18"><a href="#cb29-18" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb29-19"><a href="#cb29-19" aria-hidden="true" tabindex="-1"></a> type_aliases<span class="op">.</span>push(<span class="pp">quote!</span> <span class="op">{</span></span> +<span id="cb29-20"><a href="#cb29-20" aria-hidden="true" tabindex="-1"></a> <span class="kw">type</span> #n <span class="op">=</span> <span class="kw">impl</span> <span class="bu">Fn</span>(#t) <span class="op">-&gt;</span> #p</span> +<span id="cb29-21"><a href="#cb29-21" aria-hidden="true" tabindex="-1"></a> <span class="op">}</span>)<span class="op">;</span></span> +<span id="cb29-22"><a href="#cb29-22" aria-hidden="true" tabindex="-1"></a> <span class="op">}</span></span> +<span id="cb29-23"><a href="#cb29-23" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb29-24"><a href="#cb29-24" aria-hidden="true" tabindex="-1"></a> <span class="kw">return</span> type_aliases<span class="op">;</span></span> +<span id="cb29-25"><a href="#cb29-25" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code></pre></div> <p><strong>1. The return value</strong><br /> We are returning a <code>Vec&lt;proc_macro2::TokenStream&gt;</code>, i. e., a list of <code>TokenStream</code>s, where each item is a type alias.</p> <p><strong>2. Format identifier?</strong><br /> I’ve got some explanation to do on this line. Clearly, we are trying to write the first type alias, and initialize our <code>TokenStream</code> vector with <code>T0</code>, because it is different from the others:</p> -<div class="sourceCode" id="cb30"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb30-1"><a href="#cb30-1" aria-hidden="true"></a><span class="kw">type</span> T0 <span class="op">=</span> something</span> -<span id="cb30-2"><a href="#cb30-2" aria-hidden="true"></a><span class="co">// the others are of the form</span></span> -<span id="cb30-3"><a href="#cb30-3" aria-hidden="true"></a><span class="kw">type</span> Tr <span class="op">=</span> <span class="kw">impl</span> <span class="bu">Fn</span>(something) <span class="op">-&gt;</span> something</span></code></pre></div> +<div class="sourceCode" id="cb30"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb30-1"><a href="#cb30-1" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> T0 <span class="op">=</span> something</span> +<span id="cb30-2"><a href="#cb30-2" aria-hidden="true" tabindex="-1"></a><span class="co">// the others are of the form</span></span> +<span id="cb30-3"><a href="#cb30-3" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> Tr <span class="op">=</span> <span class="kw">impl</span> <span class="bu">Fn</span>(something) <span class="op">-&gt;</span> something</span></code></pre></div> <p><code>format_ident!</code> is similar to <code>format!</code>. Instead of returning a formatted string, it returns a <code>syn::Ident</code>. Therefore, <code>type_t0</code> is actually an identifier for, in the case of our <code>add</code> function, <code>_add_T0</code>. Why is this formatting important? Namespacing.</p> <p>Picture this, we have two functions, <code>add</code> and <code>subtract</code>, that we wish to curry with our macro:</p> -<div class="sourceCode" id="cb31"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb31-1"><a href="#cb31-1" aria-hidden="true"></a><span class="at">#[</span>curry<span class="at">]</span></span> -<span id="cb31-2"><a href="#cb31-2" aria-hidden="true"></a><span class="kw">fn</span> add(<span class="op">...</span>) <span class="op">-&gt;</span> <span class="dt">u32</span> <span class="op">{</span> <span class="op">...</span> <span class="op">}</span></span> -<span id="cb31-3"><a href="#cb31-3" aria-hidden="true"></a></span> -<span id="cb31-4"><a href="#cb31-4" aria-hidden="true"></a><span class="at">#[</span>curry<span class="at">]</span></span> -<span id="cb31-5"><a href="#cb31-5" aria-hidden="true"></a><span class="kw">fn</span> sub(<span class="op">...</span>) <span class="op">-&gt;</span> <span class="dt">u32</span> <span class="op">{</span> <span class="op">...</span> <span class="op">}</span></span></code></pre></div> +<div class="sourceCode" id="cb31"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb31-1"><a href="#cb31-1" aria-hidden="true" tabindex="-1"></a><span class="at">#[</span>curry<span class="at">]</span></span> +<span id="cb31-2"><a href="#cb31-2" aria-hidden="true" tabindex="-1"></a><span class="kw">fn</span> add(<span class="op">...</span>) <span class="op">-&gt;</span> <span class="dt">u32</span> <span class="op">{</span> <span class="op">...</span> <span class="op">}</span></span> +<span id="cb31-3"><a href="#cb31-3" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb31-4"><a href="#cb31-4" aria-hidden="true" tabindex="-1"></a><span class="at">#[</span>curry<span class="at">]</span></span> +<span id="cb31-5"><a href="#cb31-5" aria-hidden="true" tabindex="-1"></a><span class="kw">fn</span> sub(<span class="op">...</span>) <span class="op">-&gt;</span> <span class="dt">u32</span> <span class="op">{</span> <span class="op">...</span> <span class="op">}</span></span></code></pre></div> <p>Here is the same but with macros expanded:</p> -<div class="sourceCode" id="cb32"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb32-1"><a href="#cb32-1" aria-hidden="true"></a><span class="kw">type</span> T0 <span class="op">=</span> <span class="dt">u32</span><span class="op">;</span></span> -<span id="cb32-2"><a href="#cb32-2" aria-hidden="true"></a><span class="kw">type</span> T1 <span class="op">=</span> <span class="kw">impl</span> <span class="bu">Fn</span>(<span class="dt">u32</span>) <span class="op">-&gt;</span> T0<span class="op">;</span></span> -<span id="cb32-3"><a href="#cb32-3" aria-hidden="true"></a><span class="kw">fn</span> add( <span class="op">...</span> ) <span class="op">-&gt;</span> T1 <span class="op">{</span> <span class="op">...</span> <span class="op">}</span></span> -<span id="cb32-4"><a href="#cb32-4" aria-hidden="true"></a></span> -<span id="cb32-5"><a href="#cb32-5" aria-hidden="true"></a><span class="kw">type</span> T0 <span class="op">=</span> <span class="dt">u32</span><span class="op">;</span></span> -<span id="cb32-6"><a href="#cb32-6" aria-hidden="true"></a><span class="kw">type</span> T1 <span class="op">=</span> <span class="kw">impl</span> <span class="bu">Fn</span>(<span class="dt">u32</span>) <span class="op">-&gt;</span> T0<span class="op">;</span></span> -<span id="cb32-7"><a href="#cb32-7" aria-hidden="true"></a><span class="kw">fn</span> sub( <span class="op">...</span> ) <span class="op">-&gt;</span> T1 <span class="op">{</span> <span class="op">...</span> <span class="op">}</span></span></code></pre></div> +<div class="sourceCode" id="cb32"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb32-1"><a href="#cb32-1" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> T0 <span class="op">=</span> <span class="dt">u32</span><span class="op">;</span></span> +<span id="cb32-2"><a href="#cb32-2" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> T1 <span class="op">=</span> <span class="kw">impl</span> <span class="bu">Fn</span>(<span class="dt">u32</span>) <span class="op">-&gt;</span> T0<span class="op">;</span></span> +<span id="cb32-3"><a href="#cb32-3" aria-hidden="true" tabindex="-1"></a><span class="kw">fn</span> add( <span class="op">...</span> ) <span class="op">-&gt;</span> T1 <span class="op">{</span> <span class="op">...</span> <span class="op">}</span></span> +<span id="cb32-4"><a href="#cb32-4" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb32-5"><a href="#cb32-5" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> T0 <span class="op">=</span> <span class="dt">u32</span><span class="op">;</span></span> +<span id="cb32-6"><a href="#cb32-6" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> T1 <span class="op">=</span> <span class="kw">impl</span> <span class="bu">Fn</span>(<span class="dt">u32</span>) <span class="op">-&gt;</span> T0<span class="op">;</span></span> +<span id="cb32-7"><a href="#cb32-7" aria-hidden="true" tabindex="-1"></a><span class="kw">fn</span> sub( <span class="op">...</span> ) <span class="op">-&gt;</span> T1 <span class="op">{</span> <span class="op">...</span> <span class="op">}</span></span></code></pre></div> <p>We end up with two definitions of <code>T0</code>! Now, if we do the little <code>format_ident!</code> dance we did up there:</p> -<div class="sourceCode" id="cb33"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb33-1"><a href="#cb33-1" aria-hidden="true"></a><span class="kw">type</span> _add_T0 <span class="op">=</span> <span class="dt">u32</span><span class="op">;</span></span> -<span id="cb33-2"><a href="#cb33-2" aria-hidden="true"></a><span class="kw">type</span> _add_T1 <span class="op">=</span> <span class="kw">impl</span> <span class="bu">Fn</span>(<span class="dt">u32</span>) <span class="op">-&gt;</span> _add_T0<span class="op">;</span></span> -<span id="cb33-3"><a href="#cb33-3" aria-hidden="true"></a><span class="kw">fn</span> add( <span class="op">...</span> ) <span class="op">-&gt;</span> _add_T1 <span class="op">{</span> <span class="op">...</span> <span class="op">}</span></span> -<span id="cb33-4"><a href="#cb33-4" aria-hidden="true"></a></span> -<span id="cb33-5"><a href="#cb33-5" aria-hidden="true"></a><span class="kw">type</span> _sub_T0 <span class="op">=</span> <span class="dt">u32</span><span class="op">;</span></span> -<span id="cb33-6"><a href="#cb33-6" aria-hidden="true"></a><span class="kw">type</span> _sub_T1 <span class="op">=</span> <span class="kw">impl</span> <span class="bu">Fn</span>(<span class="dt">u32</span>) <span class="op">-&gt;</span> _sub_T0<span class="op">;</span></span> -<span id="cb33-7"><a href="#cb33-7" aria-hidden="true"></a><span class="kw">fn</span> sub( <span class="op">...</span> ) <span class="op">-&gt;</span> _sub_T1 <span class="op">{</span> <span class="op">...</span> <span class="op">}</span></span></code></pre></div> +<div class="sourceCode" id="cb33"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb33-1"><a href="#cb33-1" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> _add_T0 <span class="op">=</span> <span class="dt">u32</span><span class="op">;</span></span> +<span id="cb33-2"><a href="#cb33-2" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> _add_T1 <span class="op">=</span> <span class="kw">impl</span> <span class="bu">Fn</span>(<span class="dt">u32</span>) <span class="op">-&gt;</span> _add_T0<span class="op">;</span></span> +<span id="cb33-3"><a href="#cb33-3" aria-hidden="true" tabindex="-1"></a><span class="kw">fn</span> add( <span class="op">...</span> ) <span class="op">-&gt;</span> _add_T1 <span class="op">{</span> <span class="op">...</span> <span class="op">}</span></span> +<span id="cb33-4"><a href="#cb33-4" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb33-5"><a href="#cb33-5" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> _sub_T0 <span class="op">=</span> <span class="dt">u32</span><span class="op">;</span></span> +<span id="cb33-6"><a href="#cb33-6" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> _sub_T1 <span class="op">=</span> <span class="kw">impl</span> <span class="bu">Fn</span>(<span class="dt">u32</span>) <span class="op">-&gt;</span> _sub_T0<span class="op">;</span></span> +<span id="cb33-7"><a href="#cb33-7" aria-hidden="true" tabindex="-1"></a><span class="kw">fn</span> sub( <span class="op">...</span> ) <span class="op">-&gt;</span> _sub_T1 <span class="op">{</span> <span class="op">...</span> <span class="op">}</span></span></code></pre></div> <p>Voilà! The type aliases don’t tread on each other. Remember to import <code>format_ident</code> from the <code>quote</code> crate.</p> <p><strong>3. The TokenStream Vector</strong></p> <p>We iterate over our types in reverse order (<code>T0</code> is the last return, <code>T1</code> is the second last, so on), assign a number to each iteration with <code>zip</code>, generate type names with <code>format_ident</code>, push a <code>TokenStream</code> with the help of <code>quote</code> and variable interpolation.</p> <p>If you are wondering why we used <code>(1..).zip()</code> instead of <code>.enumerate()</code>, it’s because we wanted to start counting from 1 instead of 0 (we are already done with <code>T0</code>!).</p> <h4 id="getting-it-together">Getting it together</h4> <p>I promised we’d have a fully working macro by the end of last section. I lied, we have to tie everything together in our <code>generate_curry</code> function:</p> -<div class="sourceCode" id="cb34"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb34-1"><a href="#cb34-1" aria-hidden="true"></a><span class="co">// src/lib.rs</span></span> -<span id="cb34-2"><a href="#cb34-2" aria-hidden="true"></a></span> -<span id="cb34-3"><a href="#cb34-3" aria-hidden="true"></a> <span class="kw">fn</span> generate_curry(parsed<span class="op">:</span> ItemFn) <span class="op">-&gt;</span> <span class="pp">proc_macro2::</span>TokenStream <span class="op">{</span></span> -<span id="cb34-4"><a href="#cb34-4" aria-hidden="true"></a> <span class="kw">let</span> fn_body <span class="op">=</span> parsed<span class="op">.</span>block<span class="op">;</span></span> -<span id="cb34-5"><a href="#cb34-5" aria-hidden="true"></a> <span class="kw">let</span> sig <span class="op">=</span> parsed<span class="op">.</span>sig<span class="op">;</span></span> -<span id="cb34-6"><a href="#cb34-6" aria-hidden="true"></a> <span class="kw">let</span> vis <span class="op">=</span> parsed<span class="op">.</span>vis<span class="op">;</span></span> -<span id="cb34-7"><a href="#cb34-7" aria-hidden="true"></a> <span class="kw">let</span> fn_name <span class="op">=</span> sig<span class="op">.</span>ident<span class="op">;</span></span> -<span id="cb34-8"><a href="#cb34-8" aria-hidden="true"></a> <span class="kw">let</span> fn_args <span class="op">=</span> sig<span class="op">.</span>inputs<span class="op">;</span></span> -<span id="cb34-9"><a href="#cb34-9" aria-hidden="true"></a> <span class="kw">let</span> fn_return_type <span class="op">=</span> sig<span class="op">.</span>output<span class="op">;</span></span> -<span id="cb34-10"><a href="#cb34-10" aria-hidden="true"></a></span> -<span id="cb34-11"><a href="#cb34-11" aria-hidden="true"></a> <span class="kw">let</span> arg_idents <span class="op">=</span> extract_arg_idents(fn_args<span class="op">.</span>clone())<span class="op">;</span></span> -<span id="cb34-12"><a href="#cb34-12" aria-hidden="true"></a> <span class="kw">let</span> first_ident <span class="op">=</span> <span class="op">&amp;</span>arg_idents<span class="op">.</span>first()<span class="op">.</span>unwrap()<span class="op">;</span></span> -<span id="cb34-13"><a href="#cb34-13" aria-hidden="true"></a> <span class="kw">let</span> curried_body <span class="op">=</span> generate_body(<span class="op">&amp;</span>arg_idents[<span class="dv">1</span><span class="op">..</span>]<span class="op">,</span> fn_body<span class="op">.</span>clone())<span class="op">;</span></span> -<span id="cb34-14"><a href="#cb34-14" aria-hidden="true"></a></span> -<span id="cb34-15"><a href="#cb34-15" aria-hidden="true"></a><span class="op">+</span> <span class="kw">let</span> arg_types <span class="op">=</span> extract_arg_types(fn_args<span class="op">.</span>clone())<span class="op">;</span></span> -<span id="cb34-16"><a href="#cb34-16" aria-hidden="true"></a><span class="op">+</span> <span class="kw">let</span> first_type <span class="op">=</span> <span class="op">&amp;</span>arg_types<span class="op">.</span>first()<span class="op">.</span>unwrap()<span class="op">;</span></span> -<span id="cb34-17"><a href="#cb34-17" aria-hidden="true"></a><span class="op">+</span> <span class="kw">let</span> type_aliases <span class="op">=</span> generate_type_aliases(</span> -<span id="cb34-18"><a href="#cb34-18" aria-hidden="true"></a><span class="op">+</span> <span class="op">&amp;</span>arg_types[<span class="dv">1</span><span class="op">..</span>]<span class="op">,</span></span> -<span id="cb34-19"><a href="#cb34-19" aria-hidden="true"></a><span class="op">+</span> extract_return_type(fn_return_type)<span class="op">,</span></span> -<span id="cb34-20"><a href="#cb34-20" aria-hidden="true"></a><span class="op">+</span> <span class="op">&amp;</span>fn_name<span class="op">,</span></span> -<span id="cb34-21"><a href="#cb34-21" aria-hidden="true"></a><span class="op">+</span> )<span class="op">;</span></span> -<span id="cb34-22"><a href="#cb34-22" aria-hidden="true"></a></span> -<span id="cb34-23"><a href="#cb34-23" aria-hidden="true"></a><span class="op">+</span> <span class="kw">let</span> return_type <span class="op">=</span> <span class="pp">format_ident!</span>(<span class="st">&quot;_{}_{}&quot;</span><span class="op">,</span> <span class="op">&amp;</span>fn_name<span class="op">,</span> <span class="pp">format!</span>(<span class="st">&quot;T{}&quot;</span><span class="op">,</span> type_aliases<span class="op">.</span>len() <span class="op">-</span> <span class="dv">1</span>))<span class="op">;</span></span> -<span id="cb34-24"><a href="#cb34-24" aria-hidden="true"></a></span> -<span id="cb34-25"><a href="#cb34-25" aria-hidden="true"></a><span class="op">+</span> <span class="kw">return</span> <span class="pp">quote!</span> <span class="op">{</span></span> -<span id="cb34-26"><a href="#cb34-26" aria-hidden="true"></a><span class="op">+</span> #(#type_aliases)<span class="op">;*</span> <span class="op">;</span></span> -<span id="cb34-27"><a href="#cb34-27" aria-hidden="true"></a><span class="op">+</span> #vis <span class="kw">fn</span> #fn_name (#first_ident<span class="op">:</span> #first_type) <span class="op">-&gt;</span> #return_type <span class="op">{</span></span> -<span id="cb34-28"><a href="#cb34-28" aria-hidden="true"></a><span class="op">+</span> #curried_body <span class="op">;</span></span> -<span id="cb34-29"><a href="#cb34-29" aria-hidden="true"></a><span class="op">+</span> <span class="op">}</span></span> -<span id="cb34-30"><a href="#cb34-30" aria-hidden="true"></a><span class="op">+</span> <span class="op">};</span></span> -<span id="cb34-31"><a href="#cb34-31" aria-hidden="true"></a> <span class="op">}</span></span></code></pre></div> +<div class="sourceCode" id="cb34"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb34-1"><a href="#cb34-1" aria-hidden="true" tabindex="-1"></a><span class="co">// src/lib.rs</span></span> +<span id="cb34-2"><a href="#cb34-2" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb34-3"><a href="#cb34-3" aria-hidden="true" tabindex="-1"></a> <span class="kw">fn</span> generate_curry(parsed<span class="op">:</span> ItemFn) <span class="op">-&gt;</span> <span class="pp">proc_macro2::</span>TokenStream <span class="op">{</span></span> +<span id="cb34-4"><a href="#cb34-4" aria-hidden="true" tabindex="-1"></a> <span class="kw">let</span> fn_body <span class="op">=</span> parsed<span class="op">.</span>block<span class="op">;</span></span> +<span id="cb34-5"><a href="#cb34-5" aria-hidden="true" tabindex="-1"></a> <span class="kw">let</span> sig <span class="op">=</span> parsed<span class="op">.</span>sig<span class="op">;</span></span> +<span id="cb34-6"><a href="#cb34-6" aria-hidden="true" tabindex="-1"></a> <span class="kw">let</span> vis <span class="op">=</span> parsed<span class="op">.</span>vis<span class="op">;</span></span> +<span id="cb34-7"><a href="#cb34-7" aria-hidden="true" tabindex="-1"></a> <span class="kw">let</span> fn_name <span class="op">=</span> sig<span class="op">.</span>ident<span class="op">;</span></span> +<span id="cb34-8"><a href="#cb34-8" aria-hidden="true" tabindex="-1"></a> <span class="kw">let</span> fn_args <span class="op">=</span> sig<span class="op">.</span>inputs<span class="op">;</span></span> +<span id="cb34-9"><a href="#cb34-9" aria-hidden="true" tabindex="-1"></a> <span class="kw">let</span> fn_return_type <span class="op">=</span> sig<span class="op">.</span>output<span class="op">;</span></span> +<span id="cb34-10"><a href="#cb34-10" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb34-11"><a href="#cb34-11" aria-hidden="true" tabindex="-1"></a> <span class="kw">let</span> arg_idents <span class="op">=</span> extract_arg_idents(fn_args<span class="op">.</span>clone())<span class="op">;</span></span> +<span id="cb34-12"><a href="#cb34-12" aria-hidden="true" tabindex="-1"></a> <span class="kw">let</span> first_ident <span class="op">=</span> <span class="op">&amp;</span>arg_idents<span class="op">.</span>first()<span class="op">.</span>unwrap()<span class="op">;</span></span> +<span id="cb34-13"><a href="#cb34-13" aria-hidden="true" tabindex="-1"></a> <span class="kw">let</span> curried_body <span class="op">=</span> generate_body(<span class="op">&amp;</span>arg_idents[<span class="dv">1</span><span class="op">..</span>]<span class="op">,</span> fn_body<span class="op">.</span>clone())<span class="op">;</span></span> +<span id="cb34-14"><a href="#cb34-14" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb34-15"><a href="#cb34-15" aria-hidden="true" tabindex="-1"></a><span class="op">+</span> <span class="kw">let</span> arg_types <span class="op">=</span> extract_arg_types(fn_args<span class="op">.</span>clone())<span class="op">;</span></span> +<span id="cb34-16"><a href="#cb34-16" aria-hidden="true" tabindex="-1"></a><span class="op">+</span> <span class="kw">let</span> first_type <span class="op">=</span> <span class="op">&amp;</span>arg_types<span class="op">.</span>first()<span class="op">.</span>unwrap()<span class="op">;</span></span> +<span id="cb34-17"><a href="#cb34-17" aria-hidden="true" tabindex="-1"></a><span class="op">+</span> <span class="kw">let</span> type_aliases <span class="op">=</span> generate_type_aliases(</span> +<span id="cb34-18"><a href="#cb34-18" aria-hidden="true" tabindex="-1"></a><span class="op">+</span> <span class="op">&amp;</span>arg_types[<span class="dv">1</span><span class="op">..</span>]<span class="op">,</span></span> +<span id="cb34-19"><a href="#cb34-19" aria-hidden="true" tabindex="-1"></a><span class="op">+</span> extract_return_type(fn_return_type)<span class="op">,</span></span> +<span id="cb34-20"><a href="#cb34-20" aria-hidden="true" tabindex="-1"></a><span class="op">+</span> <span class="op">&amp;</span>fn_name<span class="op">,</span></span> +<span id="cb34-21"><a href="#cb34-21" aria-hidden="true" tabindex="-1"></a><span class="op">+</span> )<span class="op">;</span></span> +<span id="cb34-22"><a href="#cb34-22" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb34-23"><a href="#cb34-23" aria-hidden="true" tabindex="-1"></a><span class="op">+</span> <span class="kw">let</span> return_type <span class="op">=</span> <span class="pp">format_ident!</span>(<span class="st">&quot;_{}_{}&quot;</span><span class="op">,</span> <span class="op">&amp;</span>fn_name<span class="op">,</span> <span class="pp">format!</span>(<span class="st">&quot;T{}&quot;</span><span class="op">,</span> type_aliases<span class="op">.</span>len() <span class="op">-</span> <span class="dv">1</span>))<span class="op">;</span></span> +<span id="cb34-24"><a href="#cb34-24" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb34-25"><a href="#cb34-25" aria-hidden="true" tabindex="-1"></a><span class="op">+</span> <span class="kw">return</span> <span class="pp">quote!</span> <span class="op">{</span></span> +<span id="cb34-26"><a href="#cb34-26" aria-hidden="true" tabindex="-1"></a><span class="op">+</span> #(#type_aliases)<span class="op">;*</span> <span class="op">;</span></span> +<span id="cb34-27"><a href="#cb34-27" aria-hidden="true" tabindex="-1"></a><span class="op">+</span> #vis <span class="kw">fn</span> #fn_name (#first_ident<span class="op">:</span> #first_type) <span class="op">-&gt;</span> #return_type <span class="op">{</span></span> +<span id="cb34-28"><a href="#cb34-28" aria-hidden="true" tabindex="-1"></a><span class="op">+</span> #curried_body <span class="op">;</span></span> +<span id="cb34-29"><a href="#cb34-29" aria-hidden="true" tabindex="-1"></a><span class="op">+</span> <span class="op">}</span></span> +<span id="cb34-30"><a href="#cb34-30" aria-hidden="true" tabindex="-1"></a><span class="op">+</span> <span class="op">};</span></span> +<span id="cb34-31"><a href="#cb34-31" aria-hidden="true" tabindex="-1"></a> <span class="op">}</span></span></code></pre></div> <p>Most of the additions are self explanatory, I’ll go through the return statement with you. We are returning a <code>quote!{ ... }</code>, so a <code>proc_macro2::TokenStream</code>. We are iterating through the <code>type_aliases</code> variable, which you might recall, is a <code>Vec&lt;TokenStream&gt;</code>. You might notice the sneaky semicolon before the <code>*</code>. This basically tells <code>quote</code>, to insert an item, then a semicolon, and then the next one, another semicolon, and so on. The semicolon is a separator. We need to manually insert another semicolon at the end of it all, <code>quote</code> doesn’t insert a separator at the end of the iteration.</p> <p>We retain the visibility and name of our original function. Our curried function takes as args, just the first argument of our original function. The return type of our curried function is actually, the last type alias we create. If you think back to our manually curried <code>add</code> function, we returned <code>T2</code>, which was in fact, the last type alias we created.</p> <p>I am sure, at this point, you are itching to test this out, but before that, let me introduce you to some good methods of debugging proc-macro code.</p> @@ -868,57 +868,57 @@ fn main() { <p>Writing proc-macros without <code>cargo-expand</code> is tantamount to driving a vehicle without rear view mirrors! Keep an eye on what is going on behind your back.</p> <p>Now, your macro won’t always compile, you might just recieve the bee movie script as an error. <code>cargo-expand</code> will not work in such cases. I would suggest printing out your variables to inspect them. <code>TokenStream</code> implements <code>Display</code> as well as <code>Debug</code>. We don’t always have to be respectable programmers. Just print it.</p> <p>Enough of that, lets get testing:</p> -<div class="sourceCode" id="cb37"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb37-1"><a href="#cb37-1" aria-hidden="true"></a><span class="co">// tests/smoke.rs</span></span> -<span id="cb37-2"><a href="#cb37-2" aria-hidden="true"></a></span> -<span id="cb37-3"><a href="#cb37-3" aria-hidden="true"></a><span class="at">#![</span>feature<span class="at">(</span>type_alias_impl_trait<span class="at">)]</span></span> -<span id="cb37-4"><a href="#cb37-4" aria-hidden="true"></a></span> -<span id="cb37-5"><a href="#cb37-5" aria-hidden="true"></a><span class="at">#[</span><span class="pp">crate_name::</span>curry<span class="at">]</span></span> -<span id="cb37-6"><a href="#cb37-6" aria-hidden="true"></a><span class="kw">fn</span> add(x<span class="op">:</span> <span class="dt">u32</span><span class="op">,</span> y<span class="op">:</span> <span class="dt">u32</span><span class="op">,</span> z<span class="op">:</span> <span class="dt">u32</span>) <span class="op">-&gt;</span> <span class="dt">u32</span> <span class="op">{</span></span> -<span id="cb37-7"><a href="#cb37-7" aria-hidden="true"></a> x <span class="op">+</span> y <span class="op">+</span> z</span> -<span id="cb37-8"><a href="#cb37-8" aria-hidden="true"></a><span class="op">}</span></span> -<span id="cb37-9"><a href="#cb37-9" aria-hidden="true"></a></span> -<span id="cb37-10"><a href="#cb37-10" aria-hidden="true"></a><span class="at">#[</span>test<span class="at">]</span></span> -<span id="cb37-11"><a href="#cb37-11" aria-hidden="true"></a><span class="kw">fn</span> works() <span class="op">{</span></span> -<span id="cb37-12"><a href="#cb37-12" aria-hidden="true"></a> <span class="pp">assert_eq!</span>(<span class="dv">15</span><span class="op">,</span> add(<span class="dv">4</span>)(<span class="dv">5</span>)(<span class="dv">6</span>))<span class="op">;</span></span> -<span id="cb37-13"><a href="#cb37-13" aria-hidden="true"></a><span class="op">}</span></span></code></pre></div> +<div class="sourceCode" id="cb37"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb37-1"><a href="#cb37-1" aria-hidden="true" tabindex="-1"></a><span class="co">// tests/smoke.rs</span></span> +<span id="cb37-2"><a href="#cb37-2" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb37-3"><a href="#cb37-3" aria-hidden="true" tabindex="-1"></a><span class="at">#![</span>feature<span class="at">(</span>type_alias_impl_trait<span class="at">)]</span></span> +<span id="cb37-4"><a href="#cb37-4" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb37-5"><a href="#cb37-5" aria-hidden="true" tabindex="-1"></a><span class="at">#[</span><span class="pp">crate_name::</span>curry<span class="at">]</span></span> +<span id="cb37-6"><a href="#cb37-6" aria-hidden="true" tabindex="-1"></a><span class="kw">fn</span> add(x<span class="op">:</span> <span class="dt">u32</span><span class="op">,</span> y<span class="op">:</span> <span class="dt">u32</span><span class="op">,</span> z<span class="op">:</span> <span class="dt">u32</span>) <span class="op">-&gt;</span> <span class="dt">u32</span> <span class="op">{</span></span> +<span id="cb37-7"><a href="#cb37-7" aria-hidden="true" tabindex="-1"></a> x <span class="op">+</span> y <span class="op">+</span> z</span> +<span id="cb37-8"><a href="#cb37-8" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span> +<span id="cb37-9"><a href="#cb37-9" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb37-10"><a href="#cb37-10" aria-hidden="true" tabindex="-1"></a><span class="at">#[</span>test<span class="at">]</span></span> +<span id="cb37-11"><a href="#cb37-11" aria-hidden="true" tabindex="-1"></a><span class="kw">fn</span> works() <span class="op">{</span></span> +<span id="cb37-12"><a href="#cb37-12" aria-hidden="true" tabindex="-1"></a> <span class="pp">assert_eq!</span>(<span class="dv">15</span><span class="op">,</span> add(<span class="dv">4</span>)(<span class="dv">5</span>)(<span class="dv">6</span>))<span class="op">;</span></span> +<span id="cb37-13"><a href="#cb37-13" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code></pre></div> <p>Run <code>cargo +nightly test</code>. You should see a pleasing message:</p> <pre><code>running 1 test test tests::works ... ok</code></pre> <p>Take a look at the expansion for our curry macro, via <code>cargo +nightly expand --tests smoke</code>:</p> -<div class="sourceCode" id="cb39"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb39-1"><a href="#cb39-1" aria-hidden="true"></a><span class="kw">type</span> _add_T0 <span class="op">=</span> <span class="dt">u32</span><span class="op">;</span></span> -<span id="cb39-2"><a href="#cb39-2" aria-hidden="true"></a><span class="kw">type</span> _add_T1 <span class="op">=</span> <span class="kw">impl</span> <span class="bu">Fn</span>(<span class="dt">u32</span>) <span class="op">-&gt;</span> _add_T0<span class="op">;</span></span> -<span id="cb39-3"><a href="#cb39-3" aria-hidden="true"></a><span class="kw">type</span> _add_T2 <span class="op">=</span> <span class="kw">impl</span> <span class="bu">Fn</span>(<span class="dt">u32</span>) <span class="op">-&gt;</span> _add_T1<span class="op">;</span></span> -<span id="cb39-4"><a href="#cb39-4" aria-hidden="true"></a><span class="kw">fn</span> add(x<span class="op">:</span> <span class="dt">u32</span>) <span class="op">-&gt;</span> _add_T2 <span class="op">{</span></span> -<span id="cb39-5"><a href="#cb39-5" aria-hidden="true"></a> <span class="kw">return</span> (<span class="kw">move</span> <span class="op">|</span>y<span class="op">|</span> <span class="op">{</span></span> -<span id="cb39-6"><a href="#cb39-6" aria-hidden="true"></a> <span class="kw">move</span> <span class="op">|</span>z<span class="op">|</span> <span class="op">{</span></span> -<span id="cb39-7"><a href="#cb39-7" aria-hidden="true"></a> <span class="kw">return</span> x <span class="op">+</span> y <span class="op">+</span> z<span class="op">;</span></span> -<span id="cb39-8"><a href="#cb39-8" aria-hidden="true"></a> <span class="op">}</span></span> -<span id="cb39-9"><a href="#cb39-9" aria-hidden="true"></a> <span class="op">}</span>)<span class="op">;</span></span> -<span id="cb39-10"><a href="#cb39-10" aria-hidden="true"></a><span class="op">}</span></span> -<span id="cb39-11"><a href="#cb39-11" aria-hidden="true"></a></span> -<span id="cb39-12"><a href="#cb39-12" aria-hidden="true"></a><span class="co">// a bunch of other stuff generated by #[test] and assert_eq!</span></span></code></pre></div> +<div class="sourceCode" id="cb39"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb39-1"><a href="#cb39-1" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> _add_T0 <span class="op">=</span> <span class="dt">u32</span><span class="op">;</span></span> +<span id="cb39-2"><a href="#cb39-2" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> _add_T1 <span class="op">=</span> <span class="kw">impl</span> <span class="bu">Fn</span>(<span class="dt">u32</span>) <span class="op">-&gt;</span> _add_T0<span class="op">;</span></span> +<span id="cb39-3"><a href="#cb39-3" aria-hidden="true" tabindex="-1"></a><span class="kw">type</span> _add_T2 <span class="op">=</span> <span class="kw">impl</span> <span class="bu">Fn</span>(<span class="dt">u32</span>) <span class="op">-&gt;</span> _add_T1<span class="op">;</span></span> +<span id="cb39-4"><a href="#cb39-4" aria-hidden="true" tabindex="-1"></a><span class="kw">fn</span> add(x<span class="op">:</span> <span class="dt">u32</span>) <span class="op">-&gt;</span> _add_T2 <span class="op">{</span></span> +<span id="cb39-5"><a href="#cb39-5" aria-hidden="true" tabindex="-1"></a> <span class="kw">return</span> (<span class="kw">move</span> <span class="op">|</span>y<span class="op">|</span> <span class="op">{</span></span> +<span id="cb39-6"><a href="#cb39-6" aria-hidden="true" tabindex="-1"></a> <span class="kw">move</span> <span class="op">|</span>z<span class="op">|</span> <span class="op">{</span></span> +<span id="cb39-7"><a href="#cb39-7" aria-hidden="true" tabindex="-1"></a> <span class="kw">return</span> x <span class="op">+</span> y <span class="op">+</span> z<span class="op">;</span></span> +<span id="cb39-8"><a href="#cb39-8" aria-hidden="true" tabindex="-1"></a> <span class="op">}</span></span> +<span id="cb39-9"><a href="#cb39-9" aria-hidden="true" tabindex="-1"></a> <span class="op">}</span>)<span class="op">;</span></span> +<span id="cb39-10"><a href="#cb39-10" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span> +<span id="cb39-11"><a href="#cb39-11" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb39-12"><a href="#cb39-12" aria-hidden="true" tabindex="-1"></a><span class="co">// a bunch of other stuff generated by #[test] and assert_eq!</span></span></code></pre></div> <p>A sight for sore eyes.</p> <p>Here is a more complex example that generates ten multiples of the first ten natural numbers:</p> -<div class="sourceCode" id="cb40"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb40-1"><a href="#cb40-1" aria-hidden="true"></a><span class="at">#[</span>curry<span class="at">]</span></span> -<span id="cb40-2"><a href="#cb40-2" aria-hidden="true"></a><span class="kw">fn</span> product(x<span class="op">:</span> <span class="dt">u32</span><span class="op">,</span> y<span class="op">:</span> <span class="dt">u32</span>) <span class="op">-&gt;</span> <span class="dt">u32</span> <span class="op">{</span></span> -<span id="cb40-3"><a href="#cb40-3" aria-hidden="true"></a> x <span class="op">*</span> y</span> -<span id="cb40-4"><a href="#cb40-4" aria-hidden="true"></a><span class="op">}</span></span> -<span id="cb40-5"><a href="#cb40-5" aria-hidden="true"></a></span> -<span id="cb40-6"><a href="#cb40-6" aria-hidden="true"></a><span class="kw">fn</span> multiples() <span class="op">-&gt;</span> <span class="dt">Vec</span><span class="op">&lt;</span><span class="dt">Vec</span><span class="op">&lt;</span><span class="dt">u32</span><span class="op">&gt;&gt;{</span></span> -<span id="cb40-7"><a href="#cb40-7" aria-hidden="true"></a> <span class="kw">let</span> v <span class="op">=</span> (<span class="dv">1</span><span class="op">..=</span><span class="dv">10</span>)<span class="op">.</span>map(product)<span class="op">;</span></span> -<span id="cb40-8"><a href="#cb40-8" aria-hidden="true"></a> <span class="kw">return</span> (<span class="dv">1</span><span class="op">..=</span><span class="dv">10</span>)</span> -<span id="cb40-9"><a href="#cb40-9" aria-hidden="true"></a> <span class="op">.</span>map(<span class="op">|</span>x<span class="op">|</span> v<span class="op">.</span>clone()<span class="op">.</span>map(<span class="op">|</span>f<span class="op">|</span> f(x))<span class="op">.</span>collect())</span> -<span id="cb40-10"><a href="#cb40-10" aria-hidden="true"></a> <span class="op">.</span>collect()<span class="op">;</span></span> -<span id="cb40-11"><a href="#cb40-11" aria-hidden="true"></a><span class="op">}</span></span></code></pre></div> +<div class="sourceCode" id="cb40"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb40-1"><a href="#cb40-1" aria-hidden="true" tabindex="-1"></a><span class="at">#[</span>curry<span class="at">]</span></span> +<span id="cb40-2"><a href="#cb40-2" aria-hidden="true" tabindex="-1"></a><span class="kw">fn</span> product(x<span class="op">:</span> <span class="dt">u32</span><span class="op">,</span> y<span class="op">:</span> <span class="dt">u32</span>) <span class="op">-&gt;</span> <span class="dt">u32</span> <span class="op">{</span></span> +<span id="cb40-3"><a href="#cb40-3" aria-hidden="true" tabindex="-1"></a> x <span class="op">*</span> y</span> +<span id="cb40-4"><a href="#cb40-4" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span> +<span id="cb40-5"><a href="#cb40-5" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb40-6"><a href="#cb40-6" aria-hidden="true" tabindex="-1"></a><span class="kw">fn</span> multiples() <span class="op">-&gt;</span> <span class="dt">Vec</span><span class="op">&lt;</span><span class="dt">Vec</span><span class="op">&lt;</span><span class="dt">u32</span><span class="op">&gt;&gt;{</span></span> +<span id="cb40-7"><a href="#cb40-7" aria-hidden="true" tabindex="-1"></a> <span class="kw">let</span> v <span class="op">=</span> (<span class="dv">1</span><span class="op">..=</span><span class="dv">10</span>)<span class="op">.</span>map(product)<span class="op">;</span></span> +<span id="cb40-8"><a href="#cb40-8" aria-hidden="true" tabindex="-1"></a> <span class="kw">return</span> (<span class="dv">1</span><span class="op">..=</span><span class="dv">10</span>)</span> +<span id="cb40-9"><a href="#cb40-9" aria-hidden="true" tabindex="-1"></a> <span class="op">.</span>map(<span class="op">|</span>x<span class="op">|</span> v<span class="op">.</span>clone()<span class="op">.</span>map(<span class="op">|</span>f<span class="op">|</span> f(x))<span class="op">.</span>collect())</span> +<span id="cb40-10"><a href="#cb40-10" aria-hidden="true" tabindex="-1"></a> <span class="op">.</span>collect()<span class="op">;</span></span> +<span id="cb40-11"><a href="#cb40-11" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code></pre></div> <h3 id="notes">Notes</h3> <p>I didn’t quite explain why we use <code>move |arg|</code> in our closure. This is because we want to take ownership of the variable supplied to us. Take a look at this example:</p> -<div class="sourceCode" id="cb41"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb41-1"><a href="#cb41-1" aria-hidden="true"></a><span class="kw">let</span> v <span class="op">=</span> add(<span class="dv">5</span>)<span class="op">;</span></span> -<span id="cb41-2"><a href="#cb41-2" aria-hidden="true"></a><span class="kw">let</span> g<span class="op">;</span></span> -<span id="cb41-3"><a href="#cb41-3" aria-hidden="true"></a><span class="op">{</span></span> -<span id="cb41-4"><a href="#cb41-4" aria-hidden="true"></a> <span class="kw">let</span> x <span class="op">=</span> <span class="dv">5</span><span class="op">;</span></span> -<span id="cb41-5"><a href="#cb41-5" aria-hidden="true"></a> g <span class="op">=</span> v(x)<span class="op">;</span></span> -<span id="cb41-6"><a href="#cb41-6" aria-hidden="true"></a><span class="op">}</span></span> -<span id="cb41-7"><a href="#cb41-7" aria-hidden="true"></a><span class="pp">println!</span>(<span class="st">&quot;{}&quot;</span><span class="op">,</span> g(<span class="dv">2</span>))<span class="op">;</span></span></code></pre></div> +<div class="sourceCode" id="cb41"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb41-1"><a href="#cb41-1" aria-hidden="true" tabindex="-1"></a><span class="kw">let</span> v <span class="op">=</span> add(<span class="dv">5</span>)<span class="op">;</span></span> +<span id="cb41-2"><a href="#cb41-2" aria-hidden="true" tabindex="-1"></a><span class="kw">let</span> g<span class="op">;</span></span> +<span id="cb41-3"><a href="#cb41-3" aria-hidden="true" tabindex="-1"></a><span class="op">{</span></span> +<span id="cb41-4"><a href="#cb41-4" aria-hidden="true" tabindex="-1"></a> <span class="kw">let</span> x <span class="op">=</span> <span class="dv">5</span><span class="op">;</span></span> +<span id="cb41-5"><a href="#cb41-5" aria-hidden="true" tabindex="-1"></a> g <span class="op">=</span> v(x)<span class="op">;</span></span> +<span id="cb41-6"><a href="#cb41-6" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span> +<span id="cb41-7"><a href="#cb41-7" aria-hidden="true" tabindex="-1"></a><span class="pp">println!</span>(<span class="st">&quot;{}&quot;</span><span class="op">,</span> g(<span class="dv">2</span>))<span class="op">;</span></span></code></pre></div> <p>Variable <code>x</code> goes out of scope before <code>g</code> can return a concrete value. If we take ownership of <code>x</code> by <code>move</code>ing it into our closure, we can expect this to work reliably. In fact, rustc understands this, and forces you to use <code>move</code>.</p> <p>This usage of <code>move</code> is exactly why <strong>a curried function without a return is useless</strong>. Every variable we pass to our curried function gets moved into its local scope. Playing with these variables cannot cause a change outside this scope. Returning is our only method of interaction with anything beyond this function.</p> <h3 id="conclusion">Conclusion</h3> @@ -995,34 +995,34 @@ test tests::works ... ok</code></pre> Rapid Refactoring With Vim <p>Last weekend, I was tasked with refactoring the 96 unit tests on <a href="https://github.com/ruma/ruma-events/pull/70">ruma-events</a> to use strictly typed json objects using <code>serde_json::json!</code> instead of raw strings. It was rather painless thanks to vim :)</p> <p>Here’s a small sample of what had to be done (note the lines prefixed with the arrow):</p> -<div class="sourceCode" id="cb1"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true"></a>→ <span class="kw">use</span> <span class="pp">serde_json::</span><span class="op">{</span>from_str<span class="op">};</span></span> -<span id="cb1-2"><a href="#cb1-2" aria-hidden="true"></a> </span> -<span id="cb1-3"><a href="#cb1-3" aria-hidden="true"></a> <span class="at">#[</span>test<span class="at">]</span></span> -<span id="cb1-4"><a href="#cb1-4" aria-hidden="true"></a> <span class="kw">fn</span> deserialize() <span class="op">{</span></span> -<span id="cb1-5"><a href="#cb1-5" aria-hidden="true"></a> <span class="pp">assert_eq!</span>(</span> -<span id="cb1-6"><a href="#cb1-6" aria-hidden="true"></a>→ <span class="pp">from_str::</span><span class="op">&lt;</span>Action<span class="op">&gt;</span>(<span class="st">r#&quot;{&quot;set_tweak&quot;: &quot;highlight&quot;}&quot;#</span>)<span class="op">,</span></span> -<span id="cb1-7"><a href="#cb1-7" aria-hidden="true"></a> <span class="pp">Action::</span>SetTweak(<span class="pp">Tweak::</span>Highlight <span class="op">{</span> value<span class="op">:</span> <span class="cn">true</span> <span class="op">}</span>)</span> -<span id="cb1-8"><a href="#cb1-8" aria-hidden="true"></a> )<span class="op">;</span></span> -<span id="cb1-9"><a href="#cb1-9" aria-hidden="true"></a> <span class="op">}</span></span></code></pre></div> +<div class="sourceCode" id="cb1"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a>→ <span class="kw">use</span> <span class="pp">serde_json::</span><span class="op">{</span>from_str<span class="op">};</span></span> +<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a> </span> +<span id="cb1-3"><a href="#cb1-3" aria-hidden="true" tabindex="-1"></a> <span class="at">#[</span>test<span class="at">]</span></span> +<span id="cb1-4"><a href="#cb1-4" aria-hidden="true" tabindex="-1"></a> <span class="kw">fn</span> deserialize() <span class="op">{</span></span> +<span id="cb1-5"><a href="#cb1-5" aria-hidden="true" tabindex="-1"></a> <span class="pp">assert_eq!</span>(</span> +<span id="cb1-6"><a href="#cb1-6" aria-hidden="true" tabindex="-1"></a>→ <span class="pp">from_str::</span><span class="op">&lt;</span>Action<span class="op">&gt;</span>(<span class="st">r#&quot;{&quot;set_tweak&quot;: &quot;highlight&quot;}&quot;#</span>)<span class="op">,</span></span> +<span id="cb1-7"><a href="#cb1-7" aria-hidden="true" tabindex="-1"></a> <span class="pp">Action::</span>SetTweak(<span class="pp">Tweak::</span>Highlight <span class="op">{</span> value<span class="op">:</span> <span class="cn">true</span> <span class="op">}</span>)</span> +<span id="cb1-8"><a href="#cb1-8" aria-hidden="true" tabindex="-1"></a> )<span class="op">;</span></span> +<span id="cb1-9"><a href="#cb1-9" aria-hidden="true" tabindex="-1"></a> <span class="op">}</span></span></code></pre></div> <p>had to be converted to:</p> -<div class="sourceCode" id="cb2"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true"></a>→ <span class="kw">use</span> <span class="pp">serde_json::</span><span class="op">{</span>from_value<span class="op">};</span></span> -<span id="cb2-2"><a href="#cb2-2" aria-hidden="true"></a> </span> -<span id="cb2-3"><a href="#cb2-3" aria-hidden="true"></a> <span class="at">#[</span>test<span class="at">]</span></span> -<span id="cb2-4"><a href="#cb2-4" aria-hidden="true"></a> <span class="kw">fn</span> deserialize() <span class="op">{</span></span> -<span id="cb2-5"><a href="#cb2-5" aria-hidden="true"></a> <span class="pp">assert_eq!</span>(</span> -<span id="cb2-6"><a href="#cb2-6" aria-hidden="true"></a>→ <span class="pp">from_value::</span><span class="op">&lt;</span>Action<span class="op">&gt;</span>(<span class="pp">json!</span>(<span class="op">{</span><span class="st">&quot;set_tweak&quot;</span><span class="op">:</span> <span class="st">&quot;highlight&quot;</span><span class="op">}</span>))<span class="op">,</span></span> -<span id="cb2-7"><a href="#cb2-7" aria-hidden="true"></a> <span class="pp">Action::</span>SetTweak(<span class="pp">Tweak::</span>Highlight <span class="op">{</span> value<span class="op">:</span> <span class="cn">true</span> <span class="op">}</span>)</span> -<span id="cb2-8"><a href="#cb2-8" aria-hidden="true"></a> )<span class="op">;</span></span> -<span id="cb2-9"><a href="#cb2-9" aria-hidden="true"></a> <span class="op">}</span></span></code></pre></div> +<div class="sourceCode" id="cb2"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a>→ <span class="kw">use</span> <span class="pp">serde_json::</span><span class="op">{</span>from_value<span class="op">};</span></span> +<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a> </span> +<span id="cb2-3"><a href="#cb2-3" aria-hidden="true" tabindex="-1"></a> <span class="at">#[</span>test<span class="at">]</span></span> +<span id="cb2-4"><a href="#cb2-4" aria-hidden="true" tabindex="-1"></a> <span class="kw">fn</span> deserialize() <span class="op">{</span></span> +<span id="cb2-5"><a href="#cb2-5" aria-hidden="true" tabindex="-1"></a> <span class="pp">assert_eq!</span>(</span> +<span id="cb2-6"><a href="#cb2-6" aria-hidden="true" tabindex="-1"></a>→ <span class="pp">from_value::</span><span class="op">&lt;</span>Action<span class="op">&gt;</span>(<span class="pp">json!</span>(<span class="op">{</span><span class="st">&quot;set_tweak&quot;</span><span class="op">:</span> <span class="st">&quot;highlight&quot;</span><span class="op">}</span>))<span class="op">,</span></span> +<span id="cb2-7"><a href="#cb2-7" aria-hidden="true" tabindex="-1"></a> <span class="pp">Action::</span>SetTweak(<span class="pp">Tweak::</span>Highlight <span class="op">{</span> value<span class="op">:</span> <span class="cn">true</span> <span class="op">}</span>)</span> +<span id="cb2-8"><a href="#cb2-8" aria-hidden="true" tabindex="-1"></a> )<span class="op">;</span></span> +<span id="cb2-9"><a href="#cb2-9" aria-hidden="true" tabindex="-1"></a> <span class="op">}</span></span></code></pre></div> <h3 id="the-arglist">The arglist</h3> <p>For the initial pass, I decided to handle imports, this was a simple find and replace operation, done to all the files containing tests. Luckily, modules (and therefore files) containing tests in Rust are annotated with the <code>#[cfg(test)]</code> attribute. I opened all such files:</p> -<div class="sourceCode" id="cb3"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true"></a><span class="co"># `grep -l pattern files` lists all the files</span></span> -<span id="cb3-2"><a href="#cb3-2" aria-hidden="true"></a><span class="co"># matching the pattern</span></span> -<span id="cb3-3"><a href="#cb3-3" aria-hidden="true"></a></span> -<span id="cb3-4"><a href="#cb3-4" aria-hidden="true"></a><span class="ex">vim</span> <span class="va">$(</span><span class="fu">grep</span> -l <span class="st">&#39;cfg\(test\)&#39;</span> ./**/*.rs<span class="va">)</span></span> -<span id="cb3-5"><a href="#cb3-5" aria-hidden="true"></a></span> -<span id="cb3-6"><a href="#cb3-6" aria-hidden="true"></a><span class="co"># expands to something like:</span></span> -<span id="cb3-7"><a href="#cb3-7" aria-hidden="true"></a><span class="ex">vim</span> push_rules.rs room/member.rs key/verification/lib.rs</span></code></pre></div> +<div class="sourceCode" id="cb3"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a><span class="co"># `grep -l pattern files` lists all the files</span></span> +<span id="cb3-2"><a href="#cb3-2" aria-hidden="true" tabindex="-1"></a><span class="co"># matching the pattern</span></span> +<span id="cb3-3"><a href="#cb3-3" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb3-4"><a href="#cb3-4" aria-hidden="true" tabindex="-1"></a><span class="ex">vim</span> <span class="va">$(</span><span class="fu">grep</span> <span class="at">-l</span> <span class="st">&#39;cfg\(test\)&#39;</span> ./<span class="pp">**</span>/<span class="pp">*</span>.rs<span class="va">)</span></span> +<span id="cb3-5"><a href="#cb3-5" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb3-6"><a href="#cb3-6" aria-hidden="true" tabindex="-1"></a><span class="co"># expands to something like:</span></span> +<span id="cb3-7"><a href="#cb3-7" aria-hidden="true" tabindex="-1"></a><span class="ex">vim</span> push_rules.rs room/member.rs key/verification/lib.rs</span></code></pre></div> <p>Starting vim with more than one file at the shell prompt populates the arglist. Hit <code>:args</code> to see the list of files currently ready to edit. The square [brackets] indicate the current file. Navigate through the arglist with <code>:next</code> and <code>:prev</code>. I use tpope’s vim-unimpaired <a href="#fn1" class="footnote-ref" id="fnref1" role="doc-noteref"><sup>1</sup></a>, which adds <code>]a</code> and <code>[a</code>, mapped to <code>:next</code> and <code>:prev</code>.</p> <p>All that’s left to do is the find and replace, for which we will be using vim’s <code>argdo</code>, applying a substitution to every file in the arglist:</p> <pre><code>:argdo s/from_str/from_value/g</code></pre> @@ -1204,26 +1204,26 @@ Reading symbols from main... # yay!</code></pre> <p>I chose to write in markdown, and convert to html with <a href="https://kristaps.bsd.lv/lowdown/">lowdown</a>.</p> <h3 id="directory-structure">Directory structure</h3> <p>I host my site on GitHub pages, so <code>docs/</code> has to be the entry point. Markdown formatted posts go into <code>posts/</code>, get converted into html, and end up in <code>docs/index.html</code>, something like this:</p> -<div class="sourceCode" id="cb1"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true"></a><span class="va">posts=$(</span><span class="fu">ls</span> -t ./posts<span class="va">)</span> # <span class="ex">chronological</span> order!</span> -<span id="cb1-2"><a href="#cb1-2" aria-hidden="true"></a><span class="kw">for</span> <span class="ex">f</span> in <span class="va">$posts</span><span class="kw">;</span> <span class="kw">do</span></span> -<span id="cb1-3"><a href="#cb1-3" aria-hidden="true"></a> <span class="va">file=</span><span class="st">&quot;./posts/&quot;</span><span class="va">$f</span> # <span class="kw">`</span><span class="fu">ls</span><span class="kw">`</span> <span class="ex">mangled</span> our file paths</span> -<span id="cb1-4"><a href="#cb1-4" aria-hidden="true"></a> <span class="bu">echo</span> <span class="st">&quot;generating post </span><span class="va">$file</span><span class="st">&quot;</span></span> -<span id="cb1-5"><a href="#cb1-5" aria-hidden="true"></a></span> -<span id="cb1-6"><a href="#cb1-6" aria-hidden="true"></a> <span class="va">html=$(</span><span class="ex">lowdown</span> <span class="st">&quot;</span><span class="va">$file</span><span class="st">&quot;</span><span class="va">)</span></span> -<span id="cb1-7"><a href="#cb1-7" aria-hidden="true"></a> <span class="bu">echo</span> -e <span class="st">&quot;html&quot;</span> <span class="op">&gt;&gt;</span> docs/index.html</span> -<span id="cb1-8"><a href="#cb1-8" aria-hidden="true"></a><span class="kw">done</span></span></code></pre></div> +<div class="sourceCode" id="cb1"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="va">posts</span><span class="op">=</span><span class="va">$(</span><span class="fu">ls</span> <span class="at">-t</span> ./posts<span class="va">)</span> <span class="co"># chronological order!</span></span> +<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a><span class="cf">for</span> f <span class="kw">in</span> <span class="va">$posts</span><span class="kw">;</span> <span class="cf">do</span></span> +<span id="cb1-3"><a href="#cb1-3" aria-hidden="true" tabindex="-1"></a> <span class="va">file</span><span class="op">=</span><span class="st">&quot;./posts/&quot;</span><span class="va">$f</span> <span class="co"># `ls` mangled our file paths</span></span> +<span id="cb1-4"><a href="#cb1-4" aria-hidden="true" tabindex="-1"></a> <span class="bu">echo</span> <span class="st">&quot;generating post </span><span class="va">$file</span><span class="st">&quot;</span></span> +<span id="cb1-5"><a href="#cb1-5" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb1-6"><a href="#cb1-6" aria-hidden="true" tabindex="-1"></a> <span class="va">html</span><span class="op">=</span><span class="va">$(</span><span class="ex">lowdown</span> <span class="st">&quot;</span><span class="va">$file</span><span class="st">&quot;</span><span class="va">)</span></span> +<span id="cb1-7"><a href="#cb1-7" aria-hidden="true" tabindex="-1"></a> <span class="bu">echo</span> <span class="at">-e</span> <span class="st">&quot;html&quot;</span> <span class="op">&gt;&gt;</span> docs/index.html</span> +<span id="cb1-8"><a href="#cb1-8" aria-hidden="true" tabindex="-1"></a><span class="cf">done</span></span></code></pre></div> <h3 id="assets">Assets</h3> <p>Most static site generators recommend dropping image assets into the site source itself. That does have it’s merits, but I prefer hosting images separately:</p> -<div class="sourceCode" id="cb2"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true"></a><span class="co"># strip file extension</span></span> -<span id="cb2-2"><a href="#cb2-2" aria-hidden="true"></a><span class="va">ext=</span><span class="st">&quot;</span><span class="va">${1##</span>*.<span class="va">}</span><span class="st">&quot;</span></span> -<span id="cb2-3"><a href="#cb2-3" aria-hidden="true"></a></span> -<span id="cb2-4"><a href="#cb2-4" aria-hidden="true"></a><span class="co"># generate a random file name</span></span> -<span id="cb2-5"><a href="#cb2-5" aria-hidden="true"></a><span class="va">id=$(</span> <span class="fu">cat</span> /dev/urandom <span class="kw">|</span> <span class="fu">tr</span> -dc <span class="st">&#39;a-zA-Z0-9&#39;</span> <span class="kw">|</span> <span class="ex">fold</span> -w 2 <span class="kw">|</span> <span class="fu">head</span> -n 1 <span class="va">)</span></span> -<span id="cb2-6"><a href="#cb2-6" aria-hidden="true"></a><span class="va">id=</span><span class="st">&quot;</span><span class="va">$id</span><span class="st">.</span><span class="va">$ext</span><span class="st">&quot;</span></span> -<span id="cb2-7"><a href="#cb2-7" aria-hidden="true"></a></span> -<span id="cb2-8"><a href="#cb2-8" aria-hidden="true"></a><span class="co"># copy to my file host</span></span> -<span id="cb2-9"><a href="#cb2-9" aria-hidden="true"></a><span class="fu">scp</span> -P 443 <span class="st">&quot;</span><span class="va">$1</span><span class="st">&quot;</span> emerald:files/<span class="st">&quot;</span><span class="va">$id</span><span class="st">&quot;</span> </span> -<span id="cb2-10"><a href="#cb2-10" aria-hidden="true"></a><span class="bu">echo</span> <span class="st">&quot;https://u.peppe.rs/</span><span class="va">$id</span><span class="st">&quot;</span></span></code></pre></div> +<div class="sourceCode" id="cb2"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a><span class="co"># strip file extension</span></span> +<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a><span class="va">ext</span><span class="op">=</span><span class="st">&quot;</span><span class="va">${1</span><span class="op">##</span><span class="pp">*</span>.<span class="va">}</span><span class="st">&quot;</span></span> +<span id="cb2-3"><a href="#cb2-3" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb2-4"><a href="#cb2-4" aria-hidden="true" tabindex="-1"></a><span class="co"># generate a random file name</span></span> +<span id="cb2-5"><a href="#cb2-5" aria-hidden="true" tabindex="-1"></a><span class="va">id</span><span class="op">=</span><span class="va">$(</span> <span class="fu">cat</span> /dev/urandom <span class="kw">|</span> <span class="fu">tr</span> <span class="at">-dc</span> <span class="st">&#39;a-zA-Z0-9&#39;</span> <span class="kw">|</span> <span class="ex">fold</span> <span class="at">-w</span> 2 <span class="kw">|</span> <span class="fu">head</span> <span class="at">-n</span> 1 <span class="va">)</span></span> +<span id="cb2-6"><a href="#cb2-6" aria-hidden="true" tabindex="-1"></a><span class="va">id</span><span class="op">=</span><span class="st">&quot;</span><span class="va">$id</span><span class="st">.</span><span class="va">$ext</span><span class="st">&quot;</span></span> +<span id="cb2-7"><a href="#cb2-7" aria-hidden="true" tabindex="-1"></a></span> +<span id="cb2-8"><a href="#cb2-8" aria-hidden="true" tabindex="-1"></a><span class="co"># copy to my file host</span></span> +<span id="cb2-9"><a href="#cb2-9" aria-hidden="true" tabindex="-1"></a><span class="fu">scp</span> <span class="at">-P</span> 443 <span class="st">&quot;</span><span class="va">$1</span><span class="st">&quot;</span> emerald:files/<span class="st">&quot;</span><span class="va">$id</span><span class="st">&quot;</span> </span> +<span id="cb2-10"><a href="#cb2-10" aria-hidden="true" tabindex="-1"></a><span class="bu">echo</span> <span class="st">&quot;https://u.peppe.rs/</span><span class="va">$id</span><span class="st">&quot;</span></span></code></pre></div> <h3 id="templating">Templating</h3> <p><a href="https://github.com/NerdyPepper/site/blob/master/generate.sh"><code>generate.sh</code></a> brings the above bits and pieces together (with some extra cruft to avoid javascript). It uses <code>sed</code> to produce nice titles from the file names (removes underscores, title-case), and <code>date(1)</code> to add the date to each post listing!</p> https://peppe.rs/posts/static_sites_with_bash/ diff --git a/docs/posts/SDL2_devlog/index.html b/docs/posts/SDL2_devlog/index.html index f5e631f..0e76515 100644 --- a/docs/posts/SDL2_devlog/index.html +++ b/docs/posts/SDL2_devlog/index.html @@ -60,48 +60,48 @@

Day 17

I decided to give the text-only statusline a touch up, by adding a active color and dither level preview. Aligning the “widget” to the right of statusline involved a lot more than I thought, so I created a ghetto CSS-like rectangle placement system to position containers inside containers:

-
// roughly something like this
-let statusline = 
-    Container::new(Offset::Left(0), Offset::Bottom(40))
-    .width(Size::Max)
-    .height(Size::Absolute(20));
-    
-let mut primary = Container::uninit()
-    .width(Size::Absolute(16))
-    .height(Size::Absolute(16));
-    
-container.place(
-    &mut padding_box,
-    HorAlign::Right,
-    VertAlign::Center
-);
+
// roughly something like this
+let statusline = 
+    Container::new(Offset::Left(0), Offset::Bottom(40))
+    .width(Size::Max)
+    .height(Size::Absolute(20));
+    
+let mut primary = Container::uninit()
+    .width(Size::Absolute(16))
+    .height(Size::Absolute(16));
+    
+container.place(
+    &mut padding_box,
+    HorAlign::Right,
+    VertAlign::Center
+);

The result (brush preview on the bottom right):

Day 16

The embedded lisp is coming along nicely, users can load a custom rc.lisp, which is evaluated on startup. To disable to grid on start, for example:

-
;;; rc.lisp
-(toggle-grid)
+
;;; rc.lisp
+(toggle-grid)

Some aliases to switch between brushes:

-
;;; rc.lisp
-(define (brush kind)
-  (cond
-    ((eq? kind 'f) (brush-fill))
-    ((eq? kind 'c) (brush-circle))
-    ((eq? kind 'l) (brush-line))
-    ((eq? kind 'l+) (brush-line-extend))
-    (else (brush-circle))))
+
;;; rc.lisp
+(define (brush kind)
+  (cond
+    ((eq? kind 'f) (brush-fill))
+    ((eq? kind 'c) (brush-circle))
+    ((eq? kind 'l) (brush-line))
+    ((eq? kind 'l+) (brush-line-extend))
+    (else (brush-circle))))

The following script draws a straight line along a given axis, at a given distance from the canvas boundary:

Day 15

I began writing a standard library for the lisp, in lisp. It includes basic list operations: car, cdr, null?, list, higher order functions: map, filter, fold:

-
(define (member? item ls)
-  (fold #f
-        (lambda (acc x) (or acc (eq? item x)))
-        ls))
+
(define (member? item ls)
+  (fold #f
+        (lambda (acc x) (or acc (eq? item x)))
+        ls))

Day 14

I attempted a small art piece using the editor, while it was largely usable, I felt a certain lack of feedback. The brushes just didn’t relay as much info as I’d have liked, for example, the approximate points of the line or the angle made by the line against the x-axis. Unfortunately, the existing infrastructure around brushes and line drawing didn’t easily allow for this either. I went ahead and reimplemented brushes, and added a new flood fill brush too:

@@ -134,11 +134,11 @@

Day 8

One of my favourite features of GIMP was symmetric editing. I added some coordinate geometry primitives to my pixmap abstraction, allowing for mirroring and reflecting figures about lines or points. The result was an ergonomic function that applies symmetry to any painting operation, (undo/redo works as expected):

-
let line = self.pixmap.get_line(start, end);
-let sym_line = self.symmetry.apply(&line);
-for point on line.extend(sym_line) {
-    // draw to window
-}
+
let line = self.pixmap.get_line(start, end);
+let sym_line = self.symmetry.apply(&line);
+for point on line.extend(sym_line) {
+    // draw to window
+}
diff --git a/docs/posts/auto-currying_rust_functions/index.html b/docs/posts/auto-currying_rust_functions/index.html index 3111060..0d6fc77 100644 --- a/docs/posts/auto-currying_rust_functions/index.html +++ b/docs/posts/auto-currying_rust_functions/index.html @@ -98,17 +98,17 @@ h(x)(y)(z) = g(y)(z) = k(z) = v

We will be using Attribute macros to convert a Rust function into a curried Rust function, which we should be able to call via: function(arg1)(arg2).

Definitions

Being respectable programmers, we define the input to and the output from our proc-macro. Here’s a good non-trivial function to start out with:

-
fn add(x: u32, y: u32, z: u32) -> u32 {
-  return x + y + z;
-}
+
fn add(x: u32, y: u32, z: u32) -> u32 {
+  return x + y + z;
+}

Hmm, what would our output look like? What should our proc-macro generate ideally? Well, if we understood currying correctly, we should accept an argument and return a function that accepts an argument and returns … you get the point. Something like this should do:

-
fn add_curried1(x: u32) -> ? {
-  return fn add_curried2 (y: u32) -> ? {
-    return fn add_curried3 (z: u32) -> u32 {
-      return x + y + z;
-    }
-  }
-}
+
fn add_curried1(x: u32) -> ? {
+  return fn add_curried2 (y: u32) -> ? {
+    return fn add_curried3 (z: u32) -> u32 {
+      return x + y + z;
+    }
+  }
+}

A couple of things to note:

Return types
We have placed ?s in place of return types. Let’s try to fix that. add_curried3 returns the ‘value’, so u32 is accurate. add_curried2 returns add_curried3. What is the type of add_curried3? It is a function that takes in a u32 and returns a u32. So a fn(u32) -> u32 will do right? No, I’ll explain why in the next point, but for now, we will make use of the Fn trait, our return type is impl Fn(u32) -> u32. This basically tells the compiler that we will be returning something function-like, a.k.a, behaves like a Fn. Cool!

@@ -121,9 +121,9 @@ We have placed ?s in place of return types. Let’s try to fix that A function cannot access it’s environment. Our solution will not work. add_curried3 attempts to access x, which is not allowed! A closure1 however, can. If we are returning a closure, our return type must be impl Fn, and not fn. The difference between the Fn trait and function pointers is beyond the scope of this post.

Refinement

Armed with knowledge, we refine our expected output, this time, employing closures:

-
fn add(x: u32) -> impl Fn(u32) -> impl Fn(u32) -> u32 {
-  return move |y| move |z| x + y + z;
-}
+
fn add(x: u32) -> impl Fn(u32) -> impl Fn(u32) -> u32 {
+  return move |y| move |z| x + y + z;
+}

Alas, that does not compile either! It errors out with the following message:

error[E0562]: `impl Trait` not allowed outside of function
 and inherent method return types
@@ -134,15 +134,15 @@ and inherent method return types
 

You are allowed to return an impl Fn only inside a function. We are currently returning it from another return! Or at least, that was the most I could make out of the error message.

We are going to have to cheat a bit to fix this issue; with type aliases and a convenient nightly feature 2:

-
#![feature(type_alias_impl_trait)]  // allows us to use `impl Fn` in type aliases!
-
-type T0 = u32;                 // the return value when zero args are to be applied
-type T1 = impl Fn(u32) -> T0;  // the return value when one arg is to be applied
-type T2 = impl Fn(u32) -> T1;  // the return value when two args are to be applied
-
-fn add(x: u32) -> T2 {
-  return move |y| move |z| x + y + z;
-}
+
#![feature(type_alias_impl_trait)]  // allows us to use `impl Fn` in type aliases!
+
+type T0 = u32;                 // the return value when zero args are to be applied
+type T1 = impl Fn(u32) -> T0;  // the return value when one arg is to be applied
+type T2 = impl Fn(u32) -> T1;  // the return value when two args are to be applied
+
+fn add(x: u32) -> T2 {
+  return move |y| move |z| x + y + z;
+}

Drop that into a cargo project, call add(4)(5)(6), cross your fingers, and run cargo +nightly run. You should see a 15 unless you forgot to print it!

The In-Betweens

Let us write the magical bits that take us from function to curried function.

@@ -176,19 +176,19 @@ proc-macro = true # this is important!

We will be using an external proc-macro2 crate as well as an internal proc-macro crate. Not confusing at all!

The attribute macro

Drop this into src/lib.rs, to get the ball rolling.

-
// src/lib.rs
-
-use proc_macro::TokenStream;  // 1
-use quote::quote;
-use syn::{parse_macro_input, ItemFn};
-
-#[proc_macro_attribute]   // 2
-pub fn curry(_attr: TokenStream, item: TokenStream) -> TokenStream {
-  let parsed = parse_macro_input!(item as ItemFn);  // 3
-  generate_curry(parsed).into()  // 4
-}
-
-fn generate_curry(parsed: ItemFn) -> proc_macro2::TokenStream {}
+
// src/lib.rs
+
+use proc_macro::TokenStream;  // 1
+use quote::quote;
+use syn::{parse_macro_input, ItemFn};
+
+#[proc_macro_attribute]   // 2
+pub fn curry(_attr: TokenStream, item: TokenStream) -> TokenStream {
+  let parsed = parse_macro_input!(item as ItemFn);  // 3
+  generate_curry(parsed).into()  // 4
+}
+
+fn generate_curry(parsed: ItemFn) -> proc_macro2::TokenStream {}

1. Imports

A Tokenstream holds (hopefully valid) Rust code, this is the type of our input and output. Note that we are importing this type from proc_macro and not proc_macro2.

quote! from the quote crate is a macro that allows us to quickly produce TokenStreams. Much like the LISP quote procedure, you can use the quote! macro for symbolic transformations.

@@ -200,16 +200,16 @@ proc-macro = true # this is important!

4. Returning TokenStreams

We haven’t filled in generate_curry yet, but we can see that it returns a proc_macro2::TokenStream and not a proc_macro::TokenStream, so drop a .into() to convert it.

Lets move on, and fill in generate_curry, I would suggest keeping the documentation for syn::ItemFn and syn::Signature open.

-
// src/lib.rs
-
-fn generate_curry(parsed: ItemFn) -> proc_macro2::TokenStream {
-  let fn_body = parsed.block;      // function body
-  let sig = parsed.sig;            // function signature
-  let vis = parsed.vis;            // visibility, pub or not
-  let fn_name = sig.ident;         // function name/identifier
-  let fn_args = sig.inputs;        // comma separated args
-  let fn_return_type = sig.output; // return type
-}
+
// src/lib.rs
+
+fn generate_curry(parsed: ItemFn) -> proc_macro2::TokenStream {
+  let fn_body = parsed.block;      // function body
+  let sig = parsed.sig;            // function signature
+  let vis = parsed.vis;            // visibility, pub or not
+  let fn_name = sig.ident;         // function name/identifier
+  let fn_args = sig.inputs;        // comma separated args
+  let fn_return_type = sig.output; // return type
+}

We are simply extracting the bits of the function, we will be reusing the original function’s visibility and name. Take a look at what syn::Signature can tell us about a function:

                       .-- syn::Ident (ident)
                       /
@@ -221,220 +221,220 @@ syn::token::Fn --'            /               \       (output)
 

Enough analysis, lets produce our first bit of Rust code.

Function Body

Recall that the body of a curried add should look like this:

-
return move |y| move |z| x + y + z;
+
return move |y| move |z| x + y + z;

And in general:

-
return move |arg2| move |arg3| ... |argN| <function body here>
+
return move |arg2| move |arg3| ... |argN| <function body here>

We already have the function’s body, provided by fn_body, in our generate_curry function. All that’s left to add is the move |arg2| move |arg3| ... stuff, for which we need to extract the argument identifiers (doc: Punctuated, FnArg, PatType):

-
// src/lib.rs
-use syn::punctuated::Punctuated;
-use syn::{parse_macro_input, FnArg, Pat, ItemFn, Block};
-
-fn extract_arg_idents(fn_args: Punctuated<FnArg, syn::token::Comma>) -> Vec<Box<Pat>> { 
-  return fn_args.into_iter().map(extract_arg_pat).collect::<Vec<_>>();
-}
+
// src/lib.rs
+use syn::punctuated::Punctuated;
+use syn::{parse_macro_input, FnArg, Pat, ItemFn, Block};
+
+fn extract_arg_idents(fn_args: Punctuated<FnArg, syn::token::Comma>) -> Vec<Box<Pat>> { 
+  return fn_args.into_iter().map(extract_arg_pat).collect::<Vec<_>>();
+}

Alright, so we are iterating over function args (Punctuated is a collection that you can iterate over) and mapping an extract_arg_pat to every item. What’s extract_arg_pat?

-
// src/lib.rs
-
-fn extract_arg_pat(a: FnArg) -> Box<Pat> {
-  match a {
-    FnArg::Typed(p) => p.pat,
-    _ => panic!("Not supported on types with `self`!"),
-  }
-}
+
// src/lib.rs
+
+fn extract_arg_pat(a: FnArg) -> Box<Pat> {
+  match a {
+    FnArg::Typed(p) => p.pat,
+    _ => panic!("Not supported on types with `self`!"),
+  }
+}

FnArg is an enum type as you might have guessed. The Typed variant encompasses args that are written as name: type and the other variant, Reciever refers to self types. Ignore those for now, keep it simple.

Every FnArg::Typed value contains a pat, which is in essence, the name of the argument. The type of the arg is accessible via p.ty (we will be using this later).

With that done, we should be able to write the codegen for the function body:

-
// src/lib.rs
-
-fn generate_body(fn_args: &[Box<Pat>], body: Box<Block>) -> proc_macro2::TokenStream {
-  quote! {
-    return #( move |#fn_args|  )* #body
-  }
-}
+
// src/lib.rs
+
+fn generate_body(fn_args: &[Box<Pat>], body: Box<Block>) -> proc_macro2::TokenStream {
+  quote! {
+    return #( move |#fn_args|  )* #body
+  }
+}

That is some scary looking syntax! Allow me to explain. The quote!{ ... } returns a proc_macro2::TokenStream, if we wrote quote!{ let x = 1 + 2; }, it wouldn’t create a new variable x with value 3, it would literally produce a stream of tokens with that expression.

The # enables variable interpolation. #body will look for body in the current scope, take its value, and insert it in the returned TokenStream. Kinda like quasi quoting in LISPs, you have written one.

What about #( move |#fn_args| )*? That is repetition. quote iterates through fn_args, and drops a move behind each one, it then places pipes (|), around it.

Let us test our first bit of codegen! Modify generate_curry like so:

-
// src/lib.rs
-
- fn generate_curry(parsed: ItemFn) -> TokenStream {
-   let fn_body = parsed.block;
-   let sig = parsed.sig;
-   let vis = parsed.vis;
-   let fn_name = sig.ident;
-   let fn_args = sig.inputs;
-   let fn_return_type = sig.output;
-
-+  let arg_idents = extract_arg_idents(fn_args.clone());
-+  let first_ident = &arg_idents.first().unwrap();
-
-+  // remember, our curried body starts with the second argument!
-+  let curried_body = generate_body(&arg_idents[1..], fn_body.clone());
-+  println!("{}", curried_body);
-
-   return TokenStream::new();
- }
+
// src/lib.rs
+
+ fn generate_curry(parsed: ItemFn) -> TokenStream {
+   let fn_body = parsed.block;
+   let sig = parsed.sig;
+   let vis = parsed.vis;
+   let fn_name = sig.ident;
+   let fn_args = sig.inputs;
+   let fn_return_type = sig.output;
+
++  let arg_idents = extract_arg_idents(fn_args.clone());
++  let first_ident = &arg_idents.first().unwrap();
+
++  // remember, our curried body starts with the second argument!
++  let curried_body = generate_body(&arg_idents[1..], fn_body.clone());
++  println!("{}", curried_body);
+
+   return TokenStream::new();
+ }

Add a little test to tests/:

-
// tests/smoke.rs
-
-#[currying::curry]
-fn add(x: u32, y: u32, z: u32) -> u32 {
-  x + y + z
-}
-
-#[test]
-fn works() {
-  assert!(true);
-}
+
// tests/smoke.rs
+
+#[currying::curry]
+fn add(x: u32, y: u32, z: u32) -> u32 {
+  x + y + z
+}
+
+#[test]
+fn works() {
+  assert!(true);
+}

You should find something like this in the output of cargo test:

return move | y | move | z | { x + y + z }

Glorious println! debugging!

Function signature

This section gets into the more complicated bits of the macro, generating type aliases and the function signature. By the end of this section, we should have a full working auto-currying macro!

Recall what our generated type aliases should look like, for our add function:

-
type T0 = u32;
-type T1 = impl Fn(u32) -> T0;
-type T2 = impl Fn(u32) -> T1;
+
type T0 = u32;
+type T1 = impl Fn(u32) -> T0;
+type T2 = impl Fn(u32) -> T1;

In general:

-
type T0 = <return type>;
-type T1 = impl Fn(<type of arg N>) -> T0;
-type T2 = impl Fn(<type of arg N - 1>) -> T1;
-.
-.
-.
-type T(N-1) = impl Fn(<type of arg 2>) -> T(N-2);
+
type T0 = <return type>;
+type T1 = impl Fn(<type of arg N>) -> T0;
+type T2 = impl Fn(<type of arg N - 1>) -> T1;
+.
+.
+.
+type T(N-1) = impl Fn(<type of arg 2>) -> T(N-2);

To codegen that, we need the types of:

  • all our inputs (arguments)
  • the output (the return type)

To fetch the types of all our inputs, we can simply reuse the bits we wrote to fetch the names of all our inputs! (doc: Type)

-
// src/lib.rs
-
-use syn::{parse_macro_input, Block, FnArg, ItemFn, Pat, ReturnType, Type};
-
-fn extract_type(a: FnArg) -> Box<Type> {
-  match a {
-    FnArg::Typed(p) => p.ty,  // notice `ty` instead of `pat`
-      _ => panic!("Not supported on types with `self`!"),
-  }
-}
-
-fn extract_arg_types(fn_args: Punctuated<FnArg, syn::token::Comma>) -> Vec<Box<Type>> {
-  return fn_args.into_iter().map(extract_type).collect::<Vec<_>>();
-
-}
+
// src/lib.rs
+
+use syn::{parse_macro_input, Block, FnArg, ItemFn, Pat, ReturnType, Type};
+
+fn extract_type(a: FnArg) -> Box<Type> {
+  match a {
+    FnArg::Typed(p) => p.ty,  // notice `ty` instead of `pat`
+      _ => panic!("Not supported on types with `self`!"),
+  }
+}
+
+fn extract_arg_types(fn_args: Punctuated<FnArg, syn::token::Comma>) -> Vec<Box<Type>> {
+  return fn_args.into_iter().map(extract_type).collect::<Vec<_>>();
+
+}

A good reader would have looked at the docs for output member of the syn::Signature struct. It has the type syn::ReturnType. So there is no extraction to do here right? There are actually a couple of things we have to ensure here:

  1. We need to ensure that the function returns! A function that does not return is pointless in this case, and I will tell you why, in the Notes section.

  2. A ReturnType encloses the arrow of the return as well, we need to get rid of that. Recall:

    -
    type T0 = u32
    -// and not
    -type T0 = -> u32
  3. +
    type T0 = u32
    +// and not
    +type T0 = -> u32

Here is the snippet that handles extraction of the return type (doc: syn::ReturnType):

-
// src/lib.rs
-
-fn extract_return_type(a: ReturnType) -> Box<Type> {
-  match a {
-    ReturnType::Type(_, p) => p,
-    _ => panic!("Not supported on functions without return types!"),
-  }
-}
+
// src/lib.rs
+
+fn extract_return_type(a: ReturnType) -> Box<Type> {
+  match a {
+    ReturnType::Type(_, p) => p,
+    _ => panic!("Not supported on functions without return types!"),
+  }
+}

You might notice that we are making extensive use of the panic! macro. Well, that is because it is a good idea to quit on receiving an unsatisfactory TokenStream.

With all our types ready, we can get on with generating type aliases:

-
// src/lib.rs
-
-use quote::{quote, format_ident};
-
-fn generate_type_aliases(
-  fn_arg_types: &[Box<Type>],
-  fn_return_type: Box<Type>,
-  fn_name: &syn::Ident,
-) -> Vec<proc_macro2::TokenStream> {    // 1
-
-  let type_t0 = format_ident!("_{}_T0", fn_name);    // 2
-  let mut type_aliases = vec![quote! { type #type_t0 = #fn_return_type  }];
-
-  // 3
-  for (i, t) in (1..).zip(fn_arg_types.into_iter().rev()) {
-    let p = format_ident!("_{}_{}", fn_name, format!("T{}", i - 1));
-    let n = format_ident!("_{}_{}", fn_name, format!("T{}", i));
-
-    type_aliases.push(quote! {
-        type #n = impl Fn(#t) -> #p
-    });
-  }
-
-  return type_aliases;
-}
+
// src/lib.rs
+
+use quote::{quote, format_ident};
+
+fn generate_type_aliases(
+  fn_arg_types: &[Box<Type>],
+  fn_return_type: Box<Type>,
+  fn_name: &syn::Ident,
+) -> Vec<proc_macro2::TokenStream> {    // 1
+
+  let type_t0 = format_ident!("_{}_T0", fn_name);    // 2
+  let mut type_aliases = vec![quote! { type #type_t0 = #fn_return_type  }];
+
+  // 3
+  for (i, t) in (1..).zip(fn_arg_types.into_iter().rev()) {
+    let p = format_ident!("_{}_{}", fn_name, format!("T{}", i - 1));
+    let n = format_ident!("_{}_{}", fn_name, format!("T{}", i));
+
+    type_aliases.push(quote! {
+        type #n = impl Fn(#t) -> #p
+    });
+  }
+
+  return type_aliases;
+}

1. The return value
We are returning a Vec<proc_macro2::TokenStream>, i. e., a list of TokenStreams, where each item is a type alias.

2. Format identifier?
I’ve got some explanation to do on this line. Clearly, we are trying to write the first type alias, and initialize our TokenStream vector with T0, because it is different from the others:

-
type T0 = something
-// the others are of the form
-type Tr = impl Fn(something) -> something
+
type T0 = something
+// the others are of the form
+type Tr = impl Fn(something) -> something

format_ident! is similar to format!. Instead of returning a formatted string, it returns a syn::Ident. Therefore, type_t0 is actually an identifier for, in the case of our add function, _add_T0. Why is this formatting important? Namespacing.

Picture this, we have two functions, add and subtract, that we wish to curry with our macro:

-
#[curry]
-fn add(...) -> u32 { ... }
-
-#[curry]
-fn sub(...) -> u32 { ... }
+
#[curry]
+fn add(...) -> u32 { ... }
+
+#[curry]
+fn sub(...) -> u32 { ... }

Here is the same but with macros expanded:

-
type T0 = u32;
-type T1 = impl Fn(u32) -> T0;
-fn add( ... ) -> T1 { ... }
-
-type T0 = u32;
-type T1 = impl Fn(u32) -> T0;
-fn sub( ... ) -> T1 { ... }
+
type T0 = u32;
+type T1 = impl Fn(u32) -> T0;
+fn add( ... ) -> T1 { ... }
+
+type T0 = u32;
+type T1 = impl Fn(u32) -> T0;
+fn sub( ... ) -> T1 { ... }

We end up with two definitions of T0! Now, if we do the little format_ident! dance we did up there:

-
type _add_T0 = u32;
-type _add_T1 = impl Fn(u32) -> _add_T0;
-fn add( ... ) -> _add_T1 { ... }
-
-type _sub_T0 = u32;
-type _sub_T1 = impl Fn(u32) -> _sub_T0;
-fn sub( ... ) -> _sub_T1 { ... }
+
type _add_T0 = u32;
+type _add_T1 = impl Fn(u32) -> _add_T0;
+fn add( ... ) -> _add_T1 { ... }
+
+type _sub_T0 = u32;
+type _sub_T1 = impl Fn(u32) -> _sub_T0;
+fn sub( ... ) -> _sub_T1 { ... }

Voilà! The type aliases don’t tread on each other. Remember to import format_ident from the quote crate.

3. The TokenStream Vector

We iterate over our types in reverse order (T0 is the last return, T1 is the second last, so on), assign a number to each iteration with zip, generate type names with format_ident, push a TokenStream with the help of quote and variable interpolation.

If you are wondering why we used (1..).zip() instead of .enumerate(), it’s because we wanted to start counting from 1 instead of 0 (we are already done with T0!).

Getting it together

I promised we’d have a fully working macro by the end of last section. I lied, we have to tie everything together in our generate_curry function:

-
// src/lib.rs
-
- fn generate_curry(parsed: ItemFn) -> proc_macro2::TokenStream {
-   let fn_body = parsed.block;
-   let sig = parsed.sig;
-   let vis = parsed.vis;
-   let fn_name = sig.ident;
-   let fn_args = sig.inputs;
-   let fn_return_type = sig.output;
-
-   let arg_idents = extract_arg_idents(fn_args.clone());
-   let first_ident = &arg_idents.first().unwrap();
-   let curried_body = generate_body(&arg_idents[1..], fn_body.clone());
-
-+  let arg_types = extract_arg_types(fn_args.clone());
-+  let first_type = &arg_types.first().unwrap();
-+  let type_aliases = generate_type_aliases(
-+      &arg_types[1..],
-+      extract_return_type(fn_return_type),
-+      &fn_name,
-+  );
-
-+  let return_type = format_ident!("_{}_{}", &fn_name, format!("T{}", type_aliases.len() - 1));
-
-+  return quote! {
-+      #(#type_aliases);* ;
-+      #vis fn #fn_name (#first_ident: #first_type) -> #return_type {
-+          #curried_body ;
-+      }
-+  };
- }
+
// src/lib.rs
+
+ fn generate_curry(parsed: ItemFn) -> proc_macro2::TokenStream {
+   let fn_body = parsed.block;
+   let sig = parsed.sig;
+   let vis = parsed.vis;
+   let fn_name = sig.ident;
+   let fn_args = sig.inputs;
+   let fn_return_type = sig.output;
+
+   let arg_idents = extract_arg_idents(fn_args.clone());
+   let first_ident = &arg_idents.first().unwrap();
+   let curried_body = generate_body(&arg_idents[1..], fn_body.clone());
+
++  let arg_types = extract_arg_types(fn_args.clone());
++  let first_type = &arg_types.first().unwrap();
++  let type_aliases = generate_type_aliases(
++      &arg_types[1..],
++      extract_return_type(fn_return_type),
++      &fn_name,
++  );
+
++  let return_type = format_ident!("_{}_{}", &fn_name, format!("T{}", type_aliases.len() - 1));
+
++  return quote! {
++      #(#type_aliases);* ;
++      #vis fn #fn_name (#first_ident: #first_type) -> #return_type {
++          #curried_body ;
++      }
++  };
+ }

Most of the additions are self explanatory, I’ll go through the return statement with you. We are returning a quote!{ ... }, so a proc_macro2::TokenStream. We are iterating through the type_aliases variable, which you might recall, is a Vec<TokenStream>. You might notice the sneaky semicolon before the *. This basically tells quote, to insert an item, then a semicolon, and then the next one, another semicolon, and so on. The semicolon is a separator. We need to manually insert another semicolon at the end of it all, quote doesn’t insert a separator at the end of the iteration.

We retain the visibility and name of our original function. Our curried function takes as args, just the first argument of our original function. The return type of our curried function is actually, the last type alias we create. If you think back to our manually curried add function, we returned T2, which was in fact, the last type alias we created.

I am sure, at this point, you are itching to test this out, but before that, let me introduce you to some good methods of debugging proc-macro code.

@@ -466,57 +466,57 @@ fn main() {

Writing proc-macros without cargo-expand is tantamount to driving a vehicle without rear view mirrors! Keep an eye on what is going on behind your back.

Now, your macro won’t always compile, you might just recieve the bee movie script as an error. cargo-expand will not work in such cases. I would suggest printing out your variables to inspect them. TokenStream implements Display as well as Debug. We don’t always have to be respectable programmers. Just print it.

Enough of that, lets get testing:

-
// tests/smoke.rs
-
-#![feature(type_alias_impl_trait)]
-
-#[crate_name::curry]
-fn add(x: u32, y: u32, z: u32) -> u32 {
-   x + y + z
-}
-
-#[test]
-fn works() {
-  assert_eq!(15, add(4)(5)(6));
-}
+
// tests/smoke.rs
+
+#![feature(type_alias_impl_trait)]
+
+#[crate_name::curry]
+fn add(x: u32, y: u32, z: u32) -> u32 {
+   x + y + z
+}
+
+#[test]
+fn works() {
+  assert_eq!(15, add(4)(5)(6));
+}

Run cargo +nightly test. You should see a pleasing message:

running 1 test
 test tests::works ... ok

Take a look at the expansion for our curry macro, via cargo +nightly expand --tests smoke:

-
type _add_T0 = u32;
-type _add_T1 = impl Fn(u32) -> _add_T0;
-type _add_T2 = impl Fn(u32) -> _add_T1;
-fn add(x: u32) -> _add_T2 {
-  return (move |y| {
-    move |z| {
-      return x + y + z;
-    }
-  });
-}
-
-// a bunch of other stuff generated by #[test] and assert_eq!
+
type _add_T0 = u32;
+type _add_T1 = impl Fn(u32) -> _add_T0;
+type _add_T2 = impl Fn(u32) -> _add_T1;
+fn add(x: u32) -> _add_T2 {
+  return (move |y| {
+    move |z| {
+      return x + y + z;
+    }
+  });
+}
+
+// a bunch of other stuff generated by #[test] and assert_eq!

A sight for sore eyes.

Here is a more complex example that generates ten multiples of the first ten natural numbers:

-
#[curry]
-fn product(x: u32, y: u32) -> u32 {
-  x * y
-}
-
-fn multiples() -> Vec<Vec<u32>>{
-  let v = (1..=10).map(product);
-  return (1..=10)
-      .map(|x| v.clone().map(|f| f(x)).collect())
-      .collect();
-}
+
#[curry]
+fn product(x: u32, y: u32) -> u32 {
+  x * y
+}
+
+fn multiples() -> Vec<Vec<u32>>{
+  let v = (1..=10).map(product);
+  return (1..=10)
+      .map(|x| v.clone().map(|f| f(x)).collect())
+      .collect();
+}

Notes

I didn’t quite explain why we use move |arg| in our closure. This is because we want to take ownership of the variable supplied to us. Take a look at this example:

-
let v = add(5);
-let g;
-{
-  let x = 5;
-  g = v(x);
-}
-println!("{}", g(2));
+
let v = add(5);
+let g;
+{
+  let x = 5;
+  g = v(x);
+}
+println!("{}", g(2));

Variable x goes out of scope before g can return a concrete value. If we take ownership of x by moveing it into our closure, we can expect this to work reliably. In fact, rustc understands this, and forces you to use move.

This usage of move is exactly why a curried function without a return is useless. Every variable we pass to our curried function gets moved into its local scope. Playing with these variables cannot cause a change outside this scope. Returning is our only method of interaction with anything beyond this function.

Conclusion

diff --git a/docs/posts/gripes_with_go/index.html b/docs/posts/gripes_with_go/index.html index e1c3b33..1551fe6 100644 --- a/docs/posts/gripes_with_go/index.html +++ b/docs/posts/gripes_with_go/index.html @@ -54,101 +54,101 @@

Lack of Sum types

A “Sum” type is a data type that can hold one of many states at a given time, similar to how a boolean can hold a true or a false, not too different from an enum type in C. Go lacks enum types unfortunately, and you are forced to resort to crafting your own substitute.

A type to represent gender for example:

-
type Gender int
-
-const (
-    Male Gender = iota  // assigns Male to 0
-    Female              // assigns Female to 1
-    Other               // assigns Other to 2
-)
-
-fmt.Println("My gender is ", Male)
-// My gender is 0
-// Oops! We have to implement String() for Gender ...
-
-func (g Gender) String() string {
-    switch (g) {
-    case 0: return "Male"
-    case 1: return "Female"
-    default: return "Other"
-    }
-}
-
-// You can accidentally do stupid stuff like:
-gender := Male + 1
+
type Gender int
+
+const (
+    Male Gender = iota  // assigns Male to 0
+    Female              // assigns Female to 1
+    Other               // assigns Other to 2
+)
+
+fmt.Println("My gender is ", Male)
+// My gender is 0
+// Oops! We have to implement String() for Gender ...
+
+func (g Gender) String() string {
+    switch (g) {
+    case 0: return "Male"
+    case 1: return "Female"
+    default: return "Other"
+    }
+}
+
+// You can accidentally do stupid stuff like:
+gender := Male + 1

The Haskell equivalent of the same:

-
data Gender = Male
-            | Female
-            | Other
-            deriving (Show)
-
-print $ "My gender is " ++ (show Male)
+
data Gender = Male
+            | Female
+            | Other
+            deriving (Show)
+
+print $ "My gender is " ++ (show Male)

Type Assertions

A downcast with an optional error check? What could go wrong?

Type assertions in Go allow you to do:

-
var x interface{} = 7
-y, goodToGo := x.(int)
-if goodToGo {
-    fmt.Println(y)
-}
+
var x interface{} = 7
+y, goodToGo := x.(int)
+if goodToGo {
+    fmt.Println(y)
+}

The error check however is optional:

-
var x interface{} = 7
-var y := x.(float64)
-fmt.Println(y)
-// results in a runtime error:
-// panic: interface conversion: interface {} is int, not float64
+
var x interface{} = 7
+var y := x.(float64)
+fmt.Println(y)
+// results in a runtime error:
+// panic: interface conversion: interface {} is int, not float64

Date and Time

Anyone that has written Go previously, will probably already know what I am getting at here. For the uninitiated, parsing and formatting dates in Go requires a “layout”. This “layout” is based on magical reference date:

Mon Jan 2 15:04:05 MST 2006

Which is the date produced when you write the first seven natural numbers like so:

01/02 03:04:05 '06 -0700

Parsing a string in YYYY-MM-DD format would look something like:

-
const layout = "2006-01-02"
-time.Parse(layout, "2020-08-01")
+
const layout = "2006-01-02"
+time.Parse(layout, "2020-08-01")

This so-called “intuitive” method of formatting dates doesn’t allow you to print 0000 hrs as 2400 hrs, it doesn’t allow you to omit the leading zero in 24 hour formats. It is rife with inconveniences, if only there were a tried and tested date formatting convention …

Statements over Expressions

Statements have side effects, expressions return values. More often than not, expressions are easier to understand at a glance: evaluate the LHS and assign the same to the RHS.

Rust allows you to create local namespaces, and treats blocks ({}) as expressions:

-
let twenty_seven = {
-    let three = 1 + 2;
-    let nine = three * three;
-    nine * three
-};
+
let twenty_seven = {
+    let three = 1 + 2;
+    let nine = three * three;
+    nine * three
+};

The Go equivalent of the same:

-
twenty_seven := nil
-
-three := 1 + 2
-nine := three * three
-twenty_seven = nine * three
+
twenty_seven := nil
+
+three := 1 + 2
+nine := three * three
+twenty_seven = nine * three

Erroring out on unused variables

Want to quickly prototype something? Go says no! In all seriousness, a warning would suffice, I don’t want to have to go back and comment each unused import out, only to come back and uncomment them a few seconds later.

Error handling

-
if err != nil { ... }
+
if err != nil { ... }

Need I say more? I will, for good measure:

  1. Error handling is optional
  2. Errors are propagated via a clunky if + return statement

I prefer Haskell’s “Monadic” error handling, which is employed by Rust as well:

-
// 1. error handling is compulsory
-// 2. errors are propagated with the `?` operator
-fn foo() -> Result<String, io::Error> {
-    let mut f = File::open("foo.txt")?; // return if error
-    let mut s = String::new();
-
-    f.read_to_string(&mut s)?; // return if error
-
-    Ok(s) // all good, return a string inside a `Result` context
-}
-
-fn main() {
-    // `contents` is an enum known as Result:
-    let contents = foo();
-    match contents {
-        Ok(c) => println!(c),
-        Err(e) => eprintln!(e)
-    }
-}
+
// 1. error handling is compulsory
+// 2. errors are propagated with the `?` operator
+fn foo() -> Result<String, io::Error> {
+    let mut f = File::open("foo.txt")?; // return if error
+    let mut s = String::new();
+
+    f.read_to_string(&mut s)?; // return if error
+
+    Ok(s) // all good, return a string inside a `Result` context
+}
+
+fn main() {
+    // `contents` is an enum known as Result:
+    let contents = foo();
+    match contents {
+        Ok(c) => println!(c),
+        Err(e) => eprintln!(e)
+    }
+}

Conclusion

I did not want to conclude without talking about stylistic choices, lack of metaprogramming, bizzare export rules, but, I am too busy converting my interface{} types into actual generic code for Go v2.

diff --git a/docs/posts/nixOS/index.html b/docs/posts/nixOS/index.html index 3e012f8..75be58f 100644 --- a/docs/posts/nixOS/index.html +++ b/docs/posts/nixOS/index.html @@ -58,10 +58,10 @@

Builds may be generated by specifying a default.nix file, and running nix-build. Conventional package managers require you to specify a dependency list, but there is no guarantee that this list is complete. The package will build on your machine even if you forget a dependency. However, with Nix, packages are installed to /nix/store, and not global paths such as /usr/bin/..., if your project builds, it means you have included every last one.

Issues on most my projects have been “unable to build because libxcb is missing”, or “this version of openssl is too old”. Tools like cargo and pip are poor package managers. While they can guarantee that Rust or Python dependencies are met, they make assumptions about the target system.

For example, this website is now built using Nix, anyone using Nix may simply, clone the repository and run ./generate.sh, and it would just work, while keeping your global namespace clean™:

-
#! /usr/bin/env nix-shell
-#! nix-shell -i bash -p eva pandoc esh
-
-# some bash magic ;)
+
#! /usr/bin/env nix-shell
+#! nix-shell -i bash -p eva pandoc esh
+
+# some bash magic ;)

Dependencies are included with the -p flag, the shell script is executed with an interpreter, specified with the -i flag.

Impressions

NixOS is by no means, simple. As a newcomer, using Nix was not easy, heck, I had to learn a purely functional, lazy language to just build programs. There is a lot to be desired on the tooling front as well. A well fleshed out LSP plugin would be nice (rnix-lsp looks promising).

diff --git a/docs/posts/rapid_refactoring_with_vim/index.html b/docs/posts/rapid_refactoring_with_vim/index.html index b4081c4..3d867a3 100644 --- a/docs/posts/rapid_refactoring_with_vim/index.html +++ b/docs/posts/rapid_refactoring_with_vim/index.html @@ -44,34 +44,34 @@

Last weekend, I was tasked with refactoring the 96 unit tests on ruma-events to use strictly typed json objects using serde_json::json! instead of raw strings. It was rather painless thanks to vim :)

Here’s a small sample of what had to be done (note the lines prefixed with the arrow):

-
use serde_json::{from_str};
-  
-  #[test]
-  fn deserialize() {
-    assert_eq!(
-from_str::<Action>(r#"{"set_tweak": "highlight"}"#),
-        Action::SetTweak(Tweak::Highlight { value: true })
-        );
-  }
+
use serde_json::{from_str};
+  
+  #[test]
+  fn deserialize() {
+    assert_eq!(
+from_str::<Action>(r#"{"set_tweak": "highlight"}"#),
+        Action::SetTweak(Tweak::Highlight { value: true })
+        );
+  }

had to be converted to:

-
use serde_json::{from_value};
-  
-  #[test]
-  fn deserialize() {
-    assert_eq!(
-from_value::<Action>(json!({"set_tweak": "highlight"})),
-        Action::SetTweak(Tweak::Highlight { value: true })
-        );
-  }
+
use serde_json::{from_value};
+  
+  #[test]
+  fn deserialize() {
+    assert_eq!(
+from_value::<Action>(json!({"set_tweak": "highlight"})),
+        Action::SetTweak(Tweak::Highlight { value: true })
+        );
+  }

The arglist

For the initial pass, I decided to handle imports, this was a simple find and replace operation, done to all the files containing tests. Luckily, modules (and therefore files) containing tests in Rust are annotated with the #[cfg(test)] attribute. I opened all such files:

-
# `grep -l pattern files` lists all the files
-#  matching the pattern
-
-vim $(grep -l 'cfg\(test\)' ./**/*.rs)
-
-# expands to something like:
-vim push_rules.rs room/member.rs key/verification/lib.rs
+
# `grep -l pattern files` lists all the files
+#  matching the pattern
+
+vim $(grep -l 'cfg\(test\)' ./**/*.rs)
+
+# expands to something like:
+vim push_rules.rs room/member.rs key/verification/lib.rs

Starting vim with more than one file at the shell prompt populates the arglist. Hit :args to see the list of files currently ready to edit. The square [brackets] indicate the current file. Navigate through the arglist with :next and :prev. I use tpope’s vim-unimpaired 1, which adds ]a and [a, mapped to :next and :prev.

All that’s left to do is the find and replace, for which we will be using vim’s argdo, applying a substitution to every file in the arglist:

:argdo s/from_str/from_value/g
diff --git a/docs/posts/self-hosting_git/index.html b/docs/posts/self-hosting_git/index.html index 618688f..f41a591 100644 --- a/docs/posts/self-hosting_git/index.html +++ b/docs/posts/self-hosting_git/index.html @@ -47,19 +47,19 @@

cgit is very bare bones. It is cgi-based web interface to git, and nothing more. You may browse repositories, view diffs, commit logs and even clone via http. If you are looking to replace Github with cgit, keep in mind that cgit does not handle issues or pull/merge requests. If people wish to contribute to your work, they would have to send you a patch via email.

Setup

Installing cgit is fairly straightforward, if you would like to compile it from source:

-
# fetch
-git clone https://git.zx2c4.com && cd cgit
-git submodule init
-git submodule update
-
-# install
-make NO_LUA=1
-sudo make install
+
# fetch
+git clone https://git.zx2c4.com && cd cgit
+git submodule init
+git submodule update
+
+# install
+make NO_LUA=1
+sudo make install

This would drop the cgit cgi script (and the default css) into /var/www/htdocs/cgit. You may configure cgit by editing /etc/cgitrc. I specify the NO_LUA flag to compile without lua support, exclude that flag if you would like to extend cgit via lua scripts.

Going live

You might want to use, fcgiwrap, a fastcgi wrapper for cgi scripts,

-
sudo apt install fcgiwrap
-sudo systemctl start fcgiwrap.socket
+
sudo apt install fcgiwrap
+sudo systemctl start fcgiwrap.socket

Expose the cgit cgi script to the web via nginx:

# nginx.conf
 server {
diff --git a/docs/posts/static_sites_with_bash/index.html b/docs/posts/static_sites_with_bash/index.html
index 3db192b..07313be 100644
--- a/docs/posts/static_sites_with_bash/index.html
+++ b/docs/posts/static_sites_with_bash/index.html
@@ -47,26 +47,26 @@
 

I chose to write in markdown, and convert to html with lowdown.

Directory structure

I host my site on GitHub pages, so docs/ has to be the entry point. Markdown formatted posts go into posts/, get converted into html, and end up in docs/index.html, something like this:

-
posts=$(ls -t ./posts)     # chronological order!
-for f in $posts; do
-    file="./posts/"$f      # `ls` mangled our file paths
-    echo "generating post $file"
-
-    html=$(lowdown "$file")
-    echo -e "html" >> docs/index.html
-done
+
posts=$(ls -t ./posts)     # chronological order!
+for f in $posts; do
+    file="./posts/"$f      # `ls` mangled our file paths
+    echo "generating post $file"
+
+    html=$(lowdown "$file")
+    echo -e "html" >> docs/index.html
+done

Assets

Most static site generators recommend dropping image assets into the site source itself. That does have it’s merits, but I prefer hosting images separately:

-
# strip file extension
-ext="${1##*.}"
-
-# generate a random file name
-id=$( cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 2 | head -n 1 )
-id="$id.$ext"
-
-# copy to my file host
-scp -P 443 "$1" emerald:files/"$id" 
-echo "https://u.peppe.rs/$id"
+
# strip file extension
+ext="${1##*.}"
+
+# generate a random file name
+id=$( cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 2 | head -n 1 )
+id="$id.$ext"
+
+# copy to my file host
+scp -P 443 "$1" emerald:files/"$id" 
+echo "https://u.peppe.rs/$id"

Templating

generate.sh brings the above bits and pieces together (with some extra cruft to avoid javascript). It uses sed to produce nice titles from the file names (removes underscores, title-case), and date(1) to add the date to each post listing!

-- cgit v1.2.3