From 366df8852f503523cc4f9046d82ba9a99dd51d7f Mon Sep 17 00:00:00 2001 From: Akshay Date: Sun, 12 Feb 2023 12:13:49 +0530 Subject: new art: lapse --- art/lapse.png | Bin 0 -> 3756 bytes docs/art/index.html | 37 +- docs/art/lapse.png | Bin 0 -> 3756 bytes docs/index.html | 12 +- docs/index.xml | 2384 +++++++++++++++----- docs/posts/SDL2_devlog/index.html | 240 +- docs/posts/WPA_woes/index.html | 13 +- .../posts/a_reference_counted_afterlife/index.html | 40 +- docs/posts/auto-currying_rust_functions/index.html | 496 ++-- docs/posts/bash_harder_with_vim/index.html | 22 +- docs/posts/bye_bye_BDFs/index.html | 28 +- docs/posts/call_to_ARMs/index.html | 49 +- docs/posts/color_conundrum/index.html | 36 +- docs/posts/curing_a_case_of_git-UX/index.html | 180 +- docs/posts/font_size_fallacies/index.html | 79 +- .../index.html | 5 +- docs/posts/gripes_with_go/index.html | 85 +- docs/posts/hold_position!/index.html | 20 +- docs/posts/index.html | 14 +- docs/posts/lightweight_linting/index.html | 212 +- docs/posts/lotus58/index.html | 83 +- docs/posts/my_setup/index.html | 25 +- docs/posts/nixOS/index.html | 74 +- docs/posts/novice_nix:_flake_templates/index.html | 171 +- docs/posts/onivim_sucks/index.html | 39 +- docs/posts/pixel_art_in_GIMP/index.html | 101 +- docs/posts/programming_on_34_keys/index.html | 157 +- docs/posts/rapid_refactoring_with_vim/index.html | 119 +- docs/posts/self-hosting_git/index.html | 67 +- docs/posts/static_sites_with_bash/index.html | 36 +- docs/posts/termux_tandem/index.html | 29 +- docs/posts/turing_complete_type_systems/index.html | 24 +- 32 files changed, 3632 insertions(+), 1245 deletions(-) create mode 100644 art/lapse.png create mode 100644 docs/art/lapse.png diff --git a/art/lapse.png b/art/lapse.png new file mode 100644 index 0000000..52b7721 Binary files /dev/null and b/art/lapse.png differ diff --git a/docs/art/index.html b/docs/art/index.html index 88c6cce..e3dee61 100644 --- a/docs/art/index.html +++ b/docs/art/index.html @@ -21,7 +21,18 @@

Art

- + +
+ +
+
+
Lapse
+
12/02 — 2023
+
+
+
+
+
@@ -43,23 +54,23 @@
- +
- +
-
The Sect
+
Ivory Tower
03/06 — 2022
- +
- +
-
Ivory Tower
+
The Sect
03/06 — 2022
@@ -241,23 +252,23 @@
- +
- +
-
Beret Beaver
+
Aviator Owl
01/05 — 2021
- +
- +
-
Aviator Owl
+
Beret Beaver
01/05 — 2021
diff --git a/docs/art/lapse.png b/docs/art/lapse.png new file mode 100644 index 0000000..52b7721 Binary files /dev/null and b/docs/art/lapse.png differ diff --git a/docs/index.html b/docs/index.html index b3d6de9..9c74671 100644 --- a/docs/index.html +++ b/docs/index.html @@ -50,7 +50,7 @@ - 9.5 + 9.6 min @@ -78,15 +78,15 @@
- 29/08 — 2022 + 12/02 — 2023
-
- Ferris + + Lapse - - + + diff --git a/docs/index.xml b/docs/index.xml index 5586abd..c0277f1 100644 --- a/docs/index.xml +++ b/docs/index.xml @@ -13,51 +13,86 @@ Creative Commons BY-NC-SA 4.0 Curing A Case Of Git-UX -<p>Git worktrees are great, but they fall behind the venerable <code>git checkout</code> sometimes. I attempted to fix that with <a href="https://github.com/junegunn/fzf">fzf</a> and a bit of bash.</p> -<p><a href="https://asciinema.org/a/D297ztKRzpE4gAHbPTPmkqYps"><img src="https://asciinema.org/a/D297ztKRzpE4gAHbPTPmkqYps.svg" /></a></p> -<p>Fear not if you haven’t heard of “worktrees”, I have included a primer here.<br /> +<p>Git worktrees are great, but they fall behind the venerable +<code>git checkout</code> sometimes. I attempted to fix that with <a +href="https://github.com/junegunn/fzf">fzf</a> and a bit of bash.</p> +<p><a href="https://asciinema.org/a/D297ztKRzpE4gAHbPTPmkqYps"><img +src="https://asciinema.org/a/D297ztKRzpE4gAHbPTPmkqYps.svg" /></a></p> +<p>Fear not if you haven’t heard of “worktrees”, I have included a +primer here.<br /> <a href="#what-makes-them-clunky">Skip the primer -&gt;</a>.</p> <h3 id="why-worktrees">Why Worktrees?</h3> -<p>Picture this. You are whacking away on a feature branch. Halfway there, in fact. Your friend asks you fix something urgently. You proceed to do one of three things:</p> +<p>Picture this. You are whacking away on a feature branch. Halfway +there, in fact. Your friend asks you fix something urgently. You proceed +to do one of three things:</p> <ul> -<li>create a temporary branch, make a WIP commit, begin working on the fix</li> +<li>create a temporary branch, make a WIP commit, begin working on the +fix</li> <li>stash away your changes, begin working on the fix</li> <li>unfriend said friend for disturbing your flow</li> </ul> -<p>All of these options are … subpar. With the temporary branch, you are forced to create a partial, non-working commit, and then reset said commit once done with the fix. With the stash approach, you are required to now keep a mental model of the stash, be aware of untracked files that don’t get stashed by default, etc. Why won’t git just let you work on two things at the same time without <em>thinking</em> so much?</p> -<p>That is exactly what worktrees let you do. Worktrees let you have more than one checkout at a time, each checkout in a separate directory. Like creating a new clone, but safer (it disallows checking out the same branch twice) and a lot more space efficient (the new working tree is “linked” to the “main” worktree, and a good amount of stuff is shared). When your friend asks you to make the fix, you proceed like so:</p> +<p>All of these options are … subpar. With the temporary branch, you are +forced to create a partial, non-working commit, and then reset said +commit once done with the fix. With the stash approach, you are required +to now keep a mental model of the stash, be aware of untracked files +that don’t get stashed by default, etc. Why won’t git just let you work +on two things at the same time without <em>thinking</em> so much?</p> +<p>That is exactly what worktrees let you do. Worktrees let you have +more than one checkout at a time, each checkout in a separate directory. +Like creating a new clone, but safer (it disallows checking out the same +branch twice) and a lot more space efficient (the new working tree is +“linked” to the “main” worktree, and a good amount of stuff is shared). +When your friend asks you to make the fix, you proceed like so:</p> <ol type="1"> <li>Create a new working tree with:</li> </ol> -<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="co"># git worktree add -b &lt;branch-name&gt; &lt;path&gt; &lt;from&gt;</span></span> +<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="co"># git worktree add -b &lt;branch-name&gt; &lt;path&gt; &lt;from&gt;</span></span> <span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a><span class="fu">git</span> worktree add <span class="at">-b</span> fix-stuff /path/to/tree master</span></code></pre></div> <ol start="2" type="1"> <li><code>cd</code> into <code>/path/to/tree</code></li> <li>Fix, test, commit, push, party</li> <li>Go back to your work, <code>cd -</code></li> </ol> -<p>Easy as cake. You didn’t have to settle for a partially working commit, you didn’t to deal with this “stash” thing, <em>and</em> you didn’t have to unfriend your friend. Treating each branch as a directory just <em>feels</em> more intuitive, more UNIX-y.</p> -<p>A few weeks later, you find yourself singing in praise of worktrees, working on several things simultaneously. And at the same time, cursing them for being a little … clunky.</p> +<p>Easy as cake. You didn’t have to settle for a partially working +commit, you didn’t to deal with this “stash” thing, <em>and</em> you +didn’t have to unfriend your friend. Treating each branch as a directory +just <em>feels</em> more intuitive, more UNIX-y.</p> +<p>A few weeks later, you find yourself singing in praise of worktrees, +working on several things simultaneously. And at the same time, cursing +them for being a little … clunky.</p> <h3 id="what-makes-them-clunky">What makes them clunky?</h3> -<p>Worktrees are great at what they claim to do. They stay out of the way when you need a checkout posthaste. However, as you start using them regularly, you realize they are not as flexible as <code>git checkout</code> or <code>git switch</code>.</p> +<p>Worktrees are great at what they claim to do. They stay out of the +way when you need a checkout posthaste. However, as you start using them +regularly, you realize they are not as flexible as +<code>git checkout</code> or <code>git switch</code>.</p> <h4 id="branch-hopping">Branch-hopping</h4> -<p>You can <code>git checkout &lt;branch&gt;</code> from anywhere within a git repository. You can’t “jump” to a worktree in the same fashion. The closest you can get, is to run <code>git worktree list</code>, copy the path corresponding to your branch, and <code>cd</code> into it.</p> +<p>You can <code>git checkout &lt;branch&gt;</code> from anywhere within +a git repository. You can’t “jump” to a worktree in the same fashion. +The closest you can get, is to run <code>git worktree list</code>, copy +the path corresponding to your branch, and <code>cd</code> into it.</p> <p>Branch-hopping with the good ol’ git-checkout:</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" tabindex="-1"></a><span class="co"># anywhere, anytime</span></span> +<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"># anywhere, anytime</span></span> <span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a><span class="ex">λ</span> git checkout feature/is-ascii-octdigit</span></code></pre></div> <p>Meanwhile, in worktree world:</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" tabindex="-1"></a><span class="co"># keeping these paths in your head is hard</span></span> +<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"># keeping these paths in your head is hard</span></span> <span id="cb3-2"><a href="#cb3-2" aria-hidden="true" tabindex="-1"></a><span class="ex">λ</span> git worktree list</span> -<span id="cb3-3"><a href="#cb3-3" aria-hidden="true" tabindex="-1"></a><span class="ex">~/worktrees/rustc/master</span> eac6c33bc63 [master]</span> -<span id="cb3-4"><a href="#cb3-4" aria-hidden="true" tabindex="-1"></a><span class="ex">~/worktrees/rustc/improve-std-char-docs</span> 94cba88553e [improve-std-char-docs]</span> -<span id="cb3-5"><a href="#cb3-5" aria-hidden="true" tabindex="-1"></a><span class="ex">~/worktrees/rustc/is-ascii-octdigit</span> bc57be3af7a [feature/is-ascii-octdigit]</span> -<span id="cb3-6"><a href="#cb3-6" aria-hidden="true" tabindex="-1"></a><span class="ex">~/my/other/path/oh/god</span> op57or3ns7n [fix/some-error]</span> +<span id="cb3-3"><a href="#cb3-3" aria-hidden="true" tabindex="-1"></a><span class="ex">~/worktrees/rustc/master</span> eac6c33bc63 <span class="pp">[</span><span class="ss">master</span><span class="pp">]</span></span> +<span id="cb3-4"><a href="#cb3-4" aria-hidden="true" tabindex="-1"></a><span class="ex">~/worktrees/rustc/improve-std-char-docs</span> 94cba88553e <span class="pp">[</span><span class="ss">improve</span><span class="pp">-</span><span class="ss">std</span><span class="pp">-</span><span class="ss">char</span><span class="pp">-</span><span class="ss">docs</span><span class="pp">]</span></span> +<span id="cb3-5"><a href="#cb3-5" aria-hidden="true" tabindex="-1"></a><span class="ex">~/worktrees/rustc/is-ascii-octdigit</span> bc57be3af7a <span class="pp">[</span><span class="ss">feature/is</span><span class="pp">-</span><span class="ss">ascii</span><span class="pp">-</span><span class="ss">octdigit</span><span class="pp">]</span></span> +<span id="cb3-6"><a href="#cb3-6" aria-hidden="true" tabindex="-1"></a><span class="ex">~/my/other/path/oh/god</span> op57or3ns7n <span class="pp">[</span><span class="ss">fix/some</span><span class="pp">-</span><span class="ss">error</span><span class="pp">]</span></span> <span id="cb3-7"><a href="#cb3-7" aria-hidden="true" tabindex="-1"></a></span> <span id="cb3-8"><a href="#cb3-8" aria-hidden="true" tabindex="-1"></a><span class="ex">λ</span> cd ~/worktrees/rustc/is-ascii-octdigit</span></code></pre></div> <h4 id="branch-previewing">Branch-previewing</h4> -<p>You can “preview” branches with <code>git branch -v</code>. However, to get an idea of what “recent activity” on a worktree looks like, you might need some juggling. You can’t glean much info about a worktree in a jiffy.</p> +<p>You can “preview” branches with <code>git branch -v</code>. However, +to get an idea of what “recent activity” on a worktree looks like, you +might need some juggling. You can’t glean much info about a worktree in +a jiffy.</p> <p>Branch-previewing with the good ol’ git-branch:</p> -<div class="sourceCode" id="cb4"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a><span class="ex">λ</span> git branch <span class="at">-v</span></span> +<div class="sourceCode" id="cb4"><pre +class="sourceCode bash"><code class="sourceCode bash"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a><span class="ex">λ</span> git branch <span class="at">-v</span></span> <span id="cb4-2"><a href="#cb4-2" aria-hidden="true" tabindex="-1"></a><span class="ex">+</span> feature/is-ascii-octdigit bc57be3af7a introduce {char, u8}::is_ ...</span> <span id="cb4-3"><a href="#cb4-3" aria-hidden="true" tabindex="-1"></a><span class="ex">+</span> improve-std-char-docs 94cba88553e add whitespace in assert ...</span> <span id="cb4-4"><a href="#cb4-4" aria-hidden="true" tabindex="-1"></a><span class="ex">*</span> master eac6c33bc63 Auto merge of <span class="co">#100869 - n ...</span></span></code></pre></div> @@ -76,41 +111,60 @@ aa857eb953e Auto merge of #100537 - petrochenkov:pic ... # extra work to make the branch &lt;-&gt; worktree correspondence</code></pre> <h4 id="shell-completions">Shell completions</h4> -<p>Lastly, you can bank on shell completions to fill in your branch whilst using <code>git checkout</code>. Worktrees have no such conveniences.</p> +<p>Lastly, you can bank on shell completions to fill in your branch +whilst using <code>git checkout</code>. Worktrees have no such +conveniences.</p> <p>We can mend these minor faults with fzf.</p> <h3 id="unclunkifying-worktrees">Unclunkifying worktrees</h3> -<p>I’d suggest looking up <a href="https://github.com/junegunn/fzf">fzf</a> (or <a href="https://github.com/lotabout/skim">skim</a> or <a href="https://github.com/jhawthorn/fzy">fzy</a>). These things make it cake-easy to add interactivity to your shell. Onto fixing the first minor fault, the inability to “jump” to a worktree from anywhere within a git repository.</p> -<p>I have a little function called <code>gwj</code> which stands for “git worktree jump”. The idea is to list all the worktrees, select one with fzf, and <code>cd</code> to it upon selection:</p> -<div class="sourceCode" id="cb6"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true" tabindex="-1"></a><span class="fu">gwj ()</span> <span class="kw">{</span></span> +<p>I’d suggest looking up <a +href="https://github.com/junegunn/fzf">fzf</a> (or <a +href="https://github.com/lotabout/skim">skim</a> or <a +href="https://github.com/jhawthorn/fzy">fzy</a>). These things make it +cake-easy to add interactivity to your shell. Onto fixing the first +minor fault, the inability to “jump” to a worktree from anywhere within +a git repository.</p> +<p>I have a little function called <code>gwj</code> which stands for +“git worktree jump”. The idea is to list all the worktrees, select one +with fzf, and <code>cd</code> to it upon selection:</p> +<div class="sourceCode" id="cb6"><pre +class="sourceCode bash"><code class="sourceCode bash"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true" tabindex="-1"></a><span class="fu">gwj ()</span> <span class="kw">{</span></span> <span id="cb6-2"><a href="#cb6-2" aria-hidden="true" tabindex="-1"></a> <span class="bu">local</span> <span class="va">out</span></span> <span id="cb6-3"><a href="#cb6-3" aria-hidden="true" tabindex="-1"></a> <span class="va">out</span><span class="op">=</span><span class="va">$(</span><span class="fu">git</span> worktree list <span class="kw">|</span> <span class="ex">fzf</span> <span class="kw">|</span> <span class="fu">awk</span> <span class="st">&#39;{print $1}&#39;</span><span class="va">)</span></span> <span id="cb6-4"><a href="#cb6-4" aria-hidden="true" tabindex="-1"></a> <span class="bu">cd</span> <span class="va">$out</span></span> <span id="cb6-5"><a href="#cb6-5" aria-hidden="true" tabindex="-1"></a><span class="kw">}</span></span></code></pre></div> <p>That is all of it really. Head into a git repository:</p> -<div class="sourceCode" id="cb7"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb7-1"><a href="#cb7-1" aria-hidden="true" tabindex="-1"></a><span class="co"># here, &quot;master&quot; is a directory, which contains my main</span></span> +<div class="sourceCode" id="cb7"><pre +class="sourceCode bash"><code class="sourceCode bash"><span id="cb7-1"><a href="#cb7-1" aria-hidden="true" tabindex="-1"></a><span class="co"># here, &quot;master&quot; is a directory, which contains my main</span></span> <span id="cb7-2"><a href="#cb7-2" aria-hidden="true" tabindex="-1"></a><span class="co"># worktree: a checkout of the master branch on rust-lang/rust </span></span> <span id="cb7-3"><a href="#cb7-3" aria-hidden="true" tabindex="-1"></a><span class="ex">λ</span> cd ~/worktrees/rustc/master/library/core/src</span> <span id="cb7-4"><a href="#cb7-4" aria-hidden="true" tabindex="-1"></a><span class="ex">λ</span> <span class="co"># hack away</span></span></code></pre></div> <p>Preferably one with a few worktrees:</p> -<div class="sourceCode" id="cb8"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true" tabindex="-1"></a><span class="ex">λ</span> git worktree list</span> -<span id="cb8-2"><a href="#cb8-2" aria-hidden="true" tabindex="-1"></a><span class="ex">~/worktrees/rustc/master</span> eac6c33bc63 [master]</span> -<span id="cb8-3"><a href="#cb8-3" aria-hidden="true" tabindex="-1"></a><span class="ex">~/worktrees/rustc/improve-std-char-docs</span> 94cba88553e [improve-std-char-docs]</span> -<span id="cb8-4"><a href="#cb8-4" aria-hidden="true" tabindex="-1"></a><span class="ex">~/worktrees/rustc/is-ascii-octdigit</span> bc57be3af7a [feature/is-ascii-octdigit]</span></code></pre></div> -<p>And hit <code>gwj</code> (pretend that the pipe, |, is your cursor):</p> -<div class="sourceCode" id="cb9"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb9-1"><a href="#cb9-1" aria-hidden="true" tabindex="-1"></a><span class="ex">λ</span> gwj</span> +<div class="sourceCode" id="cb8"><pre +class="sourceCode bash"><code class="sourceCode bash"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true" tabindex="-1"></a><span class="ex">λ</span> git worktree list</span> +<span id="cb8-2"><a href="#cb8-2" aria-hidden="true" tabindex="-1"></a><span class="ex">~/worktrees/rustc/master</span> eac6c33bc63 <span class="pp">[</span><span class="ss">master</span><span class="pp">]</span></span> +<span id="cb8-3"><a href="#cb8-3" aria-hidden="true" tabindex="-1"></a><span class="ex">~/worktrees/rustc/improve-std-char-docs</span> 94cba88553e <span class="pp">[</span><span class="ss">improve</span><span class="pp">-</span><span class="ss">std</span><span class="pp">-</span><span class="ss">char</span><span class="pp">-</span><span class="ss">docs</span><span class="pp">]</span></span> +<span id="cb8-4"><a href="#cb8-4" aria-hidden="true" tabindex="-1"></a><span class="ex">~/worktrees/rustc/is-ascii-octdigit</span> bc57be3af7a <span class="pp">[</span><span class="ss">feature/is</span><span class="pp">-</span><span class="ss">ascii</span><span class="pp">-</span><span class="ss">octdigit</span><span class="pp">]</span></span></code></pre></div> +<p>And hit <code>gwj</code> (pretend that the pipe, |, is your +cursor):</p> +<div class="sourceCode" id="cb9"><pre +class="sourceCode bash"><code class="sourceCode bash"><span id="cb9-1"><a href="#cb9-1" aria-hidden="true" tabindex="-1"></a><span class="ex">λ</span> gwj</span> <span id="cb9-2"><a href="#cb9-2" aria-hidden="true" tabindex="-1"></a><span class="op">&gt;</span> <span class="kw">|</span></span> <span id="cb9-3"><a href="#cb9-3" aria-hidden="true" tabindex="-1"></a> <span class="ex">4/4</span></span> -<span id="cb9-4"><a href="#cb9-4" aria-hidden="true" tabindex="-1"></a><span class="op">&gt;</span> ~/worktrees/rustc/master <span class="ex">eac6c33bc63</span> [master]</span> -<span id="cb9-5"><a href="#cb9-5" aria-hidden="true" tabindex="-1"></a> <span class="ex">~/worktrees/rustc/improve-std-char-docs</span> 94cba88553e [improve-std-char-docs]</span> -<span id="cb9-6"><a href="#cb9-6" aria-hidden="true" tabindex="-1"></a> <span class="ex">~/worktrees/rustc/is-ascii-octdigit</span> bc57be3af7a [feature/is-ascii-octdigit]</span></code></pre></div> +<span id="cb9-4"><a href="#cb9-4" aria-hidden="true" tabindex="-1"></a><span class="op">&gt;</span> ~/worktrees/rustc/master <span class="ex">eac6c33bc63</span> <span class="pp">[</span><span class="ss">master</span><span class="pp">]</span></span> +<span id="cb9-5"><a href="#cb9-5" aria-hidden="true" tabindex="-1"></a> <span class="ex">~/worktrees/rustc/improve-std-char-docs</span> 94cba88553e <span class="pp">[</span><span class="ss">improve</span><span class="pp">-</span><span class="ss">std</span><span class="pp">-</span><span class="ss">char</span><span class="pp">-</span><span class="ss">docs</span><span class="pp">]</span></span> +<span id="cb9-6"><a href="#cb9-6" aria-hidden="true" tabindex="-1"></a> <span class="ex">~/worktrees/rustc/is-ascii-octdigit</span> bc57be3af7a <span class="pp">[</span><span class="ss">feature/is</span><span class="pp">-</span><span class="ss">ascii</span><span class="pp">-</span><span class="ss">octdigit</span><span class="pp">]</span></span></code></pre></div> <p>Approximately type in your branch of choice:</p> -<div class="sourceCode" id="cb10"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb10-1"><a href="#cb10-1" aria-hidden="true" tabindex="-1"></a><span class="ex">λ</span> gwj</span> +<div class="sourceCode" id="cb10"><pre +class="sourceCode bash"><code class="sourceCode bash"><span id="cb10-1"><a href="#cb10-1" aria-hidden="true" tabindex="-1"></a><span class="ex">λ</span> gwj</span> <span id="cb10-2"><a href="#cb10-2" aria-hidden="true" tabindex="-1"></a><span class="op">&gt;</span> docs<span class="kw">|</span></span> <span id="cb10-3"><a href="#cb10-3" aria-hidden="true" tabindex="-1"></a> <span class="ex">4/4</span></span> -<span id="cb10-4"><a href="#cb10-4" aria-hidden="true" tabindex="-1"></a><span class="op">&gt;</span> ~/worktrees/rustc/improve-std-char-docs <span class="ex">94cba88553e</span> [improve-std-char-docs]</span></code></pre></div> +<span id="cb10-4"><a href="#cb10-4" aria-hidden="true" tabindex="-1"></a><span class="op">&gt;</span> ~/worktrees/rustc/improve-std-char-docs <span class="ex">94cba88553e</span> <span class="pp">[</span><span class="ss">improve</span><span class="pp">-</span><span class="ss">std</span><span class="pp">-</span><span class="ss">char</span><span class="pp">-</span><span class="ss">docs</span><span class="pp">]</span></span></code></pre></div> <p>And hit enter. You should find yourself in the selected worktree.</p> -<p>Onward, to the next fault, lack of preview-bility. We can utilize fzf’s aptly named <code>--preview</code> flag, to, well, preview our worktree before performing a selection:</p> -<div class="sourceCode" id="cb11"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb11-1"><a href="#cb11-1" aria-hidden="true" tabindex="-1"></a><span class="fu">gwj ()</span> <span class="kw">{</span></span> +<p>Onward, to the next fault, lack of preview-bility. We can utilize +fzf’s aptly named <code>--preview</code> flag, to, well, preview our +worktree before performing a selection:</p> +<div class="sourceCode" id="cb11"><pre +class="sourceCode bash"><code class="sourceCode bash"><span id="cb11-1"><a href="#cb11-1" aria-hidden="true" tabindex="-1"></a><span class="fu">gwj ()</span> <span class="kw">{</span></span> <span id="cb11-2"><a href="#cb11-2" aria-hidden="true" tabindex="-1"></a> <span class="bu">local</span> <span class="va">out</span></span> <span id="cb11-3"><a href="#cb11-3" aria-hidden="true" tabindex="-1"></a> <span class="va">out</span><span class="op">=</span><span class="va">$(</span></span> <span id="cb11-4"><a href="#cb11-4" aria-hidden="true" tabindex="-1"></a> <span class="fu">git</span> worktree list <span class="kw">|</span></span> @@ -119,8 +173,10 @@ aa857eb953e Auto merge of #100537 - petrochenkov:pic ... <span id="cb11-7"><a href="#cb11-7" aria-hidden="true" tabindex="-1"></a> <span class="va">)</span></span> <span id="cb11-8"><a href="#cb11-8" aria-hidden="true" tabindex="-1"></a> <span class="bu">cd</span> <span class="va">$out</span></span> <span id="cb11-9"><a href="#cb11-9" aria-hidden="true" tabindex="-1"></a><span class="kw">}</span></span></code></pre></div> -<p>Once again, hit <code>gwj</code> inside a git repository with linked worktrees:</p> -<div class="sourceCode" id="cb12"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb12-1"><a href="#cb12-1" aria-hidden="true" tabindex="-1"></a><span class="ex">λ</span> gwj</span> +<p>Once again, hit <code>gwj</code> inside a git repository with linked +worktrees:</p> +<div class="sourceCode" id="cb12"><pre +class="sourceCode bash"><code class="sourceCode bash"><span id="cb12-1"><a href="#cb12-1" aria-hidden="true" tabindex="-1"></a><span class="ex">λ</span> gwj</span> <span id="cb12-2"><a href="#cb12-2" aria-hidden="true" tabindex="-1"></a><span class="ex">╭─────────────────────────────────────────────────────────╮</span></span> <span id="cb12-3"><a href="#cb12-3" aria-hidden="true" tabindex="-1"></a><span class="ex">│</span> eac6c33bc63 Auto merge of 100869 nnethercote:replace... │</span> <span id="cb12-4"><a href="#cb12-4" aria-hidden="true" tabindex="-1"></a><span class="ex">│</span> b32223fec10 Auto merge of 100707 dzvon:fix-typo, r=d... │</span> @@ -138,9 +194,16 @@ aa857eb953e Auto merge of #100537 - petrochenkov:pic ... <span id="cb12-16"><a href="#cb12-16" aria-hidden="true" tabindex="-1"></a><span class="op">&gt;</span> /home/np/worktrees/compiler/master <span class="ex">eac6c...</span></span> <span id="cb12-17"><a href="#cb12-17" aria-hidden="true" tabindex="-1"></a> <span class="ex">/home/np/worktrees/compiler/improve-std-char-docs</span> 94cba...</span> <span id="cb12-18"><a href="#cb12-18" aria-hidden="true" tabindex="-1"></a> <span class="ex">/home/np/worktrees/compiler/is-ascii-octdigit</span> bc57b...</span></code></pre></div> -<p>A fancy preview of the last 10 commits on the branch that the selected worktree corresponds to. In other words, sight for sore eyes. Our little script is already shaping up to be useful, you hit <code>gwj</code>, browse through your worktrees, preview each one and automatically <code>cd</code> to your selection. But we are not done yet.</p> -<p>The last fault was lack shell completions. A quick review of what a shell completion really does:</p> -<div class="sourceCode" id="cb13"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb13-1"><a href="#cb13-1" aria-hidden="true" tabindex="-1"></a><span class="ex">λ</span> git checkout f<span class="op">&lt;</span>tab<span class="op">&gt;</span></span> +<p>A fancy preview of the last 10 commits on the branch that the +selected worktree corresponds to. In other words, sight for sore eyes. +Our little script is already shaping up to be useful, you hit +<code>gwj</code>, browse through your worktrees, preview each one and +automatically <code>cd</code> to your selection. But we are not done +yet.</p> +<p>The last fault was lack shell completions. A quick review of what a +shell completion really does:</p> +<div class="sourceCode" id="cb13"><pre +class="sourceCode bash"><code class="sourceCode bash"><span id="cb13-1"><a href="#cb13-1" aria-hidden="true" tabindex="-1"></a><span class="ex">λ</span> git checkout f<span class="op">&lt;</span>tab<span class="op">&gt;</span></span> <span id="cb13-2"><a href="#cb13-2" aria-hidden="true" tabindex="-1"></a><span class="ex">feature/is-ascii-octdigit</span></span> <span id="cb13-3"><a href="#cb13-3" aria-hidden="true" tabindex="-1"></a><span class="ex">fix/some-error</span></span> <span id="cb13-4"><a href="#cb13-4" aria-hidden="true" tabindex="-1"></a><span class="ex">format-doc-tests</span></span> @@ -148,16 +211,22 @@ aa857eb953e Auto merge of #100537 - petrochenkov:pic ... <span id="cb13-6"><a href="#cb13-6" aria-hidden="true" tabindex="-1"></a><span class="ex">λ</span> git checkout feat<span class="op">&lt;</span>tab<span class="op">&gt;</span></span> <span id="cb13-7"><a href="#cb13-7" aria-hidden="true" tabindex="-1"></a></span> <span id="cb13-8"><a href="#cb13-8" aria-hidden="true" tabindex="-1"></a><span class="ex">λ</span> git checkout feature/is-ascii-octdigit</span></code></pre></div> -<p>Each time you hit “tab”, the shell produces a few “completion candidates”, and once you have just a single candidate left, the shell inserts that for you directly into your edit line. Of course, this process varies from shell to shell.</p> -<p>fzf narrows down your options as you type into the prompt, but you still have to:</p> +<p>Each time you hit “tab”, the shell produces a few “completion +candidates”, and once you have just a single candidate left, the shell +inserts that for you directly into your edit line. Of course, this +process varies from shell to shell.</p> +<p>fzf narrows down your options as you type into the prompt, but you +still have to:</p> <ol type="1"> <li>Type <code>gwj</code></li> <li>Hit enter</li> <li>Type out a query and narrow down your search</li> <li>Hit enter</li> </ol> -<p>We can speed that up a bit, have fzf narrow down the candidates on startup, just like our shell does:</p> -<div class="sourceCode" id="cb14"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb14-1"><a href="#cb14-1" aria-hidden="true" tabindex="-1"></a><span class="fu">gwj ()</span> <span class="kw">{</span></span> +<p>We can speed that up a bit, have fzf narrow down the candidates on +startup, just like our shell does:</p> +<div class="sourceCode" id="cb14"><pre +class="sourceCode bash"><code class="sourceCode bash"><span id="cb14-1"><a href="#cb14-1" aria-hidden="true" tabindex="-1"></a><span class="fu">gwj ()</span> <span class="kw">{</span></span> <span id="cb14-2"><a href="#cb14-2" aria-hidden="true" tabindex="-1"></a> <span class="bu">local</span> <span class="va">out</span> <span class="va">query</span></span> <span id="cb14-3"><a href="#cb14-3" aria-hidden="true" tabindex="-1"></a> <span class="va">query</span><span class="op">=</span><span class="st">&quot;</span><span class="va">${1</span><span class="op">:-</span> <span class="va">}</span><span class="st">&quot;</span></span> <span id="cb14-4"><a href="#cb14-4" aria-hidden="true" tabindex="-1"></a> <span class="va">out</span><span class="op">=</span><span class="va">$(</span></span> @@ -167,8 +236,12 @@ aa857eb953e Auto merge of #100537 - petrochenkov:pic ... <span id="cb14-8"><a href="#cb14-8" aria-hidden="true" tabindex="-1"></a> <span class="va">)</span></span> <span id="cb14-9"><a href="#cb14-9" aria-hidden="true" tabindex="-1"></a> <span class="bu">cd</span> <span class="va">$out</span></span> <span id="cb14-10"><a href="#cb14-10" aria-hidden="true" tabindex="-1"></a><span class="kw">}</span></span></code></pre></div> -<p>The change is extremely tiny, blink-and-you’ll-miss-it kinda tiny. We added a little <code>--query</code> flag, that allows you to prefill the prompt, and the <code>-1</code> flag, that avoids the interactive finder if only one match exists on startup:</p> -<div class="sourceCode" id="cb15"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb15-1"><a href="#cb15-1" aria-hidden="true" tabindex="-1"></a><span class="co"># skip through the fzf prompt:</span></span> +<p>The change is extremely tiny, blink-and-you’ll-miss-it kinda tiny. We +added a little <code>--query</code> flag, that allows you to prefill the +prompt, and the <code>-1</code> flag, that avoids the interactive finder +if only one match exists on startup:</p> +<div class="sourceCode" id="cb15"><pre +class="sourceCode bash"><code class="sourceCode bash"><span id="cb15-1"><a href="#cb15-1" aria-hidden="true" tabindex="-1"></a><span class="co"># skip through the fzf prompt:</span></span> <span id="cb15-2"><a href="#cb15-2" aria-hidden="true" tabindex="-1"></a><span class="ex">λ</span> gwj master</span> <span id="cb15-3"><a href="#cb15-3" aria-hidden="true" tabindex="-1"></a><span class="co"># cd -- ~/worktrees/rustc/master</span></span> <span id="cb15-4"><a href="#cb15-4" aria-hidden="true" tabindex="-1"></a></span> @@ -183,8 +256,11 @@ aa857eb953e Auto merge of #100537 - petrochenkov:pic ... <span id="cb15-13"><a href="#cb15-13" aria-hidden="true" tabindex="-1"></a> <span class="ex">2/2</span></span> <span id="cb15-14"><a href="#cb15-14" aria-hidden="true" tabindex="-1"></a><span class="op">&gt;</span> /home/np/worktrees/compiler/improve-const-perf <span class="ex">eac6c...</span></span> <span id="cb15-15"><a href="#cb15-15" aria-hidden="true" tabindex="-1"></a> <span class="ex">/home/np/worktrees/compiler/improve-std-char-docs</span> 94cba...</span></code></pre></div> -<p>Throw some error handling in there, hook up a similar script to improve the UX of <code>git worktree remove</code>, go wild. A few more helpers I’ve got:</p> -<div class="sourceCode" id="cb16"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb16-1"><a href="#cb16-1" aria-hidden="true" tabindex="-1"></a><span class="co"># gwa /path/to/branch-name</span></span> +<p>Throw some error handling in there, hook up a similar script to +improve the UX of <code>git worktree remove</code>, go wild. A few more +helpers I’ve got:</p> +<div class="sourceCode" id="cb16"><pre +class="sourceCode bash"><code class="sourceCode bash"><span id="cb16-1"><a href="#cb16-1" aria-hidden="true" tabindex="-1"></a><span class="co"># gwa /path/to/branch-name</span></span> <span id="cb16-2"><a href="#cb16-2" aria-hidden="true" tabindex="-1"></a><span class="co"># creates a new branch and &quot;switches&quot; to it</span></span> <span id="cb16-3"><a href="#cb16-3" aria-hidden="true" tabindex="-1"></a><span class="kw">function</span><span class="fu"> gwa ()</span> <span class="kw">{</span></span> <span id="cb16-4"><a href="#cb16-4" aria-hidden="true" tabindex="-1"></a> <span class="fu">git</span> worktree add <span class="st">&quot;</span><span class="va">$1</span><span class="st">&quot;</span> <span class="kw">&amp;&amp;</span> <span class="bu">cd</span> <span class="st">&quot;</span><span class="va">$1</span><span class="st">&quot;</span></span> @@ -197,88 +273,175 @@ aa857eb953e Auto merge of #100537 - petrochenkov:pic ... Programming On 34 Keys -<p>Minimizing your keyboard layout is a slippery slope. A few months ago, I built the <a href="https://github.com/icyphox/ferricy">Ferricy</a>, a 34-key-split-ortho-ergo keyboard. The Ferricy is a fork of the <a href="https://github.com/davidphilipbarr/Sweep/tree/main/Sweep%20Bling%20MX">Ferris Sweep MX Bling</a>.</p> +<p>Minimizing your keyboard layout is a slippery slope. A few months +ago, I built the <a +href="https://github.com/icyphox/ferricy">Ferricy</a>, a +34-key-split-ortho-ergo keyboard. The Ferricy is a fork of the <a +href="https://github.com/davidphilipbarr/Sweep/tree/main/Sweep%20Bling%20MX">Ferris +Sweep MX Bling</a>.</p> <figure> -<img src="https://u.peppe.rs/otz.jpg" alt="The Ferricy, designed by icyphox" /><figcaption aria-hidden="true">The Ferricy, designed by <a href="https://icyphox.sh">icyphox</a></figcaption> +<img src="https://u.peppe.rs/otz.jpg" +alt="The Ferricy, designed by icyphox" /> +<figcaption aria-hidden="true">The Ferricy, designed by <a +href="https://icyphox.sh">icyphox</a></figcaption> </figure> -<p>My daily use consists of a bit of prose and a lot of program, my layout has evolved accordingly.</p> +<p>My daily use consists of a bit of prose and a lot of program, my +layout has evolved accordingly.</p> <h1 id="base-layer">Base Layer</h1> <figure> -<img src="https://u.peppe.rs/base.png" alt="Colemak with no mods" /><figcaption aria-hidden="true">Colemak with no mods</figcaption> +<img src="https://u.peppe.rs/base.png" alt="Colemak with no mods" /> +<figcaption aria-hidden="true">Colemak with no mods</figcaption> </figure> -<p>The base layer contains alphabets, four symbols and four whitespace keys:</p> +<p>The base layer contains alphabets, four symbols and four whitespace +keys:</p> <ul> <li>Alphas: Stock Colemak, with no modifications whatsoever</li> <li>Symbols: <code>. , / ;</code></li> <li>Whitespace: tab, space, enter, backspace (from left to right)</li> </ul> <h1 id="layers">Layers</h1> -<p>Keyboard input is complex and it is impossible to skirt around it. You can either use a keyboard with enough keys to supply all possible inputs (a mechanical burden), or you can use firmware to supply all possible inputs (a cognitive burden). Layers are a cognitive burden.</p> -<p>I use 3 layers, heavily inspired by <a href="https://github.com/manna-harbour/miryoku">Miryoku</a>, but tuned for programming. Excluding the base Colemak layer:</p> +<p>Keyboard input is complex and it is impossible to skirt around it. +You can either use a keyboard with enough keys to supply all possible +inputs (a mechanical burden), or you can use firmware to supply all +possible inputs (a cognitive burden). Layers are a cognitive burden.</p> +<p>I use 3 layers, heavily inspired by <a +href="https://github.com/manna-harbour/miryoku">Miryoku</a>, but tuned +for programming. Excluding the base Colemak layer:</p> <ul> -<li><code>NAV</code>: activated on holding <code>space</code> (left thumb)</li> -<li><code>NUM</code>: activated on holding <code>tab</code> (left thumb)</li> -<li><code>SYM</code>: activated on holding <code>enter</code> (right thumb)</li> +<li><code>NAV</code>: activated on holding <code>space</code> (left +thumb)</li> +<li><code>NUM</code>: activated on holding <code>tab</code> (left +thumb)</li> +<li><code>SYM</code>: activated on holding <code>enter</code> (right +thumb)</li> </ul> <h2 id="the-nav-layer">The <code>NAV</code> Layer</h2> -<p>As the name suggests, this layer is focused on navigation. Arrow keys and the likes.</p> +<p>As the name suggests, this layer is focused on navigation. Arrow keys +and the likes.</p> <figure> -<img src="https://u.peppe.rs/nav.png" alt="NAV, on holding space" /><figcaption aria-hidden="true"><code>NAV</code>, on holding <code>space</code></figcaption> +<img src="https://u.peppe.rs/nav.png" alt="NAV, on holding space" /> +<figcaption aria-hidden="true"><code>NAV</code>, on holding +<code>space</code></figcaption> </figure> -<p>Using Vim and Colemak means you lose out on HJKL navigation. However, on activating the <code>NAV</code> layer, the right home-row is converted into arrow keys. In essence, by holding space, I can navigate Vim with the home-row, or Firefox, or my PDF reader. I no longer need to look for software that allows Vim navigation keys, because it is baked into the firmware!</p> -<p>My Vim motions are not limited to HJKL. In fact, my Vim motions are rarely HJKL. I tend to use <code>}</code> (next paragraph) and <code>)</code> (next sentence) more often. As a result, these have found their way into my <code>NAV</code> layer, over the likes of <code>PgDown</code> and <code>End</code>. Having brackets at my index and middle fingers is nice for programming too.</p> +<p>Using Vim and Colemak means you lose out on HJKL navigation. However, +on activating the <code>NAV</code> layer, the right home-row is +converted into arrow keys. In essence, by holding space, I can navigate +Vim with the home-row, or Firefox, or my PDF reader. I no longer need to +look for software that allows Vim navigation keys, because it is baked +into the firmware!</p> +<p>My Vim motions are not limited to HJKL. In fact, my Vim motions are +rarely HJKL. I tend to use <code>}</code> (next paragraph) and +<code>)</code> (next sentence) more often. As a result, these have found +their way into my <code>NAV</code> layer, over the likes of +<code>PgDown</code> and <code>End</code>. Having brackets at my index +and middle fingers is nice for programming too.</p> <h2 id="the-sym-layer">The <code>SYM</code> Layer</h2> <figure> -<img src="https://u.peppe.rs/sym.png" alt="SYM, on holding enter" /><figcaption aria-hidden="true"><code>SYM</code>, on holding <code>enter</code></figcaption> +<img src="https://u.peppe.rs/sym.png" alt="SYM, on holding enter" /> +<figcaption aria-hidden="true"><code>SYM</code>, on holding +<code>enter</code></figcaption> </figure> -<p>This layer contains all the symbols that you would find by hitting <code>Shift</code> and a key on the number row. Probably noteworthy to Vim users: the symbols are arranged in the form of a mirrored numpad for exactly one reason: to move <code>$</code> to the left of <code>^</code>. It has always annoyed me that <code>$</code> moves the cursor to the end of the line and <code>^</code> moves it to the beginning, but their position on a typical number row are reversed, 4 comes before 6.</p> +<p>This layer contains all the symbols that you would find by hitting +<code>Shift</code> and a key on the number row. Probably noteworthy to +Vim users: the symbols are arranged in the form of a mirrored numpad for +exactly one reason: to move <code>$</code> to the left of +<code>^</code>. It has always annoyed me that <code>$</code> moves the +cursor to the end of the line and <code>^</code> moves it to the +beginning, but their position on a typical number row are reversed, 4 +comes before 6.</p> <h2 id="the-num-layer">The <code>NUM</code> layer</h2> <figure> -<img src="https://u.peppe.rs/num.png" alt="NUM, on holding tab" /><figcaption aria-hidden="true"><code>NUM</code>, on holding <code>tab</code></figcaption> +<img src="https://u.peppe.rs/num.png" alt="NUM, on holding tab" /> +<figcaption aria-hidden="true"><code>NUM</code>, on holding +<code>tab</code></figcaption> </figure> -<p>Another deviation from Miryoku, the numpad just feels <em>right</em> on my <em>right</em> hand.</p> +<p>Another deviation from Miryoku, the numpad just feels <em>right</em> +on my <em>right</em> hand.</p> <h1 id="zmk-combos">ZMK Combos</h1> -<p>If you have been paying close attention, you might have noticed that <code>escape</code> didn’t make it to any layer. <code>escape</code> is too crucial to put on a non-base layer, but at the same time, not as important to deserve a place on the base layer. That is where ZMK’s combos come in. Combos let you tap any number of keys, and combine them to form a single key. I have combos set up for underscore, minus, escape and caps-word (more on caps-word later):</p> +<p>If you have been paying close attention, you might have noticed that +<code>escape</code> didn’t make it to any layer. <code>escape</code> is +too crucial to put on a non-base layer, but at the same time, not as +important to deserve a place on the base layer. That is where ZMK’s +combos come in. Combos let you tap any number of keys, and combine them +to form a single key. I have combos set up for underscore, minus, escape +and caps-word (more on caps-word later):</p> <figure> -<img src="https://u.peppe.rs/combos.png" alt="Combos are almost piano-like" /><figcaption aria-hidden="true">Combos are almost piano-like</figcaption> +<img src="https://u.peppe.rs/combos.png" +alt="Combos are almost piano-like" /> +<figcaption aria-hidden="true">Combos are almost piano-like</figcaption> </figure> <h1 id="home-row-mods">Home-row Mods</h1> -<p>Inherited from Miryoku, I have home-row mods for activating <code>Super</code>, <code>Alt</code>, <code>Shift</code>, <code>Ctrl</code> and <code>Hyper</code> (<code>Ctrl + Shift + Alt + Super</code>). The idea is to send <code>T</code> on tap and <code>Ctrl</code> on hold. Home-row mods are fairly popular, so I’ll not go into the details.</p> +<p>Inherited from Miryoku, I have home-row mods for activating +<code>Super</code>, <code>Alt</code>, <code>Shift</code>, +<code>Ctrl</code> and <code>Hyper</code> +(<code>Ctrl + Shift + Alt + Super</code>). The idea is to send +<code>T</code> on tap and <code>Ctrl</code> on hold. Home-row mods are +fairly popular, so I’ll not go into the details.</p> <figure> -<img src="https://u.peppe.rs/homerow.png" alt="Super, Alt, Shift, Ctrl, Hyper; on the left half, and mirrored on the right half" /><figcaption aria-hidden="true">Super, Alt, Shift, Ctrl, Hyper; on the left half, and mirrored on the right half</figcaption> +<img src="https://u.peppe.rs/homerow.png" +alt="Super, Alt, Shift, Ctrl, Hyper; on the left half, and mirrored on the right half" /> +<figcaption aria-hidden="true">Super, Alt, Shift, Ctrl, Hyper; on the +left half, and mirrored on the right half</figcaption> </figure> -<p><code>Hyper</code> bridges the gap between firmware and software. You can never configure key combination that, opens Firefox, for example, through firmware alone. However, with the <code>Hyper</code> key, and some <code>sxhkd</code> magic, you can emulate that. Pressing <code>Hyper + F</code> on a keyboard is just two keys, but the key codes sent are <code>Ctrl + Shift + Alt + Super + F</code>. That key combination is not intercepted by any application as a shortcut, except for the following <code>sxhkd</code> stanza:</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" tabindex="-1"></a><span class="ex">super</span> + alt + shift + ctrl + f</span> +<p><code>Hyper</code> bridges the gap between firmware and software. You +can never configure key combination that, opens Firefox, for example, +through firmware alone. However, with the <code>Hyper</code> key, and +some <code>sxhkd</code> magic, you can emulate that. Pressing +<code>Hyper + F</code> on a keyboard is just two keys, but the key codes +sent are <code>Ctrl + Shift + Alt + Super + F</code>. That key +combination is not intercepted by any application as a shortcut, except +for the following <code>sxhkd</code> stanza:</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" tabindex="-1"></a><span class="ex">super</span> + alt + shift + ctrl + f</span> <span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a> <span class="ex">xdotool</span> search <span class="st">&quot;Mozilla Firefox&quot;</span> windowactivate</span></code></pre></div> -<p>Alternatively, you can intercept unused <code>F</code> keys: <code>F13</code> through <code>F24</code>.</p> -<p>Home-row mods are mirrored on each half because it would be impossible to hit <code>Ctrl + T</code> if not; they lie on the same key.</p> +<p>Alternatively, you can intercept unused <code>F</code> keys: +<code>F13</code> through <code>F24</code>.</p> +<p>Home-row mods are mirrored on each half because it would be +impossible to hit <code>Ctrl + T</code> if not; they lie on the same +key.</p> <h1 id="caps-word">Caps-word</h1> -<p>Caps-word is a clever caps-lock, built into ZMK. Typing out constants such as <code>PORT</code> with home-row mods would look like this:</p> +<p>Caps-word is a clever caps-lock, built into ZMK. Typing out constants +such as <code>PORT</code> with home-row mods would look like this:</p> <ul> -<li>hold <code>e</code> (shift) on left hand, and tap <code>p</code> on right hand</li> -<li>hold <code>e</code> (shift) on left hand, and tap <code>o</code> on right hand</li> -<li>hold <code>s</code> (shift) on right hand, and tap <code>r</code> on left hand</li> -<li>hold <code>s</code> (shift) on right hand, and tap <code>t</code> on left hand</li> +<li>hold <code>e</code> (shift) on left hand, and tap <code>p</code> on +right hand</li> +<li>hold <code>e</code> (shift) on left hand, and tap <code>o</code> on +right hand</li> +<li>hold <code>s</code> (shift) on right hand, and tap <code>r</code> on +left hand</li> +<li>hold <code>s</code> (shift) on right hand, and tap <code>t</code> on +left hand</li> </ul> -<p>This hold-alternate-hold dance gets tiring quickly. With caps-word, however:</p> +<p>This hold-alternate-hold dance gets tiring quickly. With caps-word, +however:</p> <ul> <li>toggle <code>caps_word</code></li> -<li>type out <code>p</code>, <code>o</code>, <code>r</code>, <code>t</code></li> +<li>type out <code>p</code>, <code>o</code>, <code>r</code>, +<code>t</code></li> <li>hit a <em>break</em> character (space, enter will do)</li> <li>continue</li> </ul> -<p>Caps-word automatically disables capitalization upon encountering a breaking character, (which are space, enter or any modifier, by default) right in the firmware!</p> +<p>Caps-word automatically disables capitalization upon encountering a +breaking character, (which are space, enter or any modifier, by default) +right in the firmware!</p> <h1 id="findings">Findings</h1> -<p>34-keys has been reasonably comfortable to use, for both prose and program. My palms do not move across the desk at all, as I reach for keys. I mostly write Rust and Bash, and my layout has evolved to accomodate special characters from their grammars (angled brackets and hyphens, specifically). If you are on a similar journey, I would suggest focusing on accuracy and comfort over speed. Speed comes with time.</p> +<p>34-keys has been reasonably comfortable to use, for both prose and +program. My palms do not move across the desk at all, as I reach for +keys. I mostly write Rust and Bash, and my layout has evolved to +accomodate special characters from their grammars (angled brackets and +hyphens, specifically). If you are on a similar journey, I would suggest +focusing on accuracy and comfort over speed. Speed comes with time.</p> https://peppe.rs/posts/programming_on_34_keys/ Sun, 28 Aug 2022 13:51:00 +0000 https://peppe.rs/posts/programming_on_34_keys/ A Reference Counted Afterlife -<p>I took interest in the Egyptian rendition of the afterlife recently.</p> +<p>I took interest in the Egyptian rendition of the afterlife +recently.</p> <h3 id="parts-of-the-soul">Parts of the Soul</h3> -<p>Ancient Egyptians believed that the soul comprised of several components:</p> +<p>Ancient Egyptians believed that the soul comprised of several +components:</p> <ul> <li><em>ren</em></li> <li><em>ka</em></li> @@ -286,47 +449,80 @@ aa857eb953e Auto merge of #100537 - petrochenkov:pic ... <li><em>ba</em></li> <li><em>sheut</em></li> </ul> -<p>Egyptians emphasized on preserving the different parts of the soul. Mummification for example, served to preserve the physical part of the soul. The other components have their respective preservation strategies.</p> -<p>Of all of these bits, I find <em>ren</em>, which simply means <em>name</em>, to be the most interesting. <em>Ba</em>, the human-headed chicken that represents <em>personality</em>, is a close favourite.</p> -<p><em>Ren</em> is the name given to a person at birth. Egyptians believed that this portion of the soul would continue to live on for as long as it was spoken. If you were someone worthy of continued existence, your name would be inscribed all over the place. If you were the type to snatch away bread from children, your name would be condemned from memory, forgotten.</p> +<p>Egyptians emphasized on preserving the different parts of the soul. +Mummification for example, served to preserve the physical part of the +soul. The other components have their respective preservation +strategies.</p> +<p>Of all of these bits, I find <em>ren</em>, which simply means +<em>name</em>, to be the most interesting. <em>Ba</em>, the human-headed +chicken that represents <em>personality</em>, is a close favourite.</p> +<p><em>Ren</em> is the name given to a person at birth. Egyptians +believed that this portion of the soul would continue to live on for as +long as it was spoken. If you were someone worthy of continued +existence, your name would be inscribed all over the place. If you were +the type to snatch away bread from children, your name would be +condemned from memory, forgotten.</p> <h3 id="garbage-collection">Garbage-collection</h3> -<p>The concept of <em>ren</em> seems to be perfectly analogous to reference counted garbage-collection.</p> +<p>The concept of <em>ren</em> seems to be perfectly analogous to +reference counted garbage-collection.</p> <ul> -<li>A name (<em>ren</em>) is assigned to an object (person) on initialization (at birth)</li> +<li>A name (<em>ren</em>) is assigned to an object (person) on +initialization (at birth)</li> <li>Names are used to refer to objects</li> -<li>Objects go out of existence when there are no more references to them</li> +<li>Objects go out of existence when there are no more references to +them</li> </ul> -<p>The concept of <em>ren</em> seems to model human-memory. The similarity with garbage-collection is now easily explained, because garbage-collection models a program’s memory.</p> -<p>Perhaps some cheeky Egyptian has attained immortality by creating a <em>ren</em>-cycle.</p> +<p>The concept of <em>ren</em> seems to model human-memory. The +similarity with garbage-collection is now easily explained, because +garbage-collection models a program’s memory.</p> +<p>Perhaps some cheeky Egyptian has attained immortality by creating a +<em>ren</em>-cycle.</p> https://peppe.rs/posts/a_reference_counted_afterlife/ Tue, 02 Aug 2022 16:47:00 +0000 https://peppe.rs/posts/a_reference_counted_afterlife/ Lotus58 -<p>Earlier this month, I decided that I would laugh at Indian customs in the face by building a split-ergo mechanical keyboard from scratch rather than purchasing a Moonlander.</p> +<p>Earlier this month, I decided that I would laugh at Indian customs in +the face by building a split-ergo mechanical keyboard from scratch +rather than purchasing a Moonlander.</p> <figure> -<img src="https://u.peppe.rs/i8k.jpg" alt="The finished product" /><figcaption aria-hidden="true">The finished product</figcaption> +<img src="https://u.peppe.rs/i8k.jpg" alt="The finished product" /> +<figcaption aria-hidden="true">The finished product</figcaption> </figure> <h2 id="sourcing-the-parts">Sourcing the parts</h2> -<p>If you, like me, live in India, you might find this section useful. My approach to finding parts:</p> +<p>If you, like me, live in India, you might find this section useful. +My approach to finding parts:</p> <ul> <li>Check reputed, local online stores</li> <li>Check physical hardware stores</li> <li>Import the part</li> </ul> <h3 id="pcbs">PCBs</h3> -<p>This was by far the hardest component to procure. Fabrication services have certain <em>capabilities</em>. Capabilities are the limitations of a fabrication service. For example, a service may be capable of drilling holes no smaller than 0.3mm in diameter. Most sites have a verification process to check if their capabilities meet your design’s requirements. I tried a few local PCB fabrication services:</p> +<p>This was by far the hardest component to procure. Fabrication +services have certain <em>capabilities</em>. Capabilities are the +limitations of a fabrication service. For example, a service may be +capable of drilling holes no smaller than 0.3mm in diameter. Most sites +have a verification process to check if their capabilities meet your +design’s requirements. I tried a few local PCB fabrication services:</p> <ul> <li>Lion PCB: Capabilities did not meet my requirements</li> <li>PCBPower: Capabilities did not meet my requirements</li> <li>Circuitwala: Capabilities did not meet my requirements</li> </ul> -<p>I settled for JLCPCB, a Chinese service. PCBs themselves were 16 USD, shipping was another 35 USD, and customs was another 3.5K INR (ouch).</p> +<p>I settled for JLCPCB, a Chinese service. PCBs themselves were 16 USD, +shipping was another 35 USD, and customs was another 3.5K INR +(ouch).</p> <h3 id="case-material">Case material</h3> -<p>I don’t really have a case for the Lotus58, it is more of a “plastic sandwich”. I purchased acrylic plates from Robu. Cheap, fast, solid, and customizable. I cannot recommend Robu enough. A full set of plates (2 top plates and 2 bottom plates) cost me about 500 INR. I also bought a pair of laptop height raisers on Amazon to create a budget tenting setup.</p> +<p>I don’t really have a case for the Lotus58, it is more of a “plastic +sandwich”. I purchased acrylic plates from Robu. Cheap, fast, solid, and +customizable. I cannot recommend Robu enough. A full set of plates (2 +top plates and 2 bottom plates) cost me about 500 INR. I also bought a +pair of laptop height raisers on Amazon to create a budget tenting +setup.</p> <h3 id="electronics">Electronics</h3> -<p>You’ll need a few rather specific electronic components such as hotswap sockets and TRRS mounts, the rest are commonly available:</p> +<p>You’ll need a few rather specific electronic components such as +hotswap sockets and TRRS mounts, the rest are commonly available:</p> <ul> <li>Hotswap sockets: StacksKB</li> <li>TRRS mounts (PJ 320A): StacksKB</li> @@ -335,7 +531,8 @@ aa857eb953e Auto merge of #100537 - petrochenkov:pic ... <li>M2 spacers: ThinkRobotics</li> <li>Arduino Pro Micro: Robu</li> </ul> -<p>I skimped out on optional components such as OLEDs and rotary encoders.</p> +<p>I skimped out on optional components such as OLEDs and rotary +encoders.</p> <h3 id="switches-and-keycaps">Switches and Keycaps</h3> <p>Arguably the most fun part of the build:</p> <ul> @@ -343,30 +540,57 @@ aa857eb953e Auto merge of #100537 - petrochenkov:pic ... <li>DSA blanks: Meckeys</li> </ul> <h2 id="building-the-keyboard">Building the keyboard</h2> -<p>The the build is extremely straightforward. Through hole components are easy to solder. Be wary of component placement and orientation. Check thrice, solder once. Few debugging tips:</p> +<p>The the build is extremely straightforward. Through hole components +are easy to solder. Be wary of component placement and orientation. +Check thrice, solder once. Few debugging tips:</p> <ul> -<li>if a single key does not actuate, check the hotswap for poor soldering (reflow the joint), and the switch pins for deformation during installation</li> -<li>if an entire column or row activates on a single key-press, a connection has been shorted</li> -<li>if only some of the keys on a given row actuate, a diode has been soldered on the wrong way</li> +<li>if a single key does not actuate, check the hotswap for poor +soldering (reflow the joint), and the switch pins for deformation during +installation</li> +<li>if an entire column or row activates on a single key-press, a +connection has been shorted</li> +<li>if only some of the keys on a given row actuate, a diode has been +soldered on the wrong way</li> </ul> <h2 id="the-typing-experience">The typing experience</h2> -<p>I decidede to give QWERTY the boot and learn Colemak along with the new keyboard. The first few weeks were terrible because I could neither type QWERTY nor Colemak, but I got the hang of it pretty quickly. Typing websites do help, but it is best to simply use it in your daily workflow. No site can help you get accustomed to the various things you use your keyboard for such as switching windows or navigating vim/tmux.</p> +<p>I decidede to give QWERTY the boot and learn Colemak along with the +new keyboard. The first few weeks were terrible because I could neither +type QWERTY nor Colemak, but I got the hang of it pretty quickly. Typing +websites do help, but it is best to simply use it in your daily +workflow. No site can help you get accustomed to the various things you +use your keyboard for such as switching windows or navigating +vim/tmux.</p> <h3 id="colemak">Colemak</h3> -<p>Alt layouts such as Colemak are definitely worth it. I find that Colemak reduces finger movement a lot, a good portion of the keys on the left hand are the same as QWERTY, it is fairly easy to pick up as well.</p> +<p>Alt layouts such as Colemak are definitely worth it. I find that +Colemak reduces finger movement a lot, a good portion of the keys on the +left hand are the same as QWERTY, it is fairly easy to pick up as +well.</p> <h3 id="vim">Vim</h3> -<p>Using an alt layout means most programs with keyboard shortcuts are not going to work as expected, <code>HJKL</code> on vim for movements being one of them. I took the short route out by creating a new layer with arrow keys on the home row:</p> +<p>Using an alt layout means most programs with keyboard shortcuts are +not going to work as expected, <code>HJKL</code> on vim for movements +being one of them. I took the short route out by creating a new layer +with arrow keys on the home row:</p> <pre><code>default homerow: H N E I &quot;nav&quot; layer: &lt; v ^ &gt;</code></pre> -<p>The remaining commands in vim are largely mnemonics. Navigating with home-row arrow keys also means that I can use “HJKL” globally, to scroll a website, for example.</p> +<p>The remaining commands in vim are largely mnemonics. Navigating with +home-row arrow keys also means that I can use “HJKL” globally, to scroll +a website, for example.</p> <h3 id="cutting-down-to-34-keys">Cutting down to 34 keys</h3> -<p>A couple months into my ergo journey, I realized that I could get away by moving my fingers even lesser. I moved modifiers such as <code>Super</code>, <code>Ctrl</code>, <code>Alt</code> and <code>Shift</code> to the home-row as QMK Mod Taps. The rest of the keys are cleverly placed in layers, not too much unlike the Miryoku layout. Even for someone that writes Rust (a symbol-heavy grammar), I find 34-keys to be sufficient.</p> +<p>A couple months into my ergo journey, I realized that I could get +away by moving my fingers even lesser. I moved modifiers such as +<code>Super</code>, <code>Ctrl</code>, <code>Alt</code> and +<code>Shift</code> to the home-row as QMK Mod Taps. The rest of the keys +are cleverly placed in layers, not too much unlike the Miryoku layout. +Even for someone that writes Rust (a symbol-heavy grammar), I find +34-keys to be sufficient.</p> <h2 id="conclusion">Conclusion</h2> <p>I have been bitten by the ergomech bug.</p> <figure> -<img src="https://u.peppe.rs/XM3.jpg" alt="The Lotus58 in action" /><figcaption aria-hidden="true">The Lotus58 in action</figcaption> +<img src="https://u.peppe.rs/XM3.jpg" alt="The Lotus58 in action" /> +<figcaption aria-hidden="true">The Lotus58 in action</figcaption> </figure> https://peppe.rs/posts/lotus58/ Mon, 13 Jun 2022 13:55:00 +0000 @@ -374,14 +598,23 @@ H N E I Lightweight Linting -<p><a href="https://tree-sitter.github.io/tree-sitter/using-parsers#pattern-matching-with-queries">Tree-sitter</a> queries allow you to search for patterns in syntax trees, much like a regex would, in text. Combine that with some Rust glue to write simple, custom linters.</p> +<p><a +href="https://tree-sitter.github.io/tree-sitter/using-parsers#pattern-matching-with-queries">Tree-sitter</a> +queries allow you to search for patterns in syntax trees, much like a +regex would, in text. Combine that with some Rust glue to write simple, +custom linters.</p> <h3 id="tree-sitter-syntax-trees">Tree-sitter syntax trees</h3> -<p>Here is a quick crash course on syntax trees generated by tree-sitter. Syntax trees produced by tree-sitter are represented by S-expressions. The generated S-expression for the following Rust code,</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" tabindex="-1"></a><span class="kw">fn</span> main() <span class="op">{</span></span> +<p>Here is a quick crash course on syntax trees generated by +tree-sitter. Syntax trees produced by tree-sitter are represented by +S-expressions. The generated S-expression for the following Rust +code,</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" tabindex="-1"></a><span class="kw">fn</span> main() <span class="op">{</span></span> <span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a> <span class="kw">let</span> x <span class="op">=</span> <span class="dv">2</span><span class="op">;</span></span> <span id="cb1-3"><a href="#cb1-3" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code></pre></div> <p>would be:</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" tabindex="-1"></a>(source_file</span> +<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>(source_file</span> <span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a> (function_item</span> <span id="cb2-3"><a href="#cb2-3" aria-hidden="true" tabindex="-1"></a> name: (identifier)</span> <span id="cb2-4"><a href="#cb2-4" aria-hidden="true" tabindex="-1"></a> parameters: (parameters)</span> @@ -390,13 +623,19 @@ H N E I <span id="cb2-7"><a href="#cb2-7" aria-hidden="true" tabindex="-1"></a> (let_declaration </span> <span id="cb2-8"><a href="#cb2-8" aria-hidden="true" tabindex="-1"></a> pattern: (identifier)</span> <span id="cb2-9"><a href="#cb2-9" aria-hidden="true" tabindex="-1"></a> value: (integer_literal)))))</span></code></pre></div> -<p>Syntax trees generated by tree-sitter have a couple of other cool properties: they are <em>lossless</em> syntax trees. Given a lossless syntax tree, you can regenerate the original source code in its entirety. Consider the following addition to our example:</p> -<div class="sourceCode" id="cb3"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a> <span class="kw">fn</span> main() <span class="op">{</span></span> +<p>Syntax trees generated by tree-sitter have a couple of other cool +properties: they are <em>lossless</em> syntax trees. Given a lossless +syntax tree, you can regenerate the original source code in its +entirety. Consider the following addition to our example:</p> +<div class="sourceCode" id="cb3"><pre +class="sourceCode rust"><code class="sourceCode rust"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a> <span class="kw">fn</span> main() <span class="op">{</span></span> <span id="cb3-2"><a href="#cb3-2" aria-hidden="true" tabindex="-1"></a><span class="op">+</span> <span class="co">// a comment goes here</span></span> <span id="cb3-3"><a href="#cb3-3" aria-hidden="true" tabindex="-1"></a> <span class="kw">let</span> x <span class="op">=</span> <span class="dv">2</span><span class="op">;</span></span> <span id="cb3-4"><a href="#cb3-4" aria-hidden="true" tabindex="-1"></a> <span class="op">}</span></span></code></pre></div> -<p>The tree-sitter syntax tree preserves the comment, while the typical abstract syntax tree wouldn’t:</p> -<div class="sourceCode" id="cb4"><pre class="sourceCode scheme"><code class="sourceCode scheme"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a> (source_file</span> +<p>The tree-sitter syntax tree preserves the comment, while the typical +abstract syntax tree wouldn’t:</p> +<div class="sourceCode" id="cb4"><pre +class="sourceCode scheme"><code class="sourceCode scheme"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a> (source_file</span> <span id="cb4-2"><a href="#cb4-2" aria-hidden="true" tabindex="-1"></a> (function_item</span> <span id="cb4-3"><a href="#cb4-3" aria-hidden="true" tabindex="-1"></a> name: (identifier)</span> <span id="cb4-4"><a href="#cb4-4" aria-hidden="true" tabindex="-1"></a> parameters: (parameters)</span> @@ -407,25 +646,34 @@ H N E I <span id="cb4-9"><a href="#cb4-9" aria-hidden="true" tabindex="-1"></a> pattern: (identifier)</span> <span id="cb4-10"><a href="#cb4-10" aria-hidden="true" tabindex="-1"></a> value: (integer_literal)))))</span></code></pre></div> <h3 id="tree-sitter-queries">Tree-sitter queries</h3> -<p>Tree-sitter provides a DSL to match over CSTs. These queries resemble our S-expression syntax trees, here is a query to match all line comments in a Rust CST:</p> -<div class="sourceCode" id="cb5"><pre class="sourceCode scheme"><code class="sourceCode scheme"><span id="cb5-1"><a href="#cb5-1" aria-hidden="true" tabindex="-1"></a>(line_comment)</span> +<p>Tree-sitter provides a DSL to match over CSTs. These queries resemble +our S-expression syntax trees, here is a query to match all line +comments in a Rust CST:</p> +<div class="sourceCode" id="cb5"><pre +class="sourceCode scheme"><code class="sourceCode scheme"><span id="cb5-1"><a href="#cb5-1" aria-hidden="true" tabindex="-1"></a>(line_comment)</span> <span id="cb5-2"><a href="#cb5-2" aria-hidden="true" tabindex="-1"></a></span> <span id="cb5-3"><a href="#cb5-3" aria-hidden="true" tabindex="-1"></a><span class="co">; matches the following rust code</span></span> <span id="cb5-4"><a href="#cb5-4" aria-hidden="true" tabindex="-1"></a><span class="co">; // a comment goes here</span></span></code></pre></div> -<p>Neat, eh? But don’t take my word for it, give it a go on the <a href="https://tree-sitter.github.io/tree-sitter/playground">tree-sitter playground</a>. Type in a query like so:</p> -<div class="sourceCode" id="cb6"><pre class="sourceCode scheme"><code class="sourceCode scheme"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true" tabindex="-1"></a><span class="co">; the web playground requires you to specify a &quot;capture&quot;</span></span> +<p>Neat, eh? But don’t take my word for it, give it a go on the <a +href="https://tree-sitter.github.io/tree-sitter/playground">tree-sitter +playground</a>. Type in a query like so:</p> +<div class="sourceCode" id="cb6"><pre +class="sourceCode scheme"><code class="sourceCode scheme"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true" tabindex="-1"></a><span class="co">; the web playground requires you to specify a &quot;capture&quot;</span></span> <span id="cb6-2"><a href="#cb6-2" aria-hidden="true" tabindex="-1"></a><span class="co">; you will notice the capture and the nodes it captured</span></span> <span id="cb6-3"><a href="#cb6-3" aria-hidden="true" tabindex="-1"></a><span class="co">; turn blue</span></span> <span id="cb6-4"><a href="#cb6-4" aria-hidden="true" tabindex="-1"></a>(line_comment) @capture</span></code></pre></div> -<p>Here’s another to match <code>let</code> expressions that bind an integer to an identifier:</p> -<div class="sourceCode" id="cb7"><pre class="sourceCode scheme"><code class="sourceCode scheme"><span id="cb7-1"><a href="#cb7-1" aria-hidden="true" tabindex="-1"></a>(let_declaration</span> +<p>Here’s another to match <code>let</code> expressions that bind an +integer to an identifier:</p> +<div class="sourceCode" id="cb7"><pre +class="sourceCode scheme"><code class="sourceCode scheme"><span id="cb7-1"><a href="#cb7-1" aria-hidden="true" tabindex="-1"></a>(let_declaration</span> <span id="cb7-2"><a href="#cb7-2" aria-hidden="true" tabindex="-1"></a> pattern: (identifier)</span> <span id="cb7-3"><a href="#cb7-3" aria-hidden="true" tabindex="-1"></a> value: (integer_literal))</span> <span id="cb7-4"><a href="#cb7-4" aria-hidden="true" tabindex="-1"></a> </span> <span id="cb7-5"><a href="#cb7-5" aria-hidden="true" tabindex="-1"></a><span class="co">; matches:</span></span> <span id="cb7-6"><a href="#cb7-6" aria-hidden="true" tabindex="-1"></a><span class="co">; let foo = 2;</span></span></code></pre></div> <p>We can <em>capture</em> nodes into variables:</p> -<div class="sourceCode" id="cb8"><pre class="sourceCode scheme"><code class="sourceCode scheme"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true" tabindex="-1"></a>(let_declaration </span> +<div class="sourceCode" id="cb8"><pre +class="sourceCode scheme"><code class="sourceCode scheme"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true" tabindex="-1"></a>(let_declaration </span> <span id="cb8-2"><a href="#cb8-2" aria-hidden="true" tabindex="-1"></a> pattern: (identifier) @my-capture</span> <span id="cb8-3"><a href="#cb8-3" aria-hidden="true" tabindex="-1"></a> value: (integer_literal))</span> <span id="cb8-4"><a href="#cb8-4" aria-hidden="true" tabindex="-1"></a> </span> @@ -435,7 +683,8 @@ H N E I <span id="cb8-8"><a href="#cb8-8" aria-hidden="true" tabindex="-1"></a><span class="co">; captures:</span></span> <span id="cb8-9"><a href="#cb8-9" aria-hidden="true" tabindex="-1"></a><span class="co">; foo</span></span></code></pre></div> <p>And apply certain <em>predicates</em> to captures:</p> -<div class="sourceCode" id="cb9"><pre class="sourceCode scheme"><code class="sourceCode scheme"><span id="cb9-1"><a href="#cb9-1" aria-hidden="true" tabindex="-1"></a>((let_declaration</span> +<div class="sourceCode" id="cb9"><pre +class="sourceCode scheme"><code class="sourceCode scheme"><span id="cb9-1"><a href="#cb9-1" aria-hidden="true" tabindex="-1"></a>((let_declaration</span> <span id="cb9-2"><a href="#cb9-2" aria-hidden="true" tabindex="-1"></a> pattern: (identifier) @my-capture</span> <span id="cb9-3"><a href="#cb9-3" aria-hidden="true" tabindex="-1"></a> value: (integer_literal))</span> <span id="cb9-4"><a href="#cb9-4" aria-hidden="true" tabindex="-1"></a> (<span class="sc">#e</span>q? @my-capture <span class="st">&quot;foo&quot;</span>))</span> @@ -445,8 +694,10 @@ H N E I <span id="cb9-8"><a href="#cb9-8" aria-hidden="true" tabindex="-1"></a></span> <span id="cb9-9"><a href="#cb9-9" aria-hidden="true" tabindex="-1"></a><span class="co">; and not:</span></span> <span id="cb9-10"><a href="#cb9-10" aria-hidden="true" tabindex="-1"></a><span class="co">; let bar = 2;</span></span></code></pre></div> -<p>The <code>#match?</code> predicate checks if a capture matches a regex:</p> -<div class="sourceCode" id="cb10"><pre class="sourceCode scheme"><code class="sourceCode scheme"><span id="cb10-1"><a href="#cb10-1" aria-hidden="true" tabindex="-1"></a>((let_declaration</span> +<p>The <code>#match?</code> predicate checks if a capture matches a +regex:</p> +<div class="sourceCode" id="cb10"><pre +class="sourceCode scheme"><code class="sourceCode scheme"><span id="cb10-1"><a href="#cb10-1" aria-hidden="true" tabindex="-1"></a>((let_declaration</span> <span id="cb10-2"><a href="#cb10-2" aria-hidden="true" tabindex="-1"></a> pattern: (identifier) @my-capture</span> <span id="cb10-3"><a href="#cb10-3" aria-hidden="true" tabindex="-1"></a> value: (integer_literal))</span> <span id="cb10-4"><a href="#cb10-4" aria-hidden="true" tabindex="-1"></a> (#match? @my-capture <span class="st">&quot;foo|bar&quot;</span>))</span> @@ -454,8 +705,10 @@ H N E I <span id="cb10-6"><a href="#cb10-6" aria-hidden="true" tabindex="-1"></a><span class="co">; matches both `foo` and `bar`:</span></span> <span id="cb10-7"><a href="#cb10-7" aria-hidden="true" tabindex="-1"></a><span class="co">; let foo = 2;</span></span> <span id="cb10-8"><a href="#cb10-8" aria-hidden="true" tabindex="-1"></a><span class="co">; let bar = 2;</span></span></code></pre></div> -<p>Exhibit indifference, as a stoic programmer would, with the <em>wildcard</em> pattern:</p> -<div class="sourceCode" id="cb11"><pre class="sourceCode scheme"><code class="sourceCode scheme"><span id="cb11-1"><a href="#cb11-1" aria-hidden="true" tabindex="-1"></a>(let_declaration</span> +<p>Exhibit indifference, as a stoic programmer would, with the +<em>wildcard</em> pattern:</p> +<div class="sourceCode" id="cb11"><pre +class="sourceCode scheme"><code class="sourceCode scheme"><span id="cb11-1"><a href="#cb11-1" aria-hidden="true" tabindex="-1"></a>(let_declaration</span> <span id="cb11-2"><a href="#cb11-2" aria-hidden="true" tabindex="-1"></a> pattern: (identifier)</span> <span id="cb11-3"><a href="#cb11-3" aria-hidden="true" tabindex="-1"></a> value: (<span class="op">_</span>))</span> <span id="cb11-4"><a href="#cb11-4" aria-hidden="true" tabindex="-1"></a> </span> @@ -463,73 +716,106 @@ H N E I <span id="cb11-6"><a href="#cb11-6" aria-hidden="true" tabindex="-1"></a><span class="co">; let foo = &quot;foo&quot;;</span></span> <span id="cb11-7"><a href="#cb11-7" aria-hidden="true" tabindex="-1"></a><span class="co">; let foo = 42;</span></span> <span id="cb11-8"><a href="#cb11-8" aria-hidden="true" tabindex="-1"></a><span class="co">; let foo = bar;</span></span></code></pre></div> -<p><a href="https://tree-sitter.github.io/tree-sitter/using-parsers#pattern-matching-with-queries">The documentation</a> does the tree-sitter query DSL more justice, but we now know enough to write our first lint.</p> +<p><a +href="https://tree-sitter.github.io/tree-sitter/using-parsers#pattern-matching-with-queries">The +documentation</a> does the tree-sitter query DSL more justice, but we +now know enough to write our first lint.</p> <h3 id="write-you-a-tree-sitter-lint">Write you a tree-sitter lint</h3> <p>Strings in <code>std::env</code> functions are error prone:</p> -<div class="sourceCode" id="cb12"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb12-1"><a href="#cb12-1" aria-hidden="true" tabindex="-1"></a><span class="pp">std::env::</span>remove_var(<span class="st">&quot;RUST_BACKTACE&quot;</span>)<span class="op">;</span></span> +<div class="sourceCode" id="cb12"><pre +class="sourceCode rust"><code class="sourceCode rust"><span id="cb12-1"><a href="#cb12-1" aria-hidden="true" tabindex="-1"></a><span class="pp">std::env::</span>remove_var(<span class="st">&quot;RUST_BACKTACE&quot;</span>)<span class="op">;</span></span> <span id="cb12-2"><a href="#cb12-2" aria-hidden="true" tabindex="-1"></a> <span class="co">// ^^^^ &quot;TACE&quot; instead of &quot;TRACE&quot;</span></span></code></pre></div> <p>I prefer this instead:</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" tabindex="-1"></a><span class="co">// somewhere in a module that is well spellchecked</span></span> +<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">// somewhere in a module that is well spellchecked</span></span> <span id="cb13-2"><a href="#cb13-2" aria-hidden="true" tabindex="-1"></a><span class="kw">static</span> BACKTRACE<span class="op">:</span> <span class="op">&amp;</span><span class="dt">str</span> <span class="op">=</span> <span class="st">&quot;RUST_BACKTRACE&quot;</span><span class="op">;</span></span> <span id="cb13-3"><a href="#cb13-3" aria-hidden="true" tabindex="-1"></a></span> <span id="cb13-4"><a href="#cb13-4" aria-hidden="true" tabindex="-1"></a><span class="co">// rest of the codebase</span></span> <span id="cb13-5"><a href="#cb13-5" aria-hidden="true" tabindex="-1"></a><span class="pp">std::env::</span>remove_var(BACKTRACE)<span class="op">;</span></span></code></pre></div> -<p>Let’s write a lint to find <code>std::env</code> functions that use strings. Put aside the effectiveness of this lint for the moment, and take a stab at writing a tree-sitter query. For reference, a function call like so:</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" tabindex="-1"></a>remove_var(<span class="st">&quot;RUST_BACKTRACE&quot;</span>)</span></code></pre></div> +<p>Let’s write a lint to find <code>std::env</code> functions that use +strings. Put aside the effectiveness of this lint for the moment, and +take a stab at writing a tree-sitter query. For reference, a function +call like so:</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" tabindex="-1"></a>remove_var(<span class="st">&quot;RUST_BACKTRACE&quot;</span>)</span></code></pre></div> <p>Produces the following S-expression:</p> -<div class="sourceCode" id="cb15"><pre class="sourceCode scheme"><code class="sourceCode scheme"><span id="cb15-1"><a href="#cb15-1" aria-hidden="true" tabindex="-1"></a>(call_expression</span> +<div class="sourceCode" id="cb15"><pre +class="sourceCode scheme"><code class="sourceCode scheme"><span id="cb15-1"><a href="#cb15-1" aria-hidden="true" tabindex="-1"></a>(call_expression</span> <span id="cb15-2"><a href="#cb15-2" aria-hidden="true" tabindex="-1"></a> function: (identifier)</span> <span id="cb15-3"><a href="#cb15-3" aria-hidden="true" tabindex="-1"></a> arguments: (arguments (string_literal)))</span></code></pre></div> <p>We are definitely looking for a <code>call_expression</code>:</p> -<div class="sourceCode" id="cb16"><pre class="sourceCode scheme"><code class="sourceCode scheme"><span id="cb16-1"><a href="#cb16-1" aria-hidden="true" tabindex="-1"></a>(call_expression) @raise</span></code></pre></div> -<p>Whose function name matches <code>std::env::var</code> or <code>std::env::remove_var</code> at the very least (I know, I know, this isn’t the most optimal regex):</p> -<div class="sourceCode" id="cb17"><pre class="sourceCode scheme"><code class="sourceCode scheme"><span id="cb17-1"><a href="#cb17-1" aria-hidden="true" tabindex="-1"></a>((call_expression</span> +<div class="sourceCode" id="cb16"><pre +class="sourceCode scheme"><code class="sourceCode scheme"><span id="cb16-1"><a href="#cb16-1" aria-hidden="true" tabindex="-1"></a>(call_expression) @raise</span></code></pre></div> +<p>Whose function name matches <code>std::env::var</code> or +<code>std::env::remove_var</code> at the very least (I know, I know, +this isn’t the most optimal regex):</p> +<div class="sourceCode" id="cb17"><pre +class="sourceCode scheme"><code class="sourceCode scheme"><span id="cb17-1"><a href="#cb17-1" aria-hidden="true" tabindex="-1"></a>((call_expression</span> <span id="cb17-2"><a href="#cb17-2" aria-hidden="true" tabindex="-1"></a> function: (<span class="op">_</span>) @fn-name) @raise</span> <span id="cb17-3"><a href="#cb17-3" aria-hidden="true" tabindex="-1"></a> (#match? @fn-name <span class="st">&quot;std::env::(var|remove_var)&quot;</span>))</span></code></pre></div> <p>Let’s turn that <code>std::</code> prefix optional:</p> -<div class="sourceCode" id="cb18"><pre class="sourceCode scheme"><code class="sourceCode scheme"><span id="cb18-1"><a href="#cb18-1" aria-hidden="true" tabindex="-1"></a>((call_expression</span> +<div class="sourceCode" id="cb18"><pre +class="sourceCode scheme"><code class="sourceCode scheme"><span id="cb18-1"><a href="#cb18-1" aria-hidden="true" tabindex="-1"></a>((call_expression</span> <span id="cb18-2"><a href="#cb18-2" aria-hidden="true" tabindex="-1"></a> function: (<span class="op">_</span>) @fn-name) @raise</span> <span id="cb18-3"><a href="#cb18-3" aria-hidden="true" tabindex="-1"></a> (#match? @fn-name <span class="st">&quot;(std::|)env::(var|remove_var)&quot;</span>))</span></code></pre></div> <p>And ensure that <code>arguments</code> is a string:</p> -<div class="sourceCode" id="cb19"><pre class="sourceCode scheme"><code class="sourceCode scheme"><span id="cb19-1"><a href="#cb19-1" aria-hidden="true" tabindex="-1"></a>((call_expression</span> +<div class="sourceCode" id="cb19"><pre +class="sourceCode scheme"><code class="sourceCode scheme"><span id="cb19-1"><a href="#cb19-1" aria-hidden="true" tabindex="-1"></a>((call_expression</span> <span id="cb19-2"><a href="#cb19-2" aria-hidden="true" tabindex="-1"></a> function: (<span class="op">_</span>) @fn-name</span> <span id="cb19-3"><a href="#cb19-3" aria-hidden="true" tabindex="-1"></a> arguments: (arguments (string_literal)))</span> <span id="cb19-4"><a href="#cb19-4" aria-hidden="true" tabindex="-1"></a> (#match? @fn-name <span class="st">&quot;(std::|)env::(var|remove_var)&quot;</span>))</span></code></pre></div> <h3 id="running-our-linter">Running our linter</h3> -<p>We could always plug our query into the web playground, but let’s go a step further:</p> -<div class="sourceCode" id="cb20"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb20-1"><a href="#cb20-1" aria-hidden="true" tabindex="-1"></a><span class="ex">cargo</span> new <span class="at">--bin</span> toy-lint</span></code></pre></div> -<p>Add <code>tree-sitter</code> and <code>tree-sitter-rust</code> to your dependencies:</p> -<div class="sourceCode" id="cb21"><pre class="sourceCode toml"><code class="sourceCode toml"><span id="cb21-1"><a href="#cb21-1" aria-hidden="true" tabindex="-1"></a><span class="co"># within Cargo.toml</span></span> +<p>We could always plug our query into the web playground, but let’s go +a step further:</p> +<div class="sourceCode" id="cb20"><pre +class="sourceCode bash"><code class="sourceCode bash"><span id="cb20-1"><a href="#cb20-1" aria-hidden="true" tabindex="-1"></a><span class="ex">cargo</span> new <span class="at">--bin</span> toy-lint</span></code></pre></div> +<p>Add <code>tree-sitter</code> and <code>tree-sitter-rust</code> to +your dependencies:</p> +<div class="sourceCode" id="cb21"><pre +class="sourceCode toml"><code class="sourceCode toml"><span id="cb21-1"><a href="#cb21-1" aria-hidden="true" tabindex="-1"></a><span class="co"># within Cargo.toml</span></span> <span id="cb21-2"><a href="#cb21-2" aria-hidden="true" tabindex="-1"></a><span class="kw">[</span><span class="dt">dependencies</span><span class="kw">]</span></span> <span id="cb21-3"><a href="#cb21-3" aria-hidden="true" tabindex="-1"></a><span class="dt">tree-sitter</span> <span class="op">=</span> <span class="st">&quot;0.20&quot;</span></span> <span id="cb21-4"><a href="#cb21-4" aria-hidden="true" tabindex="-1"></a></span> <span id="cb21-5"><a href="#cb21-5" aria-hidden="true" tabindex="-1"></a><span class="kw">[</span><span class="dt">dependencies</span><span class="kw">.</span><span class="dt">tree-sitter-rust</span><span class="kw">]</span></span> <span id="cb21-6"><a href="#cb21-6" aria-hidden="true" tabindex="-1"></a><span class="dt">git</span> <span class="op">=</span> <span class="st">&quot;https://github.com/tree-sitter/tree-sitter-rust&quot;</span></span></code></pre></div> -<p>Let’s load in some Rust code to work with. As <a href="https://en.wikipedia.org/wiki/Self-reference">an ode to Gödel</a> (G<code>ode</code>l?), why not load in our linter itself:</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" tabindex="-1"></a><span class="kw">fn</span> main() <span class="op">{</span></span> +<p>Let’s load in some Rust code to work with. As <a +href="https://en.wikipedia.org/wiki/Self-reference">an ode to Gödel</a> +(G<code>ode</code>l?), why not load in our linter itself:</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" tabindex="-1"></a><span class="kw">fn</span> main() <span class="op">{</span></span> <span id="cb22-2"><a href="#cb22-2" aria-hidden="true" tabindex="-1"></a> <span class="kw">let</span> src <span class="op">=</span> <span class="pp">include_str!</span>(<span class="st">&quot;main.rs&quot;</span>)<span class="op">;</span></span> <span id="cb22-3"><a href="#cb22-3" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code></pre></div> -<p>Most tree-sitter APIs require a reference to a <code>Language</code> struct, we will be working with Rust if you haven’t already guessed:</p> -<div class="sourceCode" id="cb23"><pre class="sourceCode rust"><code class="sourceCode rust"><span id="cb23-1"><a href="#cb23-1" aria-hidden="true" tabindex="-1"></a><span class="kw">use</span> <span class="pp">tree_sitter::</span>Language<span class="op">;</span></span> +<p>Most tree-sitter APIs require a reference to a <code>Language</code> +struct, we will be working with Rust if you haven’t already guessed:</p> +<div class="sourceCode" id="cb23"><pre +class="sourceCode rust"><code class="sourceCode rust"><span id="cb23-1"><a href="#cb23-1" aria-hidden="true" tabindex="-1"></a><span class="kw">use</span> <span class="pp">tree_sitter::</span>Language<span class="op">;</span></span> <span id="cb23-2"><a href="#cb23-2" aria-hidden="true" tabindex="-1"></a></span> <span id="cb23-3"><a href="#cb23-3" aria-hidden="true" tabindex="-1"></a><span class="kw">let</span> rust_lang<span class="op">:</span> Language <span class="op">=</span> <span class="pp">tree_sitter_rust::</span>language()<span class="op">;</span></span></code></pre></div> <p>Enough scaffolding, let’s parse some Rust:</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" tabindex="-1"></a><span class="kw">use</span> <span class="pp">tree_sitter::</span>Parser<span class="op">;</span></span> +<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">use</span> <span class="pp">tree_sitter::</span>Parser<span class="op">;</span></span> <span id="cb24-2"><a href="#cb24-2" aria-hidden="true" tabindex="-1"></a></span> <span id="cb24-3"><a href="#cb24-3" aria-hidden="true" tabindex="-1"></a><span class="kw">let</span> <span class="kw">mut</span> parser <span class="op">=</span> <span class="pp">Parser::</span>new()<span class="op">;</span></span> <span id="cb24-4"><a href="#cb24-4" aria-hidden="true" tabindex="-1"></a>parser<span class="op">.</span>set_language(rust_lang)<span class="op">.</span>unwrap()<span class="op">;</span></span> <span id="cb24-5"><a href="#cb24-5" aria-hidden="true" tabindex="-1"></a></span> <span id="cb24-6"><a href="#cb24-6" aria-hidden="true" tabindex="-1"></a><span class="kw">let</span> parse_tree <span class="op">=</span> parser<span class="op">.</span>parse(<span class="op">&amp;</span>src<span class="op">,</span> <span class="cn">None</span>)<span class="op">.</span>unwrap()<span class="op">;</span></span></code></pre></div> -<p>The second argument to <code>Parser::parse</code> may be of interest. Tree-sitter has this cool feature that allows for quick reparsing of existing parse trees if they contain edits. If you do happen to want to reparse a source file, you can pass in the old tree:</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" tabindex="-1"></a><span class="co">// if you wish to reparse instead of parse</span></span> +<p>The second argument to <code>Parser::parse</code> may be of interest. +Tree-sitter has this cool feature that allows for quick reparsing of +existing parse trees if they contain edits. If you do happen to want to +reparse a source file, you can pass in the old tree:</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" tabindex="-1"></a><span class="co">// if you wish to reparse instead of parse</span></span> <span id="cb25-2"><a href="#cb25-2" aria-hidden="true" tabindex="-1"></a>old_tree<span class="op">.</span>edit(<span class="co">/* redacted */</span>)<span class="op">;</span></span> <span id="cb25-3"><a href="#cb25-3" aria-hidden="true" tabindex="-1"></a></span> <span id="cb25-4"><a href="#cb25-4" aria-hidden="true" tabindex="-1"></a><span class="co">// generate shiny new reparsed tree</span></span> <span id="cb25-5"><a href="#cb25-5" aria-hidden="true" tabindex="-1"></a><span class="kw">let</span> new_tree <span class="op">=</span> parser<span class="op">.</span>parse(<span class="op">&amp;</span>src<span class="op">,</span> <span class="cn">Some</span>(old_tree))<span class="op">.</span>unwrap()</span></code></pre></div> -<p>Anyhow (<a href="http://github.com/dtolnay/anyhow">hah!</a>), now that we have a parse tree, we can inspect it:</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" tabindex="-1"></a><span class="pp">println!</span>(<span class="st">&quot;{}&quot;</span><span class="op">,</span> parse_tree<span class="op">.</span>root_node()<span class="op">.</span>to_sexp())<span class="op">;</span></span></code></pre></div> +<p>Anyhow (<a href="http://github.com/dtolnay/anyhow">hah!</a>), now +that we have a parse tree, we can inspect it:</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" tabindex="-1"></a><span class="pp">println!</span>(<span class="st">&quot;{}&quot;</span><span class="op">,</span> parse_tree<span class="op">.</span>root_node()<span class="op">.</span>to_sexp())<span class="op">;</span></span></code></pre></div> <p>Or better yet, run a query on it:</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" tabindex="-1"></a><span class="kw">use</span> <span class="pp">tree_sitter::</span>Query<span class="op">;</span></span> +<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">use</span> <span class="pp">tree_sitter::</span>Query<span class="op">;</span></span> <span id="cb27-2"><a href="#cb27-2" aria-hidden="true" tabindex="-1"></a></span> <span id="cb27-3"><a href="#cb27-3" aria-hidden="true" tabindex="-1"></a><span class="kw">let</span> query <span class="op">=</span> <span class="pp">Query::</span>new(</span> <span id="cb27-4"><a href="#cb27-4" aria-hidden="true" tabindex="-1"></a> rust_lang<span class="op">,</span></span> @@ -541,8 +827,11 @@ H N E I <span id="cb27-10"><a href="#cb27-10" aria-hidden="true" tabindex="-1"></a><span class="st"> &quot;#</span></span> <span id="cb27-11"><a href="#cb27-11" aria-hidden="true" tabindex="-1"></a>)</span> <span id="cb27-12"><a href="#cb27-12" aria-hidden="true" tabindex="-1"></a><span class="op">.</span>unwrap()<span class="op">;</span></span></code></pre></div> -<p>A <code>QueryCursor</code> is tree-sitter’s way of maintaining state as we iterate through the matches or captures produced by running a query on the parse tree. Observe:</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" tabindex="-1"></a><span class="kw">use</span> <span class="pp">tree_sitter::</span>QueryCursor<span class="op">;</span></span> +<p>A <code>QueryCursor</code> is tree-sitter’s way of maintaining state +as we iterate through the matches or captures produced by running a +query on the parse tree. Observe:</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" tabindex="-1"></a><span class="kw">use</span> <span class="pp">tree_sitter::</span>QueryCursor<span class="op">;</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">let</span> <span class="kw">mut</span> query_cursor <span class="op">=</span> <span class="pp">QueryCursor::</span>new()<span class="op">;</span></span> <span id="cb28-4"><a href="#cb28-4" aria-hidden="true" tabindex="-1"></a><span class="kw">let</span> all_matches <span class="op">=</span> query_cursor<span class="op">.</span>matches(</span> @@ -550,15 +839,22 @@ H N E I <span id="cb28-6"><a href="#cb28-6" aria-hidden="true" tabindex="-1"></a> parse_tree<span class="op">.</span>root_node()<span class="op">,</span></span> <span id="cb28-7"><a href="#cb28-7" aria-hidden="true" tabindex="-1"></a> src<span class="op">.</span>as_bytes()<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>We begin by passing our query to the cursor, followed by the “root node”, which is another way of saying, “start from the top”, and lastly, the source itself. If you have already taken a look at the C API, you will notice that the last argument, the source (known as the <code>TextProvider</code>), is not required. The Rust bindings seem to require this argument to provide predicate functionality such as <code>#match?</code> and <code>#eq?</code>.</p> +<p>We begin by passing our query to the cursor, followed by the “root +node”, which is another way of saying, “start from the top”, and lastly, +the source itself. If you have already taken a look at the C API, you +will notice that the last argument, the source (known as the +<code>TextProvider</code>), is not required. The Rust bindings seem to +require this argument to provide predicate functionality such as +<code>#match?</code> and <code>#eq?</code>.</p> <p>Do something with the matches:</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" tabindex="-1"></a><span class="co">// get the index of the capture named &quot;raise&quot;</span></span> +<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">// get the index of the capture named &quot;raise&quot;</span></span> <span id="cb29-2"><a href="#cb29-2" aria-hidden="true" tabindex="-1"></a><span class="kw">let</span> raise_idx <span class="op">=</span> query<span class="op">.</span>capture_index_for_name(<span class="st">&quot;raise&quot;</span>)<span class="op">.</span>unwrap()<span class="op">;</span></span> <span id="cb29-3"><a href="#cb29-3" aria-hidden="true" tabindex="-1"></a></span> -<span id="cb29-4"><a href="#cb29-4" aria-hidden="true" tabindex="-1"></a><span class="kw">for</span> each_match <span class="kw">in</span> all_matches <span class="op">{</span></span> +<span id="cb29-4"><a href="#cb29-4" aria-hidden="true" tabindex="-1"></a><span class="cf">for</span> each_match <span class="kw">in</span> all_matches <span class="op">{</span></span> <span id="cb29-5"><a href="#cb29-5" aria-hidden="true" tabindex="-1"></a> <span class="co">// iterate over all captures called &quot;raise&quot;</span></span> <span id="cb29-6"><a href="#cb29-6" aria-hidden="true" tabindex="-1"></a> <span class="co">// ignore captures such as &quot;fn-name&quot;</span></span> -<span id="cb29-7"><a href="#cb29-7" aria-hidden="true" tabindex="-1"></a> <span class="kw">for</span> capture <span class="kw">in</span> each_match</span> +<span id="cb29-7"><a href="#cb29-7" aria-hidden="true" tabindex="-1"></a> <span class="cf">for</span> capture <span class="kw">in</span> each_match</span> <span id="cb29-8"><a href="#cb29-8" aria-hidden="true" tabindex="-1"></a> <span class="op">.</span>captures</span> <span id="cb29-9"><a href="#cb29-9" aria-hidden="true" tabindex="-1"></a> <span class="op">.</span>iter()</span> <span id="cb29-10"><a href="#cb29-10" aria-hidden="true" tabindex="-1"></a> <span class="op">.</span>filter(<span class="op">|</span>c<span class="op">|</span> c<span class="op">.</span>idx <span class="op">==</span> raise_idx)</span> @@ -573,8 +869,10 @@ H N E I <span id="cb29-19"><a href="#cb29-19" aria-hidden="true" tabindex="-1"></a> )<span class="op">;</span></span> <span id="cb29-20"><a href="#cb29-20" aria-hidden="true" tabindex="-1"></a> <span class="op">}</span></span> <span id="cb29-21"><a href="#cb29-21" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code></pre></div> -<p>Lastly, add the following line to your source code, to get the linter to catch something:</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" tabindex="-1"></a><span class="pp">env::</span>remove_var(<span class="st">&quot;RUST_BACKTRACE&quot;</span>)<span class="op">;</span></span></code></pre></div> +<p>Lastly, add the following line to your source code, to get the linter +to catch something:</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" tabindex="-1"></a><span class="pp">env::</span>remove_var(<span class="st">&quot;RUST_BACKTRACE&quot;</span>)<span class="op">;</span></span></code></pre></div> <p>And <code>cargo run</code>:</p> <pre class="shell"><code>λ cargo run Compiling toy-lint v0.1.0 (/redacted/path/to/toy-lint) @@ -583,17 +881,33 @@ H N E I [Line: 40, Col: 4] Offending source code: `env::remove_var(&quot;RUST_BACKTRACE&quot;)`</code></pre> <p>Thank you tree-sitter!</p> <h3 id="bonus">Bonus</h3> -<p>Keen readers will notice that I avoided <code>std::env::set_var</code>. Because <code>set_var</code> is called with two arguments, a “key” and a “value”, unlike <code>env::var</code> and <code>env::remove_var</code>. As a result, it requires more juggling:</p> -<div class="sourceCode" id="cb32"><pre class="sourceCode scheme"><code class="sourceCode scheme"><span id="cb32-1"><a href="#cb32-1" aria-hidden="true" tabindex="-1"></a>((call_expression</span> +<p>Keen readers will notice that I avoided +<code>std::env::set_var</code>. Because <code>set_var</code> is called +with two arguments, a “key” and a “value”, unlike <code>env::var</code> +and <code>env::remove_var</code>. As a result, it requires more +juggling:</p> +<div class="sourceCode" id="cb32"><pre +class="sourceCode scheme"><code class="sourceCode scheme"><span id="cb32-1"><a href="#cb32-1" aria-hidden="true" tabindex="-1"></a>((call_expression</span> <span id="cb32-2"><a href="#cb32-2" aria-hidden="true" tabindex="-1"></a> function: (<span class="op">_</span>) @fn-name</span> <span id="cb32-3"><a href="#cb32-3" aria-hidden="true" tabindex="-1"></a> arguments: (arguments <span class="op">.</span> (string_literal)<span class="op">?</span> <span class="op">.</span> (string_literal) <span class="op">.</span>)) @raise</span> <span id="cb32-4"><a href="#cb32-4" aria-hidden="true" tabindex="-1"></a> (#match? @fn-name <span class="st">&quot;(std::|)env::(var|remove_var|set_var)&quot;</span>))</span></code></pre></div> -<p>The interesting part of this query is the humble <code>.</code>, the <em>anchor</em> operator. Anchors help constrain child nodes in certain ways. In this case, it ensures that we match exactly two <code>string_literal</code>s who are siblings or exactly one <code>string_literal</code> with no siblings. Unfortunately, this query also matches the following invalid Rust code:</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" tabindex="-1"></a><span class="co">// remove_var accepts only 1 arg!</span></span> +<p>The interesting part of this query is the humble <code>.</code>, the +<em>anchor</em> operator. Anchors help constrain child nodes in certain +ways. In this case, it ensures that we match exactly two +<code>string_literal</code>s who are siblings or exactly one +<code>string_literal</code> with no siblings. Unfortunately, this query +also matches the following invalid Rust code:</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" tabindex="-1"></a><span class="co">// remove_var accepts only 1 arg!</span></span> <span id="cb33-2"><a href="#cb33-2" aria-hidden="true" tabindex="-1"></a><span class="pp">std::env::</span>remove_var(<span class="st">&quot;RUST_BACKTRACE&quot;</span><span class="op">,</span> <span class="st">&quot;1&quot;</span>)<span class="op">;</span></span></code></pre></div> <h3 id="notes">Notes</h3> -<p>All-in-all, the query DSL does a great job in lowering the bar to writing language tools. The knowledge gained from mastering the query DSL can be applied to other languages that have tree-sitter grammars too. This query detects <code>to_json</code> methods that do not accept additional arguments, in Ruby:</p> -<div class="sourceCode" id="cb34"><pre class="sourceCode scheme"><code class="sourceCode scheme"><span id="cb34-1"><a href="#cb34-1" aria-hidden="true" tabindex="-1"></a>((method</span> +<p>All-in-all, the query DSL does a great job in lowering the bar to +writing language tools. The knowledge gained from mastering the query +DSL can be applied to other languages that have tree-sitter grammars +too. This query detects <code>to_json</code> methods that do not accept +additional arguments, in Ruby:</p> +<div class="sourceCode" id="cb34"><pre +class="sourceCode scheme"><code class="sourceCode scheme"><span id="cb34-1"><a href="#cb34-1" aria-hidden="true" tabindex="-1"></a>((method</span> <span id="cb34-2"><a href="#cb34-2" aria-hidden="true" tabindex="-1"></a> name: (identifier) @fn</span> <span id="cb34-3"><a href="#cb34-3" aria-hidden="true" tabindex="-1"></a> !parameters)</span> <span id="cb34-4"><a href="#cb34-4" aria-hidden="true" tabindex="-1"></a> (<span class="sc">#i</span>s? @fn <span class="st">&quot;to_json&quot;</span>))</span></code></pre></div> @@ -603,13 +917,25 @@ H N E I Novice Nix: Flake Templates -<p>Flakes are very handy to setup entirely pure, project-specific dependencies (not just dependencies, but build steps, shell environments and more) in a declarative way. Writing Flake expressions can get repetitive though, oftentimes, you’d much rather start off with a skeleton. Luckily, <code>nix</code> already supports templates!</p> -<p>You might already be familiar with <code>nix flake init</code>, that drops a “default” flake expression into your current working directory. If you head over to the manpage:</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" tabindex="-1"></a><span class="ex">nix</span> flake init <span class="at">--help</span></span></code></pre></div> -<p>You will read that <code>nix flake init</code> creates a flake using the “default template”. Additionally, you can create a flake from a specific template by passing the <code>-t</code> flag. Where does this default originate from?</p> +<p>Flakes are very handy to setup entirely pure, project-specific +dependencies (not just dependencies, but build steps, shell environments +and more) in a declarative way. Writing Flake expressions can get +repetitive though, oftentimes, you’d much rather start off with a +skeleton. Luckily, <code>nix</code> already supports templates!</p> +<p>You might already be familiar with <code>nix flake init</code>, that +drops a “default” flake expression into your current working directory. +If you head over to the manpage:</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" tabindex="-1"></a><span class="ex">nix</span> flake init <span class="at">--help</span></span></code></pre></div> +<p>You will read that <code>nix flake init</code> creates a flake using +the “default template”. Additionally, you can create a flake from a +specific template by passing the <code>-t</code> flag. Where does this +default originate from?</p> <h2 id="flake-registries">Flake Registries</h2> -<p>Quick detour into registries! Registries are a way to alias popular flakes using identifiers:</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" tabindex="-1"></a><span class="co"># list a few predefined registries</span></span> +<p>Quick detour into registries! Registries are a way to alias popular +flakes using identifiers:</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" tabindex="-1"></a><span class="co"># list a few predefined registries</span></span> <span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> nix registry list</span> <span id="cb2-3"><a href="#cb2-3" aria-hidden="true" tabindex="-1"></a><span class="bu">.</span> . . </span> <span id="cb2-4"><a href="#cb2-4" aria-hidden="true" tabindex="-1"></a><span class="ex">global</span> flake:nixpkgs github:NixOS/nixpkgs</span> @@ -627,8 +953,11 @@ H N E I <span id="cb2-16"><a href="#cb2-16" aria-hidden="true" tabindex="-1"></a></span> <span id="cb2-17"><a href="#cb2-17" aria-hidden="true" tabindex="-1"></a><span class="co"># which is short for</span></span> <span id="cb2-18"><a href="#cb2-18" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> nix flake show git+https://github.com/tweag/nickel</span></code></pre></div> -<p>You might notice a registry called <code>templates</code> aliased to <code>github:NixOS/templates</code>. Take a peek with <code>nix flake show</code>:</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" tabindex="-1"></a><span class="ex">$</span> nix flake show templates</span> +<p>You might notice a registry called <code>templates</code> aliased to +<code>github:NixOS/templates</code>. Take a peek with +<code>nix flake show</code>:</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" tabindex="-1"></a><span class="ex">$</span> nix flake show templates</span> <span id="cb3-2"><a href="#cb3-2" aria-hidden="true" tabindex="-1"></a><span class="ex">github:NixOS/templates/79f48a7b822f35c068c5e235da2e9fbd154cecee</span></span> <span id="cb3-3"><a href="#cb3-3" aria-hidden="true" tabindex="-1"></a><span class="ex">├───defaultTemplate:</span> template: A very basic flake</span> <span id="cb3-4"><a href="#cb3-4" aria-hidden="true" tabindex="-1"></a><span class="ex">└───templates</span></span> @@ -637,8 +966,12 @@ H N E I <span id="cb3-7"><a href="#cb3-7" aria-hidden="true" tabindex="-1"></a> <span class="ex">├───rust-web-server:</span> template: A Rust web server including a NixOS module</span> <span id="cb3-8"><a href="#cb3-8" aria-hidden="true" tabindex="-1"></a> <span class="ex">├───simpleContainer:</span> template: A NixOS container running apache-httpd</span> <span id="cb3-9"><a href="#cb3-9" aria-hidden="true" tabindex="-1"></a> <span class="ex">└───trivial:</span> template: A very basic flake</span></code></pre></div> -<p>Aha! There is a flake output called <code>defaultTemplate</code>. This is the template being sourced when you run <code>nix flake init</code>. Astute readers may conclude the following:</p> -<div class="sourceCode" id="cb4"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> nix flake init</span> +<p>Aha! There is a flake output called <code>defaultTemplate</code>. +This is the template being sourced when you run +<code>nix flake init</code>. Astute readers may conclude the +following:</p> +<div class="sourceCode" id="cb4"><pre +class="sourceCode bash"><code class="sourceCode bash"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> nix flake init</span> <span id="cb4-2"><a href="#cb4-2" aria-hidden="true" tabindex="-1"></a></span> <span id="cb4-3"><a href="#cb4-3" aria-hidden="true" tabindex="-1"></a><span class="co"># is equivalent to</span></span> <span id="cb4-4"><a href="#cb4-4" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> nix flake init <span class="at">-t</span> templates#defaultTemplate</span> @@ -649,7 +982,8 @@ H N E I <span id="cb4-9"><a href="#cb4-9" aria-hidden="true" tabindex="-1"></a><span class="co"># which is short for</span></span> <span id="cb4-10"><a href="#cb4-10" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> nix flake init <span class="at">-t</span> git+https://github.com/NixOS/templates#defaultTemplate</span></code></pre></div> <p>Similarly, the other templates can be accessed via:</p> -<div class="sourceCode" id="cb5"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb5-1"><a href="#cb5-1" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> nix flake init <span class="at">-t</span> templates#c-hello</span> +<div class="sourceCode" id="cb5"><pre +class="sourceCode bash"><code class="sourceCode bash"><span id="cb5-1"><a href="#cb5-1" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> nix flake init <span class="at">-t</span> templates#c-hello</span> <span id="cb5-2"><a href="#cb5-2" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> nix flake init <span class="at">-t</span> templates#simpleContainer</span> <span id="cb5-3"><a href="#cb5-3" aria-hidden="true" tabindex="-1"></a><span class="co"># I think you get the drift ...</span></span></code></pre></div> <h2 id="rolling-your-own-templates">Rolling your own templates</h2> @@ -657,38 +991,52 @@ H N E I <ul> <li>create a flake with a <code>templates</code> output</li> <li>populate our template directories with content</li> -<li>(<strong>optionally</strong>) alias our custom templates flake to an identifier using registries, for easier access</li> +<li>(<strong>optionally</strong>) alias our custom templates flake to an +identifier using registries, for easier access</li> </ul> -<p>Start off by creating a directory to store your templates in (we will be converting this to a registry later):</p> -<div class="sourceCode" id="cb6"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> mkdir ~/mytemplates</span></code></pre></div> -<p>A flake that exposes a “template” as its output looks something like this:</p> -<div class="sourceCode" id="cb7"><pre class="sourceCode nix"><code class="sourceCode bash"><span id="cb7-1"><a href="#cb7-1" aria-hidden="true" tabindex="-1"></a><span class="co"># inside ~/mytemplates/flake.nix</span></span> +<p>Start off by creating a directory to store your templates in (we will +be converting this to a registry later):</p> +<div class="sourceCode" id="cb6"><pre +class="sourceCode bash"><code class="sourceCode bash"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> mkdir ~/mytemplates</span></code></pre></div> +<p>A flake that exposes a “template” as its output looks something like +this:</p> +<div class="sourceCode" id="cb7"><pre +class="sourceCode nix"><code class="sourceCode nix"><span id="cb7-1"><a href="#cb7-1" aria-hidden="true" tabindex="-1"></a><span class="co"># inside ~/mytemplates/flake.nix</span></span> <span id="cb7-2"><a href="#cb7-2" aria-hidden="true" tabindex="-1"></a></span> -<span id="cb7-3"><a href="#cb7-3" aria-hidden="true" tabindex="-1"></a><span class="kw">{</span></span> -<span id="cb7-4"><a href="#cb7-4" aria-hidden="true" tabindex="-1"></a> <span class="ex">description</span> = <span class="st">&quot;Pepper&#39;s flake templates&quot;</span><span class="kw">;</span></span> +<span id="cb7-3"><a href="#cb7-3" aria-hidden="true" tabindex="-1"></a><span class="op">{</span></span> +<span id="cb7-4"><a href="#cb7-4" aria-hidden="true" tabindex="-1"></a> <span class="va">description</span> <span class="op">=</span> <span class="st">&quot;Pepper&#39;s flake templates&quot;</span><span class="op">;</span></span> <span id="cb7-5"><a href="#cb7-5" aria-hidden="true" tabindex="-1"></a></span> -<span id="cb7-6"><a href="#cb7-6" aria-hidden="true" tabindex="-1"></a> <span class="ex">outputs</span> = { self, ... }: {</span> -<span id="cb7-7"><a href="#cb7-7" aria-hidden="true" tabindex="-1"></a> <span class="ex">templates</span> = {</span> -<span id="cb7-8"><a href="#cb7-8" aria-hidden="true" tabindex="-1"></a> <span class="ex">latex-report</span> = {</span> -<span id="cb7-9"><a href="#cb7-9" aria-hidden="true" tabindex="-1"></a> <span class="ex">path</span> = ./latex-report-template<span class="kw">;</span></span> -<span id="cb7-10"><a href="#cb7-10" aria-hidden="true" tabindex="-1"></a> <span class="ex">description</span> = <span class="st">&quot;A latex whitepaper project&quot;</span><span class="kw">;</span></span> -<span id="cb7-11"><a href="#cb7-11" aria-hidden="true" tabindex="-1"></a> <span class="kw">};</span></span> -<span id="cb7-12"><a href="#cb7-12" aria-hidden="true" tabindex="-1"></a> <span class="ex">rust-hello</span> = {</span> -<span id="cb7-13"><a href="#cb7-13" aria-hidden="true" tabindex="-1"></a> <span class="ex">path</span> = ./rust-hello-template<span class="kw">;</span></span> -<span id="cb7-14"><a href="#cb7-14" aria-hidden="true" tabindex="-1"></a> <span class="ex">description</span> = <span class="st">&quot;Simple Hello World in Rust&quot;</span><span class="kw">;</span></span> -<span id="cb7-15"><a href="#cb7-15" aria-hidden="true" tabindex="-1"></a> <span class="er">}</span><span class="kw">;</span></span> -<span id="cb7-16"><a href="#cb7-16" aria-hidden="true" tabindex="-1"></a> <span class="er">}</span><span class="kw">;</span></span> -<span id="cb7-17"><a href="#cb7-17" aria-hidden="true" tabindex="-1"></a> <span class="er">}</span><span class="kw">;</span></span> -<span id="cb7-18"><a href="#cb7-18" aria-hidden="true" tabindex="-1"></a><span class="er">}</span></span></code></pre></div> -<p>The <code>path</code> attribute to each template is what gets copied over when you initialize a flake. Running <code>nix flake init -t .#latex-report</code> will initialize the current directory with the contents of <code>./latex-report-template</code> (we are yet to populate these directories).</p> -<p>The output of <code>nix flake show</code> should be something like:</p> -<div class="sourceCode" id="cb8"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> nix flake show</span> +<span id="cb7-6"><a href="#cb7-6" aria-hidden="true" tabindex="-1"></a> <span class="va">outputs</span> <span class="op">=</span> <span class="op">{</span> <span class="va">self</span><span class="op">,</span> <span class="op">...</span> <span class="op">}</span>: <span class="op">{</span></span> +<span id="cb7-7"><a href="#cb7-7" aria-hidden="true" tabindex="-1"></a> <span class="va">templates</span> <span class="op">=</span> <span class="op">{</span></span> +<span id="cb7-8"><a href="#cb7-8" aria-hidden="true" tabindex="-1"></a> <span class="va">latex-report</span> <span class="op">=</span> <span class="op">{</span></span> +<span id="cb7-9"><a href="#cb7-9" aria-hidden="true" tabindex="-1"></a> <span class="va">path</span> <span class="op">=</span> <span class="ss">./latex-report-template</span><span class="op">;</span></span> +<span id="cb7-10"><a href="#cb7-10" aria-hidden="true" tabindex="-1"></a> <span class="va">description</span> <span class="op">=</span> <span class="st">&quot;A latex whitepaper project&quot;</span><span class="op">;</span></span> +<span id="cb7-11"><a href="#cb7-11" aria-hidden="true" tabindex="-1"></a> <span class="op">};</span></span> +<span id="cb7-12"><a href="#cb7-12" aria-hidden="true" tabindex="-1"></a> <span class="va">rust-hello</span> <span class="op">=</span> <span class="op">{</span></span> +<span id="cb7-13"><a href="#cb7-13" aria-hidden="true" tabindex="-1"></a> <span class="va">path</span> <span class="op">=</span> <span class="ss">./rust-hello-template</span><span class="op">;</span></span> +<span id="cb7-14"><a href="#cb7-14" aria-hidden="true" tabindex="-1"></a> <span class="va">description</span> <span class="op">=</span> <span class="st">&quot;Simple Hello World in Rust&quot;</span><span class="op">;</span></span> +<span id="cb7-15"><a href="#cb7-15" aria-hidden="true" tabindex="-1"></a> <span class="op">};</span></span> +<span id="cb7-16"><a href="#cb7-16" aria-hidden="true" tabindex="-1"></a> <span class="op">};</span></span> +<span id="cb7-17"><a href="#cb7-17" aria-hidden="true" tabindex="-1"></a> <span class="op">};</span></span> +<span id="cb7-18"><a href="#cb7-18" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code></pre></div> +<p>The <code>path</code> attribute to each template is what gets copied +over when you initialize a flake. Running +<code>nix flake init -t .#latex-report</code> will initialize the +current directory with the contents of +<code>./latex-report-template</code> (we are yet to populate these +directories).</p> +<p>The output of <code>nix flake show</code> should be something +like:</p> +<div class="sourceCode" id="cb8"><pre +class="sourceCode bash"><code class="sourceCode bash"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> nix flake show</span> <span id="cb8-2"><a href="#cb8-2" aria-hidden="true" tabindex="-1"></a><span class="ex">path:/home/np/code/nix-stuff/template-tests?narHash=sha256-{...}</span></span> <span id="cb8-3"><a href="#cb8-3" aria-hidden="true" tabindex="-1"></a><span class="ex">└───templates</span></span> <span id="cb8-4"><a href="#cb8-4" aria-hidden="true" tabindex="-1"></a> <span class="ex">├───latex-report:</span> template: A latex whitepaper project</span> <span id="cb8-5"><a href="#cb8-5" aria-hidden="true" tabindex="-1"></a> <span class="ex">└───rust-hello:</span> template: Simple Hello World in Rust</span></code></pre></div> -<p>Populate your template directories with content, here are my template directories for example:</p> -<div class="sourceCode" id="cb9"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb9-1"><a href="#cb9-1" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> tree mytemplates</span> +<p>Populate your template directories with content, here are my template +directories for example:</p> +<div class="sourceCode" id="cb9"><pre +class="sourceCode bash"><code class="sourceCode bash"><span id="cb9-1"><a href="#cb9-1" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> tree mytemplates</span> <span id="cb9-2"><a href="#cb9-2" aria-hidden="true" tabindex="-1"></a><span class="ex">mytemplates/</span></span> <span id="cb9-3"><a href="#cb9-3" aria-hidden="true" tabindex="-1"></a><span class="ex">├──</span> flake.nix</span> <span id="cb9-4"><a href="#cb9-4" aria-hidden="true" tabindex="-1"></a><span class="ex">├──</span> latex-report-template</span> @@ -703,15 +1051,18 @@ H N E I <span id="cb9-13"><a href="#cb9-13" aria-hidden="true" tabindex="-1"></a> <span class="ex">└──</span> src</span> <span id="cb9-14"><a href="#cb9-14" aria-hidden="true" tabindex="-1"></a> <span class="ex">└──</span> main.rs</span></code></pre></div> <p>And that’s it! Start using your templates with:</p> -<div class="sourceCode" id="cb10"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb10-1"><a href="#cb10-1" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> nix flake init <span class="at">-t</span> ~/mytemplates#rust-hello</span> +<div class="sourceCode" id="cb10"><pre +class="sourceCode bash"><code class="sourceCode bash"><span id="cb10-1"><a href="#cb10-1" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> nix flake init <span class="at">-t</span> ~/mytemplates#rust-hello</span> <span id="cb10-2"><a href="#cb10-2" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> tree .</span> <span id="cb10-3"><a href="#cb10-3" aria-hidden="true" tabindex="-1"></a><span class="bu">.</span></span> <span id="cb10-4"><a href="#cb10-4" aria-hidden="true" tabindex="-1"></a><span class="ex">├──</span> Cargo.toml</span> <span id="cb10-5"><a href="#cb10-5" aria-hidden="true" tabindex="-1"></a><span class="ex">├──</span> flake.nix</span> <span id="cb10-6"><a href="#cb10-6" aria-hidden="true" tabindex="-1"></a><span class="ex">└──</span> src</span> <span id="cb10-7"><a href="#cb10-7" aria-hidden="true" tabindex="-1"></a> <span class="ex">└──</span> main.rs</span></code></pre></div> -<p>To avoid writing <code>~/mytemplates</code> each time, simply alias it to a registry:</p> -<div class="sourceCode" id="cb11"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb11-1"><a href="#cb11-1" aria-hidden="true" tabindex="-1"></a><span class="co"># alias it to `biscuits`</span></span> +<p>To avoid writing <code>~/mytemplates</code> each time, simply alias +it to a registry:</p> +<div class="sourceCode" id="cb11"><pre +class="sourceCode bash"><code class="sourceCode bash"><span id="cb11-1"><a href="#cb11-1" aria-hidden="true" tabindex="-1"></a><span class="co"># alias it to `biscuits`</span></span> <span id="cb11-2"><a href="#cb11-2" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> nix registry add biscuits ~/mytemplates</span> <span id="cb11-3"><a href="#cb11-3" aria-hidden="true" tabindex="-1"></a></span> <span id="cb11-4"><a href="#cb11-4" aria-hidden="true" tabindex="-1"></a><span class="co"># you will see it listed under `user` registries</span></span> @@ -721,59 +1072,102 @@ H N E I <span id="cb11-8"><a href="#cb11-8" aria-hidden="true" tabindex="-1"></a><span class="bu">.</span> . .</span> <span id="cb11-9"><a href="#cb11-9" aria-hidden="true" tabindex="-1"></a></span> <span id="cb11-10"><a href="#cb11-10" aria-hidden="true" tabindex="-1"></a><span class="ex">$</span> nix flake init <span class="at">-t</span> biscuits#latex-report</span></code></pre></div> -<h2 id="extending-the-official-templates">Extending the official templates</h2> -<p>I personally, would like the <code>biscuits</code> registry to include not just my homemade templates, but also the templates from <code>NixOS/templates</code> (and maybe a couple of other repositories in the wild):</p> -<div class="sourceCode" id="cb12"><pre class="sourceCode nix"><code class="sourceCode bash"><span id="cb12-1"><a href="#cb12-1" aria-hidden="true" tabindex="-1"></a> <span class="kw">{</span></span> -<span id="cb12-2"><a href="#cb12-2" aria-hidden="true" tabindex="-1"></a> <span class="ex">description</span> = <span class="st">&quot;Pepper&#39;s flake templates&quot;</span><span class="kw">;</span></span> +<h2 id="extending-the-official-templates">Extending the official +templates</h2> +<p>I personally, would like the <code>biscuits</code> registry to +include not just my homemade templates, but also the templates from +<code>NixOS/templates</code> (and maybe a couple of other repositories +in the wild):</p> +<div class="sourceCode" id="cb12"><pre +class="sourceCode nix"><code class="sourceCode nix"><span id="cb12-1"><a href="#cb12-1" aria-hidden="true" tabindex="-1"></a> <span class="op">{</span></span> +<span id="cb12-2"><a href="#cb12-2" aria-hidden="true" tabindex="-1"></a> <span class="va">description</span> <span class="op">=</span> <span class="st">&quot;Pepper&#39;s flake templates&quot;</span><span class="op">;</span></span> <span id="cb12-3"><a href="#cb12-3" aria-hidden="true" tabindex="-1"></a> </span> -<span id="cb12-4"><a href="#cb12-4" aria-hidden="true" tabindex="-1"></a><span class="ex">+</span> inputs = {</span> -<span id="cb12-5"><a href="#cb12-5" aria-hidden="true" tabindex="-1"></a><span class="ex">+</span> official-templates.url = github:NixOS/templates<span class="kw">;</span></span> -<span id="cb12-6"><a href="#cb12-6" aria-hidden="true" tabindex="-1"></a><span class="ex">+</span> other-templates.url = github:some-other/templates<span class="kw">;</span></span> -<span id="cb12-7"><a href="#cb12-7" aria-hidden="true" tabindex="-1"></a><span class="ex">+</span> }<span class="kw">;</span></span> +<span id="cb12-4"><a href="#cb12-4" aria-hidden="true" tabindex="-1"></a>+ <span class="va">inputs</span> <span class="op">=</span> <span class="op">{</span></span> +<span id="cb12-5"><a href="#cb12-5" aria-hidden="true" tabindex="-1"></a>+ <span class="va">official-templates</span>.<span class="va">url</span> <span class="op">=</span> <span class="va">github</span><span class="op">:</span><span class="ss">NixOS/templates</span><span class="op">;</span></span> +<span id="cb12-6"><a href="#cb12-6" aria-hidden="true" tabindex="-1"></a>+ <span class="va">other-templates</span>.<span class="va">url</span> <span class="op">=</span> <span class="va">github</span><span class="op">:</span><span class="ss">some-other/templates</span><span class="op">;</span></span> +<span id="cb12-7"><a href="#cb12-7" aria-hidden="true" tabindex="-1"></a>+ <span class="op">};</span></span> <span id="cb12-8"><a href="#cb12-8" aria-hidden="true" tabindex="-1"></a> </span> -<span id="cb12-9"><a href="#cb12-9" aria-hidden="true" tabindex="-1"></a> <span class="ex">outputs</span> = { self, official-templates, other-templates ... }: {</span> +<span id="cb12-9"><a href="#cb12-9" aria-hidden="true" tabindex="-1"></a> <span class="va">outputs</span> <span class="op">=</span> <span class="op">{</span> <span class="va">self</span><span class="op">,</span> <span class="va">official-templates</span><span class="op">,</span> <span class="va">other-templates</span> <span class="op">...</span> <span class="op">}</span>: <span class="op">{</span></span> <span id="cb12-10"><a href="#cb12-10" aria-hidden="true" tabindex="-1"></a> </span> -<span id="cb12-11"><a href="#cb12-11" aria-hidden="true" tabindex="-1"></a> <span class="ex">templates</span> = {</span> -<span id="cb12-12"><a href="#cb12-12" aria-hidden="true" tabindex="-1"></a> <span class="ex">latex-report</span> = {</span> -<span id="cb12-13"><a href="#cb12-13" aria-hidden="true" tabindex="-1"></a> <span class="ex">path</span> = ./latex-report-template<span class="kw">;</span></span> -<span id="cb12-14"><a href="#cb12-14" aria-hidden="true" tabindex="-1"></a> <span class="ex">description</span> = <span class="st">&quot;A latex whitepaper project&quot;</span><span class="kw">;</span></span> -<span id="cb12-15"><a href="#cb12-15" aria-hidden="true" tabindex="-1"></a> <span class="kw">};</span></span> -<span id="cb12-16"><a href="#cb12-16" aria-hidden="true" tabindex="-1"></a> <span class="ex">rust-hello</span> = {</span> -<span id="cb12-17"><a href="#cb12-17" aria-hidden="true" tabindex="-1"></a> <span class="ex">path</span> = ./rust-hello-template<span class="kw">;</span></span> -<span id="cb12-18"><a href="#cb12-18" aria-hidden="true" tabindex="-1"></a> <span class="ex">description</span> = <span class="st">&quot;Simple Hello World in Rust, with overloaded Rust toolchain&quot;</span><span class="kw">;</span></span> -<span id="cb12-19"><a href="#cb12-19" aria-hidden="true" tabindex="-1"></a> <span class="er">}</span><span class="kw">;</span></span> -<span id="cb12-20"><a href="#cb12-20" aria-hidden="true" tabindex="-1"></a> <span class="er">}</span></span> -<span id="cb12-21"><a href="#cb12-21" aria-hidden="true" tabindex="-1"></a><span class="ex">+</span> // official-templates.templates</span> -<span id="cb12-22"><a href="#cb12-22" aria-hidden="true" tabindex="-1"></a><span class="ex">+</span> // other-templates.templates<span class="kw">;</span></span> +<span id="cb12-11"><a href="#cb12-11" aria-hidden="true" tabindex="-1"></a> <span class="va">templates</span> <span class="op">=</span> <span class="op">{</span></span> +<span id="cb12-12"><a href="#cb12-12" aria-hidden="true" tabindex="-1"></a> <span class="va">latex-report</span> <span class="op">=</span> <span class="op">{</span></span> +<span id="cb12-13"><a href="#cb12-13" aria-hidden="true" tabindex="-1"></a> <span class="va">path</span> <span class="op">=</span> <span class="ss">./latex-report-template</span><span class="op">;</span></span> +<span id="cb12-14"><a href="#cb12-14" aria-hidden="true" tabindex="-1"></a> <span class="va">description</span> <span class="op">=</span> <span class="st">&quot;A latex whitepaper project&quot;</span><span class="op">;</span></span> +<span id="cb12-15"><a href="#cb12-15" aria-hidden="true" tabindex="-1"></a> <span class="op">};</span></span> +<span id="cb12-16"><a href="#cb12-16" aria-hidden="true" tabindex="-1"></a> <span class="va">rust-hello</span> <span class="op">=</span> <span class="op">{</span></span> +<span id="cb12-17"><a href="#cb12-17" aria-hidden="true" tabindex="-1"></a> <span class="va">path</span> <span class="op">=</span> <span class="ss">./rust-hello-template</span><span class="op">;</span></span> +<span id="cb12-18"><a href="#cb12-18" aria-hidden="true" tabindex="-1"></a> <span class="va">description</span> <span class="op">=</span> <span class="st">&quot;Simple Hello World in Rust, with overloaded Rust toolchain&quot;</span><span class="op">;</span></span> +<span id="cb12-19"><a href="#cb12-19" aria-hidden="true" tabindex="-1"></a> <span class="op">};</span></span> +<span id="cb12-20"><a href="#cb12-20" aria-hidden="true" tabindex="-1"></a> <span class="op">}</span></span> +<span id="cb12-21"><a href="#cb12-21" aria-hidden="true" tabindex="-1"></a><span class="op">+</span> <span class="op">//</span> official<span class="op">-</span>templates.templates</span> +<span id="cb12-22"><a href="#cb12-22" aria-hidden="true" tabindex="-1"></a><span class="op">+</span> <span class="op">//</span> other<span class="op">-</span>templates.templates<span class="op">;</span></span> <span id="cb12-23"><a href="#cb12-23" aria-hidden="true" tabindex="-1"></a> </span> -<span id="cb12-24"><a href="#cb12-24" aria-hidden="true" tabindex="-1"></a> <span class="er">}</span><span class="kw">;</span></span> -<span id="cb12-25"><a href="#cb12-25" aria-hidden="true" tabindex="-1"></a> <span class="er">}</span></span></code></pre></div> -<p>Running <code>nix flake show biscuits</code> will now list templates from the <code>biscuits</code> registry as well as the ones from <code>NixOS/templates</code>. Ensure that the names don’t collide though.</p> +<span id="cb12-24"><a href="#cb12-24" aria-hidden="true" tabindex="-1"></a> <span class="op">};</span></span> +<span id="cb12-25"><a href="#cb12-25" aria-hidden="true" tabindex="-1"></a> <span class="op">}</span></span></code></pre></div> +<p>Running <code>nix flake show biscuits</code> will now list templates +from the <code>biscuits</code> registry as well as the ones from +<code>NixOS/templates</code>. Ensure that the names don’t collide +though.</p> https://peppe.rs/posts/novice_nix:_flake_templates/ Tue, 05 Oct 2021 16:49:00 +0000 https://peppe.rs/posts/novice_nix:_flake_templates/ SDL2 Devlog -<p>I have been working on an editor for the <a href="https://git.peppe.rs/graphics/obi/about">One Bit Image</a> file format in Rust and SDL2. This entry in my blog follows my progress on the editor. The days are listed in reverse chronological order, begin from the bottom, if this is your first time on this page.</p> +<p>I have been working on an editor for the <a +href="https://git.peppe.rs/graphics/obi/about">One Bit Image</a> file +format in Rust and SDL2. This entry in my blog follows my progress on +the editor. The days are listed in reverse chronological order, begin +from the bottom, if this is your first time on this page.</p> <h3 id="day-20">Day 20</h3> -<p>More <code>lisp</code> stuff! I added a new brush, for rectangular selections. While selection doesn’t do much on its own, the selected area can be passed onto a <code>lisp</code> procedure, for example, a procedure to draw horizontal black and white lines:</p> +<p>More <code>lisp</code> stuff! I added a new brush, for rectangular +selections. While selection doesn’t do much on its own, the selected +area can be passed onto a <code>lisp</code> procedure, for example, a +procedure to draw horizontal black and white lines:</p> <figure> -<video src="https://u.peppe.rs/frU.mp4" controls=""><a href="https://u.peppe.rs/frU.mp4">Day 20</a></video><figcaption aria-hidden="true">Day 20</figcaption> +<video src="https://u.peppe.rs/frU.mp4" controls=""><a +href="https://u.peppe.rs/frU.mp4">Day 20</a></video> +<figcaption aria-hidden="true">Day 20</figcaption> </figure> <h3 id="day-19">Day 19</h3> -<p>Attempted <a href="https://peppe.rs/art/conduit.png">some isometric art</a> within the editor. The angles displayed alongside the line brush are handly, however, having only a rectangular grid did not help. I implemented an isometric grid today. Isometric grids in pixel art differ in that the tangent of the isometric angle is exactly 0.5! For every pixel down, you go exactly two pixels sideways. The math works out really well in the drawing procedures too, dealing with floating points is a pain.</p> +<p>Attempted <a href="https://peppe.rs/art/conduit.png">some isometric +art</a> within the editor. The angles displayed alongside the line brush +are handly, however, having only a rectangular grid did not help. I +implemented an isometric grid today. Isometric grids in pixel art differ +in that the tangent of the isometric angle is exactly 0.5! For every +pixel down, you go exactly two pixels sideways. The math works out +really well in the drawing procedures too, dealing with floating points +is a pain.</p> <figure> -<img src="https://u.peppe.rs/1Kb.png" alt="Day 19" /><figcaption aria-hidden="true">Day 19</figcaption> +<img src="https://u.peppe.rs/1Kb.png" alt="Day 19" /> +<figcaption aria-hidden="true">Day 19</figcaption> </figure> <h3 id="day-18">Day 18</h3> -<p>I added basic support for guides, they can be added and activated from the <code>lisp</code> REPL. Another long standing improvement I wanted to make was reworking the pixmap drawing procedure. The old procedure draws a square for each pixel in the pixmap, coloured according to its value in the pixmap. Naturally, this means, for an <strong>NxN</strong> pixmap, there are <strong>N²</strong> calls to SDL! I reworked this procedure to compress each line of the pixmap using RLE (run length encoding), and call out to SDL for each run in the line. This drastically improved drawing speeds on larger grids. The following is a comparison between the two procedures, the leftmost picture is the rendered image, the middle picture is the optimized drawing procedure (draws each run instead of pixel), and the right most picture is the primitive drawing procedure (draws each pixel):</p> +<p>I added basic support for guides, they can be added and activated +from the <code>lisp</code> REPL. Another long standing improvement I +wanted to make was reworking the pixmap drawing procedure. The old +procedure draws a square for each pixel in the pixmap, coloured +according to its value in the pixmap. Naturally, this means, for an +<strong>NxN</strong> pixmap, there are <strong>N²</strong> calls to SDL! +I reworked this procedure to compress each line of the pixmap using RLE +(run length encoding), and call out to SDL for each run in the line. +This drastically improved drawing speeds on larger grids. The following +is a comparison between the two procedures, the leftmost picture is the +rendered image, the middle picture is the optimized drawing procedure +(draws each run instead of pixel), and the right most picture is the +primitive drawing procedure (draws each pixel):</p> <figure> -<img src="https://u.peppe.rs/U4B.png" alt="Day 18" /><figcaption aria-hidden="true">Day 18</figcaption> +<img src="https://u.peppe.rs/U4B.png" alt="Day 18" /> +<figcaption aria-hidden="true">Day 18</figcaption> </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" tabindex="-1"></a><span class="co">// roughly something like this</span></span> +<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" 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> @@ -790,14 +1184,20 @@ H N E I <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> +<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" tabindex="-1"></a><span class="co">;;; rc.lisp</span></span> +<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" 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" tabindex="-1"></a><span class="co">;;; rc.lisp</span></span> +<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> @@ -805,90 +1205,195 @@ H N E I <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> +<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> +<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" tabindex="-1"></a>(define (member? item ls)</span> +<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" 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> +<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> -<video src="https://u.peppe.rs/8q.mp4" controls=""><a href="https://u.peppe.rs/8q.mp4">Day 14</a></video><figcaption aria-hidden="true">Day 14</figcaption> +<video src="https://u.peppe.rs/8q.mp4" controls=""><a +href="https://u.peppe.rs/8q.mp4">Day 14</a></video> +<figcaption aria-hidden="true">Day 14</figcaption> </figure> <h3 id="day-13">Day 13</h3> -<p>I added a few more forms to the <code>lisp</code> evaluator. It handles recursion, definitions, variable mutation and more. The prelude contains 20 subroutines so far, including comparision and logic operators. The REPL interface on the SDL side requires some UX tweaks; environment based completion, readline motions sound doable.</p> +<p>I added a few more forms to the <code>lisp</code> evaluator. It +handles recursion, definitions, variable mutation and more. The prelude +contains 20 subroutines so far, including comparision and logic +operators. The REPL interface on the SDL side requires some UX tweaks; +environment based completion, readline motions sound doable.</p> <figure> -<video src="https://u.peppe.rs/u3.mp4" controls=""><a href="https://u.peppe.rs/u3.mp4">Day 13</a></video><figcaption aria-hidden="true">Day 13</figcaption> +<video src="https://u.peppe.rs/u3.mp4" controls=""><a +href="https://u.peppe.rs/u3.mp4">Day 13</a></video> +<figcaption aria-hidden="true">Day 13</figcaption> </figure> <h3 id="day-12">Day 12</h3> -<p>I lifted most of <a href="https://github.com/murarth/ketos">murarth/ketos</a> into the editor. <code>ketos</code>’s implementation of <code>lisp</code> is too vast for my use case. For example, the editor does not need data types to handle raw strings or byte strings. I have got a basic evaluator running inside the SDL2 context (notice the <code>lisp</code> REPL at the bottom of the window). Over the following days, I intend to create a set of prelude functions to manipulate the pixmap. Users can implement their own brushes, dithering patterns, keybinds and more (hopefully).</p> +<p>I lifted most of <a +href="https://github.com/murarth/ketos">murarth/ketos</a> into the +editor. <code>ketos</code>’s implementation of <code>lisp</code> is too +vast for my use case. For example, the editor does not need data types +to handle raw strings or byte strings. I have got a basic evaluator +running inside the SDL2 context (notice the <code>lisp</code> REPL at +the bottom of the window). Over the following days, I intend to create a +set of prelude functions to manipulate the pixmap. Users can implement +their own brushes, dithering patterns, keybinds and more +(hopefully).</p> <figure> -<video src="https://u.peppe.rs/y0.mp4" controls=""><a href="https://u.peppe.rs/y0.mp4">Day 12</a></video><figcaption aria-hidden="true">Day 12</figcaption> +<video src="https://u.peppe.rs/y0.mp4" controls=""><a +href="https://u.peppe.rs/y0.mp4">Day 12</a></video> +<figcaption aria-hidden="true">Day 12</figcaption> </figure> <h3 id="day-11">Day 11</h3> -<p>I intend to supplement the editor with scripting language and an inbuilt REPL for the same. I began by implementing a text box widget from scratch, with history and readline like editing:</p> +<p>I intend to supplement the editor with scripting language and an +inbuilt REPL for the same. I began by implementing a text box widget +from scratch, with history and readline like editing:</p> <figure> -<video src="https://u.peppe.rs/Mh.mp4" controls=""><a href="https://u.peppe.rs/Mh.mp4">Day 11</a></video><figcaption aria-hidden="true">Day 11</figcaption> +<video src="https://u.peppe.rs/Mh.mp4" controls=""><a +href="https://u.peppe.rs/Mh.mp4">Day 11</a></video> +<figcaption aria-hidden="true">Day 11</figcaption> </figure> <h3 id="day-10">Day 10</h3> -<p>I started reading up on dithering methods and half-toning, I wanted to create a dithering brush that would automatically produce popular dithering patterns. The method that caught my eye (and also the one used most often in pixel art), was Bayer’s ordered dithering. When applied to a black and white image, each pixel, based on its intensity, is mapped to a 4x4 grid of pixels. A completely empty (completely black) 4x4 grid represents zero intensity, and a filled 4x4 grid represents full intensity. Bayer’s ordered dithering can produce 15 steps of intensity between zero and full (by switching on exactly 1 pixel more at each level), thus, being able to draw 17 “shades” from white to black. Creating a dithering brush from here was fairly trivial. Our pixmap is supposed to represent the final dithered image, it must be divided into 4x4 grids. Each grid is colored based on the intensity of the brush passing over it:</p> +<p>I started reading up on dithering methods and half-toning, I wanted +to create a dithering brush that would automatically produce popular +dithering patterns. The method that caught my eye (and also the one used +most often in pixel art), was Bayer’s ordered dithering. When applied to +a black and white image, each pixel, based on its intensity, is mapped +to a 4x4 grid of pixels. A completely empty (completely black) 4x4 grid +represents zero intensity, and a filled 4x4 grid represents full +intensity. Bayer’s ordered dithering can produce 15 steps of intensity +between zero and full (by switching on exactly 1 pixel more at each +level), thus, being able to draw 17 “shades” from white to black. +Creating a dithering brush from here was fairly trivial. Our pixmap is +supposed to represent the final dithered image, it must be divided into +4x4 grids. Each grid is colored based on the intensity of the brush +passing over it:</p> <figure> -<img src="https://u.peppe.rs/Mn.png" alt="Day 10" /><figcaption aria-hidden="true">Day 10</figcaption> +<img src="https://u.peppe.rs/Mn.png" alt="Day 10" /> +<figcaption aria-hidden="true">Day 10</figcaption> </figure> <h3 id="day-9">Day 9</h3> -<p>I started working towards an interface. I like the idea of a largely read-only HUD, i. e., an interface that simply describes the state of the application. Changes to this state are initiated via keybinds or text commands. I am proud of the symmetry indicator; <code>-</code> for horizontal symmetry, <code>|</code> for vertical symmetry, <code>+</code> for radial symmetry.</p> +<p>I started working towards an interface. I like the idea of a largely +read-only HUD, i. e., an interface that simply describes the state of +the application. Changes to this state are initiated via keybinds or +text commands. I am proud of the symmetry indicator; <code>-</code> for +horizontal symmetry, <code>|</code> for vertical symmetry, +<code>+</code> for radial symmetry.</p> <figure> -<img src="https://u.peppe.rs/hx.png" alt="Day 9" /><figcaption aria-hidden="true">Day 9</figcaption> +<img src="https://u.peppe.rs/hx.png" alt="Day 9" /> +<figcaption aria-hidden="true">Day 9</figcaption> </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" 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> +<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" 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-3"><a href="#cb5-3" aria-hidden="true" tabindex="-1"></a><span class="cf">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> +<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> <h3 id="day-7">Day 7</h3> -<p>Bresenham saves the day again! This time, I implemented his line drawing algorithm, to, well, draw lines. Each point on the line is then “buffed” based on the active brush size. Today’s changes fit in very well with the undo system and the brush size feature. Creating the right abstractions, one at a time :)</p> +<p>Bresenham saves the day again! This time, I implemented his line +drawing algorithm, to, well, draw lines. Each point on the line is then +“buffed” based on the active brush size. Today’s changes fit in very +well with the undo system and the brush size feature. Creating the right +abstractions, one at a time :)</p> <figure> -<video src="https://u.peppe.rs/xt.mp4" controls=""><a href="https://u.peppe.rs/xt.mp4">Day 7</a></video><figcaption aria-hidden="true">Day 7</figcaption> +<video src="https://u.peppe.rs/xt.mp4" controls=""><a +href="https://u.peppe.rs/xt.mp4">Day 7</a></video> +<figcaption aria-hidden="true">Day 7</figcaption> </figure> <h3 id="day-6">Day 6</h3> -<p>I extended Bresenham’s algorithm to draw not just circle outlines, but also generate their fills. Unlike Bresenham’s algorithm, this variant generates points for two quadrants at once, these points are mirrored over the dividing axis to generate the other two quadrants.</p> +<p>I extended Bresenham’s algorithm to draw not just circle outlines, +but also generate their fills. Unlike Bresenham’s algorithm, this +variant generates points for two quadrants at once, these points are +mirrored over the dividing axis to generate the other two quadrants.</p> <figure> -<img src="https://u.peppe.rs/f3.png" alt="Day 6" /><figcaption aria-hidden="true">Day 6</figcaption> +<img src="https://u.peppe.rs/f3.png" alt="Day 6" /> +<figcaption aria-hidden="true">Day 6</figcaption> </figure> <h3 id="day-5">Day 5</h3> -<p>I discovered and implemented Bresenham’s algorithm for efficient circle drawing. The algorithm allowed for sized circular brushes, something I really liked from GIMP. Very convenient that the Wikipedia page for Bresenham’s algorithm also includes a section about optimizing for integer based arithmetic. I managed to abstract out another giant component of the application, the pixmap. Any image is just a grid of pixels (a pixmap), where the pixel’s value is decided by the application (1-bit in my case). I could potentially extend the application to a 24-bit image editor!</p> +<p>I discovered and implemented Bresenham’s algorithm for efficient +circle drawing. The algorithm allowed for sized circular brushes, +something I really liked from GIMP. Very convenient that the Wikipedia +page for Bresenham’s algorithm also includes a section about optimizing +for integer based arithmetic. I managed to abstract out another giant +component of the application, the pixmap. Any image is just a grid of +pixels (a pixmap), where the pixel’s value is decided by the application +(1-bit in my case). I could potentially extend the application to a +24-bit image editor!</p> <figure> -<video src="https://u.peppe.rs/Kh.mp4" controls=""><a href="https://u.peppe.rs/Kh.mp4">Day 5</a></video><figcaption aria-hidden="true">Day 5</figcaption> +<video src="https://u.peppe.rs/Kh.mp4" controls=""><a +href="https://u.peppe.rs/Kh.mp4">Day 5</a></video> +<figcaption aria-hidden="true">Day 5</figcaption> </figure> <h3 id="day-4">Day 4</h3> -<p>I created a generic “undo stack” data structure that allows for infinite “undos” and “redos”. Every modification operation to the grid is persisted to the application state. A couple of keybinds allow the user to revert and re-apply these operations! I expect abstracting this component will come in handy down the line.</p> +<p>I created a generic “undo stack” data structure that allows for +infinite “undos” and “redos”. Every modification operation to the grid +is persisted to the application state. A couple of keybinds allow the +user to revert and re-apply these operations! I expect abstracting this +component will come in handy down the line.</p> <figure> -<video src="https://u.peppe.rs/w5.mp4" controls=""><a href="https://u.peppe.rs/w5.mp4">Day 4</a></video><figcaption aria-hidden="true">Day 4</figcaption> +<video src="https://u.peppe.rs/w5.mp4" controls=""><a +href="https://u.peppe.rs/w5.mp4">Day 4</a></video> +<figcaption aria-hidden="true">Day 4</figcaption> </figure> <h3 id="day-3">Day 3</h3> -<p>I implemented the bare minimum required to call the program an “editor”. The application displays a grid, tracks mouse events, paints white to the canvas on left click, and black to the canvas on right click. I created a make-shift MVC architecture à la Elm in Rust.</p> +<p>I implemented the bare minimum required to call the program an +“editor”. The application displays a grid, tracks mouse events, paints +white to the canvas on left click, and black to the canvas on right +click. I created a make-shift MVC architecture à la Elm in Rust.</p> <figure> -<video src="https://u.peppe.rs/GF.mp4" controls=""><a href="https://u.peppe.rs/GF.mp4">Day 3</a></video><figcaption aria-hidden="true">Day 3</figcaption> +<video src="https://u.peppe.rs/GF.mp4" controls=""><a +href="https://u.peppe.rs/GF.mp4">Day 3</a></video> +<figcaption aria-hidden="true">Day 3</figcaption> </figure> <h3 id="day-2">Day 2</h3> -<p>I started figuring out event handling today. Implemented a couple of keybinds to zoom in/out of the drawing area. Conversions of SDL2 coordinates (measured in signed 32 bit integers) to my internal “drawing area” coordinates (measured in unsigned 32 bit integers) is very annoying. Hopefully the unchecked conversions won’t haunt me later.</p> +<p>I started figuring out event handling today. Implemented a couple of +keybinds to zoom in/out of the drawing area. Conversions of SDL2 +coordinates (measured in signed 32 bit integers) to my internal “drawing +area” coordinates (measured in unsigned 32 bit integers) is very +annoying. Hopefully the unchecked conversions won’t haunt me later.</p> <figure> -<video src="https://u.peppe.rs/L4.mp4" controls=""><a href="https://u.peppe.rs/L4.mp4">Day 2</a></video><figcaption aria-hidden="true">Day 2</figcaption> +<video src="https://u.peppe.rs/L4.mp4" controls=""><a +href="https://u.peppe.rs/L4.mp4">Day 2</a></video> +<figcaption aria-hidden="true">Day 2</figcaption> </figure> <h3 id="day-1">Day 1</h3> -<p>Getting started with Rust and SDL2 is very straightforward. The <code>rust-sdl2</code> library contains some detailed examples that allowed me to get all the way to drawing a grid from a <code>Vec&lt;bool&gt;</code>:</p> +<p>Getting started with Rust and SDL2 is very straightforward. The +<code>rust-sdl2</code> library contains some detailed examples that +allowed me to get all the way to drawing a grid from a +<code>Vec&lt;bool&gt;</code>:</p> <figure> -<img src="https://u.peppe.rs/Ma.png" alt="Day 1" /><figcaption aria-hidden="true">Day 1</figcaption> +<img src="https://u.peppe.rs/Ma.png" alt="Day 1" /> +<figcaption aria-hidden="true">Day 1</figcaption> </figure> https://peppe.rs/posts/SDL2_devlog/ Sun, 11 Apr 2021 10:46:00 +0000 @@ -896,11 +1401,21 @@ H N E I Self-hosting Git -<p>Earlier this week, I began migrating my repositories from Github to <a href="https://git.zx2c4.com/cgit/about/">cgit</a>. If you care at all about big corporates turning open-source into a T-shirt farming service, this is the way to go.</p> +<p>Earlier this week, I began migrating my repositories from Github to +<a href="https://git.zx2c4.com/cgit/about/">cgit</a>. If you care at all +about big corporates turning open-source into a T-shirt farming service, +this is the way to go.</p> <h3 id="offerings">Offerings</h3> -<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> +<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> +<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" 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> @@ -909,9 +1424,16 @@ H N E I <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> +<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> +<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" 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> @@ -935,15 +1457,21 @@ server { <p>Point cgit to your git repositories:</p> <pre><code># /etc/cgitrc scan-path=/path/to/git/repos</code></pre> -<p><strong><em>Note</em></strong>: <em><code>scan-path</code> works best if you stick it at the end of your <code>cgitrc</code></em>.</p> -<p>You may now create remote repositories at <code>/path/to/git/repos</code>, via:</p> +<p><strong><em>Note</em></strong>: <em><code>scan-path</code> works best +if you stick it at the end of your <code>cgitrc</code></em>.</p> +<p>You may now create remote repositories at +<code>/path/to/git/repos</code>, via:</p> <pre><code>git init --bare</code></pre> <p>Add the remote to your local repository:</p> <pre><code>git remote set-url origin user@remote:/above/path git push origin master</code></pre> <h3 id="configuration">Configuration</h3> -<p>cgit is fairly easy to configure, all configuration options can be found <a href="https://git.zx2c4.com/cgit/tree/cgitrc.5.txt">in the manual</a>, here are a couple of cool ones though:</p> -<p><strong>enable-commit-graph</strong>: Generates a text based graphical representation of the commit history, similar to <code>git log --graph --oneline</code>.</p> +<p>cgit is fairly easy to configure, all configuration options can be +found <a href="https://git.zx2c4.com/cgit/tree/cgitrc.5.txt">in the +manual</a>, here are a couple of cool ones though:</p> +<p><strong>enable-commit-graph</strong>: Generates a text based +graphical representation of the commit history, similar to +<code>git log --graph --oneline</code>.</p> <pre><code>| * | Add support for configuration file * | | simplify command parsing logic * | | Refactor parsers @@ -964,7 +1492,11 @@ git push origin master</code></pre> | | * | Merge branch &#39;fix/duplicate-habits&#39; | | |\ \ | | | * | move duplicate check to command parsing blo...</code></pre> -<p><strong>section-from-path</strong>: This option paired with <code>scan-path</code> will automatically generate sections in your cgit index page, from the path to each repo. For example, the directory structure used to generate sections on <a href="https://git.peppe.rs">my cgit instance</a> looks like this:</p> +<p><strong>section-from-path</strong>: This option paired with +<code>scan-path</code> will automatically generate sections in your cgit +index page, from the path to each repo. For example, the directory +structure used to generate sections on <a href="https://git.peppe.rs">my +cgit instance</a> looks like this:</p> <pre><code>├── cli │ ├── dijo │ ├── eva @@ -988,11 +1520,18 @@ git push origin master</code></pre> └── web └── isostatic</code></pre> <h3 id="ease-of-use">Ease of use</h3> -<p>As I mentioned before, <code>cgit</code> is simply a view into your git repositories, you will have to manually create new repositories by entering your remote and using <code>git init --bare</code>. Here are a couple of scripts I wrote to perform actions on remotes, think of it as a smaller version of Github’s <code>gh</code> program.</p> -<p>You may save these scripts as <code>git-script-name</code> and drop them in your <code>$PATH</code>, and git will automatically add an alias called <code>script-name</code>, callable via:</p> +<p>As I mentioned before, <code>cgit</code> is simply a view into your +git repositories, you will have to manually create new repositories by +entering your remote and using <code>git init --bare</code>. Here are a +couple of scripts I wrote to perform actions on remotes, think of it as +a smaller version of Github’s <code>gh</code> program.</p> +<p>You may save these scripts as <code>git-script-name</code> and drop +them in your <code>$PATH</code>, and git will automatically add an alias +called <code>script-name</code>, callable via:</p> <pre><code>git script-name</code></pre> <h4 id="git-new-repo">git-new-repo</h4> -<p>Creates a new repository on your remote, the first arg may be a path (section/repo-name) or just the repo name:</p> +<p>Creates a new repository on your remote, the first arg may be a path +(section/repo-name) or just the repo name:</p> <pre><code>#! /usr/bin/env bash # # usage: @@ -1009,7 +1548,10 @@ fi ssh user@remote git init --bare &quot;$1&quot;;</code></pre> <h4 id="git-set-desc">git-set-desc</h4> -<p>To set a one line repository description. It simply copies the local <code>.git/description</code>, into <code>remote/description</code>. <code>cgit</code> displays the contents of this file on the index page:</p> +<p>To set a one line repository description. It simply copies the local +<code>.git/description</code>, into <code>remote/description</code>. +<code>cgit</code> displays the contents of this file on the index +page:</p> <pre><code>#! /usr/bin/env bash # # usage: @@ -1024,11 +1566,24 @@ scp .git/description &quot;$remote/description&quot;</code></pr NixOS -<p>I have been eyeing operating systems with functional package managers for a while now, aka, NixOS or Guix. Reproducible builds, declarative and rollback-able system configuration, system consistency, all sound pretty cool. I have been using NixOS for about a month now.</p> +<p>I have been eyeing operating systems with functional package managers +for a while now, aka, NixOS or Guix. Reproducible builds, declarative +and rollback-able system configuration, system consistency, all sound +pretty cool. I have been using NixOS for about a month now.</p> <h3 id="installation">Installation</h3> -<p>I went with their minimal installation ISO. The installation was pretty smooth from start to end, no hitches there. The entire <a href="https://nixos.org/manual/nixos/stable/">manual</a> is available offline, and is accessible during the installation. Very handy.</p> +<p>I went with their minimal installation ISO. The installation was +pretty smooth from start to end, no hitches there. The entire <a +href="https://nixos.org/manual/nixos/stable/">manual</a> is available +offline, and is accessible during the installation. Very handy.</p> <h3 id="setup">Setup</h3> -<p>The entire system is configured via <code>/etc/nixos/configuration.nix</code>. Wifi, <code>libinput</code> gestures, audio, locale settings, there are options for literally everything. You can declaratively write down the packages you want installed too. With fresh installs of most distros, I usually fumble with getting things like screen backlight and media keys to work. If I do manage to fix it, I can’t carry it forward to future installations trivially. Getting all my hardware to work on NixOS is as easy as:</p> +<p>The entire system is configured via +<code>/etc/nixos/configuration.nix</code>. Wifi, <code>libinput</code> +gestures, audio, locale settings, there are options for literally +everything. You can declaratively write down the packages you want +installed too. With fresh installs of most distros, I usually fumble +with getting things like screen backlight and media keys to work. If I +do manage to fix it, I can’t carry it forward to future installations +trivially. Getting all my hardware to work on NixOS is as easy as:</p> <pre><code>{ server.xserver.libinput.enable = true; # touchpad programs.light.enable = true; # backlight @@ -1036,37 +1591,77 @@ scp .git/description &quot;$remote/description&quot;</code></pr networking.wireless.enable = true; # wifi }</code></pre> <h3 id="developing-with-nix">Developing with Nix</h3> -<p>Nix makes it easy to enter environments that aren’t affected by your system configuration using <code>nix-shell</code>.</p> -<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" tabindex="-1"></a><span class="co">#! /usr/bin/env nix-shell</span></span> +<p>Nix makes it easy to enter environments that aren’t affected by your +system configuration using <code>nix-shell</code>.</p> +<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" 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> +<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> -<p>Being able to rollback changes at a system level is cool. Package broke something? Just <code>nixos-rebuild switch --rollback</code>! Deleted <code>nix</code> by mistake? Find the binary in <code>/nix/store</code> and rollback! You aren’t punished for not thinking twice.</p> -<p>I don’t see myself switching to anything else in the near future, NixOS does a lot of things right. If I ever need to reinstall NixOS, I can generate an <a href="https://github.com/nix-community/nixos-generators">image of my current system</a>.</p> -<p><a href="https://u.peppe.rs/6m.png"><img src="https://u.peppe.rs/6m.png" /></a></p> +<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> +<p>Being able to rollback changes at a system level is cool. Package +broke something? Just <code>nixos-rebuild switch --rollback</code>! +Deleted <code>nix</code> by mistake? Find the binary in +<code>/nix/store</code> and rollback! You aren’t punished for not +thinking twice.</p> +<p>I don’t see myself switching to anything else in the near future, +NixOS does a lot of things right. If I ever need to reinstall NixOS, I +can generate an <a +href="https://github.com/nix-community/nixos-generators">image of my +current system</a>.</p> +<p><a href="https://u.peppe.rs/6m.png"><img +src="https://u.peppe.rs/6m.png" /></a></p> https://peppe.rs/posts/nixOS/ Tue, 01 Sep 2020 07:08:00 +0000 https://peppe.rs/posts/nixOS/ Gripes With Go -<p>You’ve read a lot of posts about the shortcomings of the Go programming language, so what’s one more.</p> +<p>You’ve read a lot of posts about the shortcomings of the Go +programming language, so what’s one more.</p> <ol type="1"> <li><a href="#lack-of-sum-types">Lack of sum types</a></li> <li><a href="#type-assertions">Type assertions</a></li> <li><a href="#date-and-time">Date and Time</a></li> -<li><a href="#statements-over-expressions">Statements over Expressions</a></li> -<li><a href="#erroring-out-on-unused-variables">Erroring out on unused variables</a></li> +<li><a href="#statements-over-expressions">Statements over +Expressions</a></li> +<li><a href="#erroring-out-on-unused-variables">Erroring out on unused +variables</a></li> <li><a href="#error-handling">Error handling</a></li> </ol> <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 “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" 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> @@ -1081,17 +1676,18 @@ scp .git/description &quot;$remote/description&quot;</code></pr <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-14"><a href="#cb1-14" aria-hidden="true" tabindex="-1"></a> <span class="cf">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="cf">case</span> <span class="dv">0</span><span class="op">:</span> <span class="cf">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="cf">case</span> <span class="dv">1</span><span class="op">:</span> <span class="cf">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="cf">default</span><span class="op">:</span> <span class="cf">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" tabindex="-1"></a><span class="kw">data</span> <span class="dt">Gender</span> <span class="ot">=</span> <span class="dt">Male</span></span> +<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> @@ -1102,7 +1698,7 @@ scp .git/description &quot;$remote/description&quot;</code></pr <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" 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-3"><a href="#cb3-3" aria-hidden="true" tabindex="-1"></a><span class="cf">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> @@ -1112,18 +1708,32 @@ scp .git/description &quot;$remote/description&quot;</code></pr <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> +<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> +<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> +<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" 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> +<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" tabindex="-1"></a><span class="kw">let</span> twenty_seven <span class="op">=</span> <span class="op">{</span></span> +<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" 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> @@ -1134,17 +1744,25 @@ scp .git/description &quot;$remote/description&quot;</code></pr <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="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" 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> +<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="cf">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> +<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" tabindex="-1"></a><span class="co">// 1. error handling is compulsory</span></span> +<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" 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> @@ -1158,13 +1776,16 @@ scp .git/description &quot;$remote/description&quot;</code></pr <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-15"><a href="#cb11-15" aria-hidden="true" tabindex="-1"></a> <span class="cf">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> +<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/ Sat, 01 Aug 2020 11:55:00 +0000 https://peppe.rs/posts/gripes_with_go/ @@ -1173,12 +1794,26 @@ scp .git/description &quot;$remote/description&quot;</code></pr Turing Complete Type Systems <p>Rust’s type system is Turing complete:</p> <ul> -<li><a href="https://github.com/doctorn/trait-eval/">FizzBuzz with Rust Traits</a></li> -<li><a href="https://github.com/Ashymad/fortraith">A Forth implementation with Rust Traits</a></li> +<li><a href="https://github.com/doctorn/trait-eval/">FizzBuzz with Rust +Traits</a></li> +<li><a href="https://github.com/Ashymad/fortraith">A Forth +implementation with Rust Traits</a></li> </ul> -<p>It is impossible to determine if a program written in a generally Turing complete system will ever stop. That is, it is impossible to write a program <code>f</code> that determines if a program <code>g</code>, where <code>g</code> is written in a Turing complete programming language, will ever halt. The <a href="https://en.wikipedia.org/wiki/Halting_problem">Halting Problem</a> is in fact, an <a href="https://en.wikipedia.org/wiki/Undecidable_problem">undecidable problem</a>.</p> +<p>It is impossible to determine if a program written in a generally +Turing complete system will ever stop. That is, it is impossible to +write a program <code>f</code> that determines if a program +<code>g</code>, where <code>g</code> is written in a Turing complete +programming language, will ever halt. The <a +href="https://en.wikipedia.org/wiki/Halting_problem">Halting Problem</a> +is in fact, an <a +href="https://en.wikipedia.org/wiki/Undecidable_problem">undecidable +problem</a>.</p> <p><em>How is any of this relevant?</em></p> -<p>Rust performs compile-time type inference. The type checker, in turn, compiles and infers types, I would describe it as a compiler inside a compiler. It is possible that <code>rustc</code> may never finish compiling your Rust program! I lied, <code>rustc</code> stops after a while, after hitting the recursion limit.</p> +<p>Rust performs compile-time type inference. The type checker, in turn, +compiles and infers types, I would describe it as a compiler inside a +compiler. It is possible that <code>rustc</code> may never finish +compiling your Rust program! I lied, <code>rustc</code> stops after a +while, after hitting the recursion limit.</p> <p>I understand that this post lacks content.</p> https://peppe.rs/posts/turing_complete_type_systems/ Wed, 17 Jun 2020 18:30:00 +0000 @@ -1186,13 +1821,22 @@ scp .git/description &quot;$remote/description&quot;</code></pr Auto-currying Rust Functions -<p>This post contains a gentle introduction to procedural macros in Rust and a guide to writing a procedural macro to curry Rust functions. The source code for the entire library can be found <a href="https://github.com/nerdypepper/cutlass">here</a>. It is also available on <a href="https://crates.io/crates/cutlass">crates.io</a>.</p> -<p>The following links might prove to be useful before getting started:</p> +<p>This post contains a gentle introduction to procedural macros in Rust +and a guide to writing a procedural macro to curry Rust functions. The +source code for the entire library can be found <a +href="https://github.com/nerdypepper/cutlass">here</a>. It is also +available on <a +href="https://crates.io/crates/cutlass">crates.io</a>.</p> +<p>The following links might prove to be useful before getting +started:</p> <ul> -<li><a href="https://doc.rust-lang.org/reference/procedural-macros.html">Procedural Macros</a></li> +<li><a +href="https://doc.rust-lang.org/reference/procedural-macros.html">Procedural +Macros</a></li> <li><a href="https://en.wikipedia.org/wiki/Currying">Currying</a></li> </ul> -<p>Or you can pretend you read them, because I have included a primer here :)</p> +<p>Or you can pretend you read them, because I have included a primer +here :)</p> <h3 id="contents">Contents</h3> <ol type="1"> <li><a href="#currying">Currying</a><br /> @@ -1217,7 +1861,12 @@ scp .git/description &quot;$remote/description&quot;</code></pr <li><a href="#conclusion">Conclusion</a></li> </ol> <h3 id="currying">Currying</h3> -<p>Currying is the process of transformation of a function call like <code>f(a, b, c)</code> to <code>f(a)(b)(c)</code>. A curried function returns a concrete value only when it receives all its arguments! If it does recieve an insufficient amount of arguments, say 1 of 3, it returns a <em>curried function</em>, that returns after receiving 2 arguments.</p> +<p>Currying is the process of transformation of a function call like +<code>f(a, b, c)</code> to <code>f(a)(b)(c)</code>. A curried function +returns a concrete value only when it receives all its arguments! If it +does recieve an insufficient amount of arguments, say 1 of 3, it returns +a <em>curried function</em>, that returns after receiving 2 +arguments.</p> <pre><code>curry(f(a, b, c)) = h(a)(b)(c) h(x) = g &lt;- curried function that takes upto 2 args (g) @@ -1226,49 +1875,86 @@ k(z) = v &lt;- a value (v) Keen readers will conclude the following, h(x)(y)(z) = g(y)(z) = k(z) = v</code></pre> -<p>Mathematically, if <code>f</code> is a function that takes two arguments <code>x</code> and <code>y</code>, such that <code>x ϵ X</code>, and <code>y ϵ Y</code> , we write it as:</p> +<p>Mathematically, if <code>f</code> is a function that takes two +arguments <code>x</code> and <code>y</code>, such that +<code>x ϵ X</code>, and <code>y ϵ Y</code> , we write it as:</p> <pre><code>f: (X × Y) -&gt; Z</code></pre> -<p>where <code>×</code> denotes the Cartesian product of set <code>X</code> and <code>Y</code>, and curried <code>f</code> (denoted by <code>h</code> here) is written as:</p> +<p>where <code>×</code> denotes the Cartesian product of set +<code>X</code> and <code>Y</code>, and curried <code>f</code> (denoted +by <code>h</code> here) is written as:</p> <pre><code>h: X -&gt; (Y -&gt; Z)</code></pre> <h3 id="procedural-macros">Procedural Macros</h3> -<p>These are functions that take code as input and spit out modified code as output. Powerful stuff. Rust has three kinds of proc-macros:</p> +<p>These are functions that take code as input and spit out modified +code as output. Powerful stuff. Rust has three kinds of proc-macros:</p> <ul> <li>Function like macros<br /> </li> -<li>Derive macros: <code>#[derive(...)]</code>, used to automatically implement traits for structs/enums<br /> +<li>Derive macros: <code>#[derive(...)]</code>, used to automatically +implement traits for structs/enums<br /> </li> -<li>and Attribute macros: <code>#[test]</code>, usually slapped onto functions</li> +<li>and Attribute macros: <code>#[test]</code>, usually slapped onto +functions</li> </ul> -<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> +<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" 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> +<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" 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="cf">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" 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> +<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" 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="cf">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="cf">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="cf">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> -<p>If you have been following along, you should be able to tell that the return type of <code>add_curried1</code> is:</p> +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> +<p>If you have been following along, you should be able to tell that the +return type of <code>add_curried1</code> is:</p> <pre><code>impl Fn(u32) -&gt; (impl Fn(u32) -&gt; u32)</code></pre> -<p>We can drop the parentheses because <code>-&gt;</code> is right associative:</p> +<p>We can drop the parentheses because <code>-&gt;</code> is right +associative:</p> <pre><code>impl Fn(u32) -&gt; impl Fn(u32) -&gt; u32 </code></pre> <p><strong>Accessing environment</strong><br /> -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> +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" 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> +<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" 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="cf">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> +<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 --&gt; src/main.rs:17:37 @@ -1276,21 +1962,33 @@ and inherent method return types | fn add(x: u32) -&gt; impl Fn(u32) -&gt; impl Fn(u32) -&gt; u32 | ^^^^^^^^^^^^^^^^^^^ </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" 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> +<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" 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-8"><a href="#cb10-8" aria-hidden="true" tabindex="-1"></a> <span class="cf">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> +<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> -<p>Initialize your workspace with <code>cargo new --lib currying</code>. Proc-macro crates are libraries with exactly one export, the macro itself. Add a <code>tests</code> directory to your crate root. Your directory should look something like this:</p> +<p>Let us write the magical bits that take us from function to curried +function.</p> +<p>Initialize your workspace with <code>cargo new --lib currying</code>. +Proc-macro crates are libraries with exactly one export, the macro +itself. Add a <code>tests</code> directory to your crate root. Your +directory should look something like this:</p> <pre><code>. ├── Cargo.toml ├── src @@ -1300,9 +1998,11 @@ and inherent method return types <h4 id="dependencies">Dependencies</h4> <p>We will be using a total of 3 external crates:</p> <ul> -<li><a href="https://docs.rs/proc-macro2/1.0.12/proc_macro2/">proc_macro2</a></li> +<li><a +href="https://docs.rs/proc-macro2/1.0.12/proc_macro2/">proc_macro2</a></li> <li><a href="https://docs.rs/syn/1.0.18/syn/index.html">syn</a></li> -<li><a href="https://docs.rs/quote/1.0.4/quote/index.html">quote</a></li> +<li><a +href="https://docs.rs/quote/1.0.4/quote/index.html">quote</a></li> </ul> <p>Here’s a sample <code>Cargo.toml</code>:</p> <pre><code># Cargo.toml @@ -1317,10 +2017,12 @@ features = [&quot;full&quot;] [lib] 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> +<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" tabindex="-1"></a><span class="co">// src/lib.rs</span></span> +<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> @@ -1334,17 +2036,49 @@ proc-macro = true # this is important!</code></pre> <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> -<p><code>ItemFn</code> from the <code>syn</code> crate holds the parsed <code>TokenStream</code> of a Rust function. <code>parse_macro_input!</code> is a helper macro provided by <code>syn</code>.</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> +<p><code>ItemFn</code> from the <code>syn</code> crate holds the parsed +<code>TokenStream</code> of a Rust function. +<code>parse_macro_input!</code> is a helper macro provided by +<code>syn</code>.</p> <p><strong>2. The lone export</strong></p> -<p>Annotate the only <code>pub</code> of our crate with <code>#[proc_macro_attribute]</code>. This tells rustc that <code>curry</code> is a procedural macro, and allows us to use it as <code>#[crate_name::curry]</code> in other crates. Note the signature of the <code>curry</code> function. <code>_attr</code> is the <code>TokenStream</code> representing the attribute itself, <code>item</code> refers to the thing we slapped our macro into, in this case a function (like <code>add</code>). The return value is a modified <code>TokenStream</code>, this will contain our curried version of <code>add</code>.</p> +<p>Annotate the only <code>pub</code> of our crate with +<code>#[proc_macro_attribute]</code>. This tells rustc that +<code>curry</code> is a procedural macro, and allows us to use it as +<code>#[crate_name::curry]</code> in other crates. Note the signature of +the <code>curry</code> function. <code>_attr</code> is the +<code>TokenStream</code> representing the attribute itself, +<code>item</code> refers to the thing we slapped our macro into, in this +case a function (like <code>add</code>). The return value is a modified +<code>TokenStream</code>, this will contain our curried version of +<code>add</code>.</p> <p><strong>3. The helper macro</strong></p> -<p>A <code>TokenStream</code> is a little hard to work with, which is why we have the <code>syn</code> crate, which provides types to represent Rust tokens. An <code>RArrow</code> struct to represent the return arrow on a function and so on. One of those types is <code>ItemFn</code>, that represents an entire Rust function. The <code>parse_macro_input!</code> automatically puts the input to our macro into an <code>ItemFn</code>. What a gentleman!</p> +<p>A <code>TokenStream</code> is a little hard to work with, which is +why we have the <code>syn</code> crate, which provides types to +represent Rust tokens. An <code>RArrow</code> struct to represent the +return arrow on a function and so on. One of those types is +<code>ItemFn</code>, that represents an entire Rust function. The +<code>parse_macro_input!</code> automatically puts the input to our +macro into an <code>ItemFn</code>. What a gentleman!</p> <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" tabindex="-1"></a><span class="co">// src/lib.rs</span></span> +<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" 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> @@ -1354,7 +2088,9 @@ proc-macro = true # this is important!</code></pre> <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> +<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) / fn add(x: u32, y: u32) -&gt; u32 @@ -1364,42 +2100,77 @@ syn::token::Fn --&#39; / \ (output) Punctuated&lt;FnArg, Comma&gt; (inputs)</code></pre> <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" 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>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" tabindex="-1"></a><span class="cf">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" 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" tabindex="-1"></a><span class="co">// src/lib.rs</span></span> +<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="cf">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" 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-6"><a href="#cb18-6" aria-hidden="true" tabindex="-1"></a> <span class="cf">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" tabindex="-1"></a><span class="co">// src/lib.rs</span></span> +<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" 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-4"><a href="#cb19-4" aria-hidden="true" tabindex="-1"></a> <span class="cf">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" tabindex="-1"></a><span class="co">// src/lib.rs</span></span> +<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" 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-5"><a href="#cb20-5" aria-hidden="true" tabindex="-1"></a> <span class="cf">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" tabindex="-1"></a><span class="co">// src/lib.rs</span></span> +<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" 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> @@ -1416,10 +2187,11 @@ syn::token::Fn --&#39; / \ (output) <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-18"><a href="#cb21-18" aria-hidden="true" tabindex="-1"></a> <span class="cf">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" tabindex="-1"></a><span class="co">// tests/smoke.rs</span></span> +<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> @@ -1430,17 +2202,23 @@ syn::token::Fn --&#39; / \ (output) <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> +<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" tabindex="-1"></a><span class="kw">type</span> T0 <span class="op">=</span> <span class="dt">u32</span><span class="op">;</span></span> +<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" 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" 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> +<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="cf">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> @@ -1452,42 +2230,59 @@ syn::token::Fn --&#39; / \ (output) <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" tabindex="-1"></a><span class="co">// src/lib.rs</span></span> +<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" 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-6"><a href="#cb26-6" aria-hidden="true" tabindex="-1"></a> <span class="cf">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-13"><a href="#cb26-13" aria-hidden="true" tabindex="-1"></a> <span class="cf">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> +<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" tabindex="-1"></a><span class="kw">type</span> T0 <span class="op">=</span> <span class="dt">u32</span></span> +<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" 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" tabindex="-1"></a><span class="co">// src/lib.rs</span></span> +<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" 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-4"><a href="#cb28-4" aria-hidden="true" tabindex="-1"></a> <span class="cf">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" tabindex="-1"></a><span class="co">// src/lib.rs</span></span> +<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" 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> @@ -1501,7 +2296,7 @@ syn::token::Fn --&#39; / \ (output) <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-15"><a href="#cb29-15" aria-hidden="true" tabindex="-1"></a> <span class="cf">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> @@ -1510,45 +2305,70 @@ syn::token::Fn --&#39; / \ (output) <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-24"><a href="#cb29-24" aria-hidden="true" tabindex="-1"></a> <span class="cf">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> +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" tabindex="-1"></a><span class="kw">type</span> T0 <span class="op">=</span> something</span> +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" 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" tabindex="-1"></a><span class="at">#[</span>curry<span class="at">]</span></span> +<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" 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" tabindex="-1"></a><span class="kw">type</span> T0 <span class="op">=</span> <span class="dt">u32</span><span class="op">;</span></span> +<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" tabindex="-1"></a><span class="kw">type</span> _add_T0 <span class="op">=</span> <span class="dt">u32</span><span class="op">;</span></span> +<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" 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>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> +<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" tabindex="-1"></a><span class="co">// src/lib.rs</span></span> +<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" 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> @@ -1572,20 +2392,39 @@ I’ve got some explanation to do on this line. Clearly, we are trying to write <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-25"><a href="#cb34-25" aria-hidden="true" tabindex="-1"></a><span class="op">+</span> <span class="cf">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> +<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> <h3 id="debugging-and-testing">Debugging and Testing</h3> <p>Install <code>cargo-expand</code> via:</p> <pre><code>cargo install cargo-expand</code></pre> -<p><code>cargo-expand</code> is a neat little tool that expands your macro in places where it is used, and lets you view the generated code! For example:</p> +<p><code>cargo-expand</code> is a neat little tool that expands your +macro in places where it is used, and lets you view the generated code! +For example:</p> <pre class="shell"><code># create a bin package hello $ cargo new hello @@ -1607,10 +2446,18 @@ fn main() { )); }; }</code></pre> -<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>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" tabindex="-1"></a><span class="co">// tests/smoke.rs</span></span> +<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> @@ -1623,55 +2470,81 @@ fn main() { <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> +<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" tabindex="-1"></a><span class="kw">type</span> _add_T0 <span class="op">=</span> <span class="dt">u32</span><span class="op">;</span></span> +<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" 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-5"><a href="#cb39-5" aria-hidden="true" tabindex="-1"></a> <span class="cf">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-7"><a href="#cb39-7" aria-hidden="true" tabindex="-1"></a> <span class="cf">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" tabindex="-1"></a><span class="at">#[</span>curry<span class="at">]</span></span> +<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" 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-8"><a href="#cb40-8" aria-hidden="true" tabindex="-1"></a> <span class="cf">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" tabindex="-1"></a><span class="kw">let</span> v <span class="op">=</span> add(<span class="dv">5</span>)<span class="op">;</span></span> +<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" 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> +<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> -<p>Currying may not seem to be all that useful. Curried functions are unwieldy in Rust because the standard library is not built around currying. If you enjoy the possibilities posed by currying, consider taking a look at Haskell or Scheme.</p> -<p>My original intention with <a href="https://peppe.rs">peppe.rs</a> was to post condensed articles, a micro blog, but this one turned out extra long.</p> +<p>Currying may not seem to be all that useful. Curried functions are +unwieldy in Rust because the standard library is not built around +currying. If you enjoy the possibilities posed by currying, consider +taking a look at Haskell or Scheme.</p> +<p>My original intention with <a href="https://peppe.rs">peppe.rs</a> +was to post condensed articles, a micro blog, but this one turned out +extra long.</p> <p>Perhaps I should call it a ‘macro’ blog :)</p> -<section class="footnotes" role="doc-endnotes"> +<section id="footnotes" class="footnotes footnotes-end-of-document" +role="doc-endnotes"> <hr /> <ol> -<li id="fn1" role="doc-endnote"><p><a href="https://doc.rust-lang.org/book/ch13-01-closures.html">https://doc.rust-lang.org/book/ch13-01-closures.html</a><a href="#fnref1" class="footnote-back" role="doc-backlink">↩︎</a></p></li> -<li id="fn2" role="doc-endnote"><p><a href="https://caniuse.rs">caniuse.rs</a> contains an indexed list of features and their status.<a href="#fnref2" class="footnote-back" role="doc-backlink">↩︎</a></p></li> +<li id="fn1"><p><a +href="https://doc.rust-lang.org/book/ch13-01-closures.html">https://doc.rust-lang.org/book/ch13-01-closures.html</a><a +href="#fnref1" class="footnote-back" role="doc-backlink">↩︎</a></p></li> +<li id="fn2"><p><a href="https://caniuse.rs">caniuse.rs</a> contains an +indexed list of features and their status.<a href="#fnref2" +class="footnote-back" role="doc-backlink">↩︎</a></p></li> </ol> </section> https://peppe.rs/posts/auto-currying_rust_functions/ @@ -1680,54 +2553,105 @@ test tests::works ... ok</code></pre> Pixel Art In GIMP -<p>I’ve always been an admirer of pixel art, because of it’s simplicity and it’s resemblance to bitmap font design. Recently, I decided to take the dive and make some art of my own.</p> -<p>I used GIMP because I am fairly familiar with it. Aseprite seems to be the editor of choice for animated pixel art though.</p> +<p>I’ve always been an admirer of pixel art, because of it’s simplicity +and it’s resemblance to bitmap font design. Recently, I decided to take +the dive and make some art of my own.</p> +<p>I used GIMP because I am fairly familiar with it. Aseprite seems to +be the editor of choice for animated pixel art though.</p> <h3 id="setting-up-the-canvas">Setting up the canvas</h3> -<p>Picking a canvas size is daunting. Too small, and you won’t be able to fit in enough detail to make a legible piece. Too big and you’ve got too many pixels to work with!</p> -<p>I would suggest starting out with anywhere between 100x100 and 200x200. <a href="https://u.peppe.rs/u9.png">Here’s</a> a sample configuration.</p> -<p>Sometimes I use a 10x10 grid, <code>View &gt; Show Grid</code> and <code>Edit &gt; Preferences &gt; Default Grid &gt; Spacing</code>, but that can get jarring, so I throw down a couple of guides, drag right or down from the left or top gutters for vertical and horizontal guides respectively.</p> +<p>Picking a canvas size is daunting. Too small, and you won’t be able +to fit in enough detail to make a legible piece. Too big and you’ve got +too many pixels to work with!</p> +<p>I would suggest starting out with anywhere between 100x100 and +200x200. <a href="https://u.peppe.rs/u9.png">Here’s</a> a sample +configuration.</p> +<p>Sometimes I use a 10x10 grid, <code>View &gt; Show Grid</code> and +<code>Edit &gt; Preferences &gt; Default Grid &gt; Spacing</code>, but +that can get jarring, so I throw down a couple of guides, drag right or +down from the left or top gutters for vertical and horizontal guides +respectively.</p> <h3 id="choosing-a-brush">Choosing a Brush</h3> -<p>The most important part of our setup is the brush. Use the Pencil Tool (<code>n</code> on the keyboard) for hard edge drawings. Here’s a small comparison if you don’t know the difference between a hard edge and a soft edge:</p> +<p>The most important part of our setup is the brush. Use the Pencil +Tool (<code>n</code> on the keyboard) for hard edge drawings. Here’s a +small comparison if you don’t know the difference between a hard edge +and a soft edge:</p> <figure> -<img src="https://u.peppe.rs/kz.png" alt="Hard edge vs Soft Edge" /><figcaption aria-hidden="true">Hard edge vs Soft Edge</figcaption> +<img src="https://u.peppe.rs/kz.png" alt="Hard edge vs Soft Edge" /> +<figcaption aria-hidden="true">Hard edge vs Soft Edge</figcaption> </figure> -<p>I turn the size down all the way to 1 (<code>[</code> on the keyboard). Set <code>Dynamics</code> off. <a href="https://u.peppe.rs/Fs.png">Here’s</a> a sample brush configuration.</p> +<p>I turn the size down all the way to 1 (<code>[</code> on the +keyboard). Set <code>Dynamics</code> off. <a +href="https://u.peppe.rs/Fs.png">Here’s</a> a sample brush +configuration.</p> <h3 id="laying-down-the-pixels">Laying down the pixels!</h3> -<p>With the boring stuff out of the way, we can start with our piece. I usually follow a three step process:</p> +<p>With the boring stuff out of the way, we can start with our piece. I +usually follow a three step process:</p> <ul> <li>draw a rough outline</li> <li>fill in the shadows</li> <li>add highlights</li> </ul> -<p>But this process is better explained with an example: an onigiri. Let us start off with a 100x100 canvas.</p> +<p>But this process is better explained with an example: an onigiri. Let +us start off with a 100x100 canvas.</p> <h4 id="drawing-the-outline">Drawing the outline</h4> -<p>For the most part, our figure will be symmetric. If you are on GIMP 2.10+, you can take advantage of the Symmetry Painting feature. Go ahead and enable vertical symmetry, <code>Window &gt; Dockable Dialogs &gt; Symmetry Painting</code> and <code>Symmetry Painting &gt; Symmetry &gt; Mirror &gt; Vertical</code>.</p> -<p>If you are running an older version of GIMP, draw in the left side, duplicate the layer, flip it horizontally, and merge it with the original.</p> +<p>For the most part, our figure will be symmetric. If you are on GIMP +2.10+, you can take advantage of the Symmetry Painting feature. Go ahead +and enable vertical symmetry, +<code>Window &gt; Dockable Dialogs &gt; Symmetry Painting</code> and +<code>Symmetry Painting &gt; Symmetry &gt; Mirror &gt; Vertical</code>.</p> +<p>If you are running an older version of GIMP, draw in the left side, +duplicate the layer, flip it horizontally, and merge it with the +original.</p> <p>Your outline might look something like this:</p> <p><img src="https://u.peppe.rs/mn.png" /></p> -<p>Go ahead and fill it in with the fill tool (<code>Shift + b</code> on the keyboard), add in some seaweed as well, preferably on a different layer. You can toggle symmetry on and off to save yourself some time.</p> +<p>Go ahead and fill it in with the fill tool (<code>Shift + b</code> on +the keyboard), add in some seaweed as well, preferably on a different +layer. You can toggle symmetry on and off to save yourself some +time.</p> <p><img src="https://u.peppe.rs/xu.png" /></p> <h4 id="shadows">Shadows</h4> -<p>For now, let us focus on the shadows on the object itself, we’ll come back to the shadows cast by the object on the surface later.</p> -<p>Shadows on any surface always follow the shape of the surface. A spherical onigiri would have a circular shadow:</p> +<p>For now, let us focus on the shadows on the object itself, we’ll come +back to the shadows cast by the object on the surface later.</p> +<p>Shadows on any surface always follow the shape of the surface. A +spherical onigiri would have a circular shadow:</p> <p><img src="https://u.peppe.rs/FU.png" /></p> <p>A couple of noticeable changes:</p> -<p><strong>Layers</strong>: The layer containing the seaweed has been hidden.<br /> -<strong>Color</strong>: The color of the shadow is just a slightly lighter version of the original object (reduce the Value on the HSV scale).<br /> -<strong>Area</strong>: The shadow does not go all the way (notice the bottom edges).</p> -<p>The shadow does not go all the way because we will be filling in that area with another, darker shadow! An image might explain better:</p> +<p><strong>Layers</strong>: The layer containing the seaweed has been +hidden.<br /> +<strong>Color</strong>: The color of the shadow is just a slightly +lighter version of the original object (reduce the Value on the HSV +scale).<br /> +<strong>Area</strong>: The shadow does not go all the way (notice the +bottom edges).</p> +<p>The shadow does not go all the way because we will be filling in that +area with another, darker shadow! An image might explain better:</p> <p><img src="https://u.peppe.rs/Br.png" /></p> -<p>To emulate soft lights, reduce the value by 2 to 3 points every iteration. Notice how area <code>1</code> is much larger than area <code>4</code>. This is because an onigiri resembles a bottom heavy oblate spheroid, a sphere that is slightly fatter around the lower bottom, and areas <code>1</code> and <code>2</code> catch more light than areas <code>3</code> and <code>4</code>.</p> -<p>Do the same with the seaweed. The seaweed, being a smaller, flatter object, doesn’t cast much of a shadow, so stop with 1 or 2 iterations of the gradient:</p> +<p>To emulate soft lights, reduce the value by 2 to 3 points every +iteration. Notice how area <code>1</code> is much larger than area +<code>4</code>. This is because an onigiri resembles a bottom heavy +oblate spheroid, a sphere that is slightly fatter around the lower +bottom, and areas <code>1</code> and <code>2</code> catch more light +than areas <code>3</code> and <code>4</code>.</p> +<p>Do the same with the seaweed. The seaweed, being a smaller, flatter +object, doesn’t cast much of a shadow, so stop with 1 or 2 iterations of +the gradient:</p> <p><img src="https://u.peppe.rs/T3.png" /></p> <p>We’re getting there!</p> <h4 id="highlights">Highlights</h4> -<p>This step handles the details on the strongly illuminated portions of the object. Seaweed is a bit glossy, lighten the edges to make it seem shiny. The rice is not as shiny, but it does form an uneven surface. Add in some shadows to promote the idea of rice grains. Here is the finished result:</p> +<p>This step handles the details on the strongly illuminated portions of +the object. Seaweed is a bit glossy, lighten the edges to make it seem +shiny. The rice is not as shiny, but it does form an uneven surface. Add +in some shadows to promote the idea of rice grains. Here is the finished +result:</p> <p><img src="https://u.peppe.rs/VE.png" /></p> <h3 id="finishing-touches">Finishing Touches</h3> -<p>Some color correction and <code>a e s t h e t i c</code> Japanese text later, our piece is complete!</p> +<p>Some color correction and <code>a e s t h e t i c</code> Japanese +text later, our piece is complete!</p> <p><img src="https://u.peppe.rs/cn.png" /></p> -<p>Hold on, why is it so tiny? Well, that’s because our canvas was 100x100, head over to <code>Image &gt; Scale Image</code>, set <code>Quality &gt; Interpolation</code> to <code>None</code> and scale it up to 700x700, et voilà!</p> +<p>Hold on, why is it so tiny? Well, that’s because our canvas was +100x100, head over to <code>Image &gt; Scale Image</code>, set +<code>Quality &gt; Interpolation</code> to <code>None</code> and scale +it up to 700x700, et voilà!</p> <p><img src="https://u.peppe.rs/CH.png" /></p> https://peppe.rs/posts/pixel_art_in_GIMP/ Wed, 08 Apr 2020 18:30:00 +0000 @@ -1735,9 +2659,14 @@ 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" 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> +<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" 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> @@ -1747,7 +2676,8 @@ test tests::works ... ok</code></pre> <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" 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> +<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> @@ -1757,19 +2687,38 @@ test tests::works ... ok</code></pre> <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" tabindex="-1"></a><span class="co"># `grep -l pattern files` lists all the files</span></span> +<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" 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> +<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> <h3 id="the-quickfix-list">The quickfix list</h3> -<p>Next up, replacing <code>r#" ... "#</code> with <code>json!( ... )</code>. I couldn’t search and replace that trivially, so I went with a macro call <a href="#fn2" class="footnote-ref" id="fnref2" role="doc-noteref"><sup>2</sup></a> instead, starting with the cursor on ‘r’, represented by the caret, in my attempt to breakdown the process:</p> +<p>Next up, replacing <code>r#" ... "#</code> with +<code>json!( ... )</code>. I couldn’t search and replace that trivially, +so I went with a macro call <a href="#fn2" class="footnote-ref" +id="fnref2" role="doc-noteref"><sup>2</sup></a> instead, starting with +the cursor on ‘r’, represented by the caret, in my attempt to breakdown +the process:</p> <pre><code>BUFFER: r#&quot; ... &quot;#; ^ @@ -1786,42 +2735,80 @@ BUFFER: json!( ... &quot;#; ACTION: vhs)&lt;esc&gt; BUFFER: json!( ... );</code></pre> -<p>Here’s the recorded <a href="#fn3" class="footnote-ref" id="fnref3" role="doc-noteref"><sup>3</sup></a> macro in all its glory: <code>vllsjson!(&lt;esc&gt;$F#vhs)&lt;esc&gt;</code>.</p> -<p>Great! So now we just go ahead, find every occurrence of <code>r#</code> and apply the macro right? Unfortunately, there were more than a few occurrences of raw strings that had to stay raw strings. Enter, the quickfix list.</p> -<p>The idea behind the quickfix list is to jump from one position in a file to another (maybe in a different file), much like how the arglist lets you jump from one file to another.</p> -<p>One of the easiest ways to populate this list with a bunch of positions is to use <code>vimgrep</code>:</p> +<p>Here’s the recorded <a href="#fn3" class="footnote-ref" id="fnref3" +role="doc-noteref"><sup>3</sup></a> macro in all its glory: +<code>vllsjson!(&lt;esc&gt;$F#vhs)&lt;esc&gt;</code>.</p> +<p>Great! So now we just go ahead, find every occurrence of +<code>r#</code> and apply the macro right? Unfortunately, there were +more than a few occurrences of raw strings that had to stay raw strings. +Enter, the quickfix list.</p> +<p>The idea behind the quickfix list is to jump from one position in a +file to another (maybe in a different file), much like how the arglist +lets you jump from one file to another.</p> +<p>One of the easiest ways to populate this list with a bunch of +positions is to use <code>vimgrep</code>:</p> <pre><code># basic usage :vimgrep pattern files # search for raw strings :vimgrep &#39;r#&#39; ./**/*.rs</code></pre> -<p>Like <code>:next</code> and <code>:prev</code>, you can navigate the quickfix list with <code>:cnext</code> and <code>:cprev</code>. Every time you move up or down the list, vim indicates your index:</p> +<p>Like <code>:next</code> and <code>:prev</code>, you can navigate the +quickfix list with <code>:cnext</code> and <code>:cprev</code>. Every +time you move up or down the list, vim indicates your index:</p> <pre><code>(1 of 131): r#&quot;{&quot;set_tweak&quot;: &quot;highlight&quot;}&quot;#;</code></pre> -<p>And just like <code>argdo</code>, you can <code>cdo</code> to apply commands to <em>every</em> match in the quickfix list:</p> +<p>And just like <code>argdo</code>, you can <code>cdo</code> to apply +commands to <em>every</em> match in the quickfix list:</p> <pre><code>:cdo norm! @q</code></pre> -<p>But, I had to manually pick out matches, and it involved some button mashing.</p> +<p>But, I had to manually pick out matches, and it involved some button +mashing.</p> <h3 id="external-filtering">External Filtering</h3> -<p>Some code reviews later, I was asked to format all the json inside the <code>json!</code> macro. All you have to do is pass a visual selection through a pretty json printer. Select the range to be formatted in visual mode, and hit <code>:</code>, you will notice the command line displaying what seems to be gibberish:</p> +<p>Some code reviews later, I was asked to format all the json inside +the <code>json!</code> macro. All you have to do is pass a visual +selection through a pretty json printer. Select the range to be +formatted in visual mode, and hit <code>:</code>, you will notice the +command line displaying what seems to be gibberish:</p> <pre><code>:&#39;&lt;,&#39;&gt;</code></pre> -<p><code>'&lt;</code> and <code>'&gt;</code> are <em>marks</em> <a href="#fn4" class="footnote-ref" id="fnref4" role="doc-noteref"><sup>4</sup></a>. More specifically, they are marks that vim sets automatically every time you make a visual selection, denoting the start and end of the selection.</p> -<p>A range is one or more line specifiers separated by a <code>,</code>:</p> +<p><code>'&lt;</code> and <code>'&gt;</code> are <em>marks</em> <a +href="#fn4" class="footnote-ref" id="fnref4" +role="doc-noteref"><sup>4</sup></a>. More specifically, they are marks +that vim sets automatically every time you make a visual selection, +denoting the start and end of the selection.</p> +<p>A range is one or more line specifiers separated by a +<code>,</code>:</p> <pre><code>:1,7 lines 1 through 7 :32 just line 32 :. the current line :.,$ the current line to the last line :&#39;a,&#39;b mark &#39;a&#39; to mark &#39;b&#39;</code></pre> -<p>Most <code>:</code> commands can be prefixed by ranges. <code>:help usr_10.txt</code> for more on that.</p> -<p>Alright, lets pass json through <code>python -m json.tool</code>, a json formatter that accepts <code>stdin</code> (note the use of <code>!</code> to make use of an external program):</p> +<p>Most <code>:</code> commands can be prefixed by ranges. +<code>:help usr_10.txt</code> for more on that.</p> +<p>Alright, lets pass json through <code>python -m json.tool</code>, a +json formatter that accepts <code>stdin</code> (note the use of +<code>!</code> to make use of an external program):</p> <pre><code>:&#39;&lt;,&#39;&gt;!python -m json.tool</code></pre> -<p>Unfortunately that didn’t quite work for me because the range included some non-json text as well, a mix of regex and macros helped fix that. I think you get the drift.</p> -<p>Another fun filter I use from time to time is <code>:!sort</code>, to sort css attributes, or <code>:!uniq</code> to remove repeated imports.</p> -<section class="footnotes" role="doc-endnotes"> +<p>Unfortunately that didn’t quite work for me because the range +included some non-json text as well, a mix of regex and macros helped +fix that. I think you get the drift.</p> +<p>Another fun filter I use from time to time is <code>:!sort</code>, to +sort css attributes, or <code>:!uniq</code> to remove repeated +imports.</p> +<section id="footnotes" class="footnotes footnotes-end-of-document" +role="doc-endnotes"> <hr /> <ol> -<li id="fn1" role="doc-endnote"><p>https://github.com/tpope/vim-unimpaired It also handles various other mappings, <code>]q</code> and <code>[q</code> to navigate the quickfix list for example<a href="#fnref1" class="footnote-back" role="doc-backlink">↩︎</a></p></li> -<li id="fn2" role="doc-endnote"><p><code>:help recording</code><a href="#fnref2" class="footnote-back" role="doc-backlink">↩︎</a></p></li> -<li id="fn3" role="doc-endnote"><p>When I’m recording a macro, I prefer starting out by storing it in register <code>q</code>, and then copying it over to another register if it works as intended. I think of <code>qq</code> as ‘quick record’.<a href="#fnref3" class="footnote-back" role="doc-backlink">↩︎</a></p></li> -<li id="fn4" role="doc-endnote"><p><code>:help mark-motions</code><a href="#fnref4" class="footnote-back" role="doc-backlink">↩︎</a></p></li> +<li id="fn1"><p>https://github.com/tpope/vim-unimpaired It also handles +various other mappings, <code>]q</code> and <code>[q</code> to navigate +the quickfix list for example<a href="#fnref1" class="footnote-back" +role="doc-backlink">↩︎</a></p></li> +<li id="fn2"><p><code>:help recording</code><a href="#fnref2" +class="footnote-back" role="doc-backlink">↩︎</a></p></li> +<li id="fn3"><p>When I’m recording a macro, I prefer starting out by +storing it in register <code>q</code>, and then copying it over to +another register if it works as intended. I think of <code>qq</code> as +‘quick record’.<a href="#fnref3" class="footnote-back" +role="doc-backlink">↩︎</a></p></li> +<li id="fn4"><p><code>:help mark-motions</code><a href="#fnref4" +class="footnote-back" role="doc-backlink">↩︎</a></p></li> </ol> </section> https://peppe.rs/posts/rapid_refactoring_with_vim/ @@ -1830,34 +2817,75 @@ BUFFER: json!( ... );</code></pre> Font Size Fallacies -<p>I am not an expert with fonts, but I do have some experience <a href="#fn1" class="footnote-ref" id="fnref1" role="doc-noteref"><sup>1</sup></a>, and common sense. This post aims to debunk some misconceptions about font sizes!</p> -<p>11 px on your display is <em>probably not</em> 11 px on my display. Let’s do some quick math. I have two displays, 1366x768 @ 21" and another with 1920x1080 @ 13", call them <code>A</code> and <code>B</code> for now.</p> -<p>Display <code>A</code> has 1,049,088 pixels. A pixel is a square, of side say, <code>s</code> cm. The total area covered by my 21" display is about 1,066 cm^2 (41x26). Thus,</p> +<p>I am not an expert with fonts, but I do have some experience <a +href="#fn1" class="footnote-ref" id="fnref1" +role="doc-noteref"><sup>1</sup></a>, and common sense. This post aims to +debunk some misconceptions about font sizes!</p> +<p>11 px on your display is <em>probably not</em> 11 px on my display. +Let’s do some quick math. I have two displays, 1366x768 @ 21” and +another with 1920x1080 @ 13”, call them <code>A</code> and +<code>B</code> for now.</p> +<p>Display <code>A</code> has 1,049,088 pixels. A pixel is a square, of +side say, <code>s</code> cm. The total area covered by my 21” display is +about 1,066 cm^2 (41x26). Thus,</p> <pre><code>Display A Dimensions: 1366x768 @ 21&quot; (41x26 sq. cm) 1,049,088 s^2 = 1066 s = 0.0318 cm (side of a pixel on Display A)</code></pre> -<p>Bear with me, as I repeat the number crunching for Display <code>B</code>:</p> +<p>Bear with me, as I repeat the number crunching for Display +<code>B</code>:</p> <pre><code>Display B Dimensions: 1920x1080 @ 13&quot; (29.5x16.5 sq. cm) 2,073,600 s^2 = 486.75 s = 0.0153 cm (side of a pixel on Display B)</code></pre> -<p>The width of a pixel on Display <code>A</code> is <em>double</em> the width of a pixel on Display <code>B</code>. The area occupied by a pixel on Display <code>A</code> is <em>4 times</em> the area occupied by a pixel on Display <code>B</code>.</p> +<p>The width of a pixel on Display <code>A</code> is <em>double</em> the +width of a pixel on Display <code>B</code>. The area occupied by a pixel +on Display <code>A</code> is <em>4 times</em> the area occupied by a +pixel on Display <code>B</code>.</p> <p><em>The size of a pixel varies from display to display!</em></p> -<p>A 5x11 bitmap font on Display <code>A</code> would be around 4 mm tall whereas the same bitmap font on Display <code>B</code> would be around 1.9 mm tall. A 11 px tall character on <code>B</code> is visually equivalent to a 5 px character on <code>A</code>. When you view a screenshot of Display <code>A</code> on Display <code>B</code>, the contents are shrunk down by a factor of 2!</p> -<p>So screen resolution is not enough, how else do we measure size? Pixel Density! Keen readers will realize that the 5^th grade math problem we solved up there showcases pixel density, or, pixels per cm (PPCM). Usually we deal with pixels per inch (PPI).</p> -<p><strong>Note:</strong> PPI is not to be confused with DPI <a href="#fn2" class="footnote-ref" id="fnref2" role="doc-noteref"><sup>2</sup></a> (dots per inch). DPI is defined for printers.</p> -<p>In our example, <code>A</code> is a 75 ppi display and <code>B</code> is around 165 ppi <a href="#fn3" class="footnote-ref" id="fnref3" role="doc-noteref"><sup>3</sup></a>. A low ppi display appears to be ‘pixelated’, because the pixels are more prominent, much like Display <code>A</code>. A higher ppi usually means you can view larger images and render crispier fonts. The average desktop display can stuff 100-200 pixels per inch. Smart phones usually fall into the 400-600 ppi (XXXHDPI) category. The human eye fails to differentiate detail past 300 ppi.</p> -<p><em>So … streaming an 8K video on a 60" TV provides the same clarity as a HD video on a smart phone?</em></p> -<p>Absolutely. Well, clarity is subjective, but the amount of detail you can discern on mobile displays has always been limited. Salty consumers of the Xperia 1 <a href="#fn4" class="footnote-ref" id="fnref4" role="doc-noteref"><sup>4</sup></a> will say otherwise.</p> -<p>Maybe I will talk about font rendering in another post, but thats all for now. Don’t judge a font size by its screenshot.</p> -<section class="footnotes" role="doc-endnotes"> +<p>A 5x11 bitmap font on Display <code>A</code> would be around 4 mm +tall whereas the same bitmap font on Display <code>B</code> would be +around 1.9 mm tall. A 11 px tall character on <code>B</code> is visually +equivalent to a 5 px character on <code>A</code>. When you view a +screenshot of Display <code>A</code> on Display <code>B</code>, the +contents are shrunk down by a factor of 2!</p> +<p>So screen resolution is not enough, how else do we measure size? +Pixel Density! Keen readers will realize that the 5^th grade math +problem we solved up there showcases pixel density, or, pixels per cm +(PPCM). Usually we deal with pixels per inch (PPI).</p> +<p><strong>Note:</strong> PPI is not to be confused with DPI <a +href="#fn2" class="footnote-ref" id="fnref2" +role="doc-noteref"><sup>2</sup></a> (dots per inch). DPI is defined for +printers.</p> +<p>In our example, <code>A</code> is a 75 ppi display and <code>B</code> +is around 165 ppi <a href="#fn3" class="footnote-ref" id="fnref3" +role="doc-noteref"><sup>3</sup></a>. A low ppi display appears to be +‘pixelated’, because the pixels are more prominent, much like Display +<code>A</code>. A higher ppi usually means you can view larger images +and render crispier fonts. The average desktop display can stuff 100-200 +pixels per inch. Smart phones usually fall into the 400-600 ppi +(XXXHDPI) category. The human eye fails to differentiate detail past 300 +ppi.</p> +<p><em>So … streaming an 8K video on a 60” TV provides the same clarity +as a HD video on a smart phone?</em></p> +<p>Absolutely. Well, clarity is subjective, but the amount of detail you +can discern on mobile displays has always been limited. Salty consumers +of the Xperia 1 <a href="#fn4" class="footnote-ref" id="fnref4" +role="doc-noteref"><sup>4</sup></a> will say otherwise.</p> +<p>Maybe I will talk about font rendering in another post, but thats all +for now. Don’t judge a font size by its screenshot.</p> +<section id="footnotes" class="footnotes footnotes-end-of-document" +role="doc-endnotes"> <hr /> <ol> -<li id="fn1" role="doc-endnote"><p>https://github.com/nerdypepper/scientifica<a href="#fnref1" class="footnote-back" role="doc-backlink">↩︎</a></p></li> -<li id="fn2" role="doc-endnote"><p>https://en.wikipedia.org/wiki/Dots_per_inch<a href="#fnref2" class="footnote-back" role="doc-backlink">↩︎</a></p></li> -<li id="fn3" role="doc-endnote"><p>https://www.sven.de/dpi/<a href="#fnref3" class="footnote-back" role="doc-backlink">↩︎</a></p></li> -<li id="fn4" role="doc-endnote"><p>https://en.wikipedia.org/wiki/Sony_Xperia_1<a href="#fnref4" class="footnote-back" role="doc-backlink">↩︎</a></p></li> +<li id="fn1"><p>https://github.com/nerdypepper/scientifica<a +href="#fnref1" class="footnote-back" role="doc-backlink">↩︎</a></p></li> +<li id="fn2"><p>https://en.wikipedia.org/wiki/Dots_per_inch<a +href="#fnref2" class="footnote-back" role="doc-backlink">↩︎</a></p></li> +<li id="fn3"><p>https://www.sven.de/dpi/<a href="#fnref3" +class="footnote-back" role="doc-backlink">↩︎</a></p></li> +<li id="fn4"><p>https://en.wikipedia.org/wiki/Sony_Xperia_1<a +href="#fnref4" class="footnote-back" role="doc-backlink">↩︎</a></p></li> </ol> </section> https://peppe.rs/posts/font_size_fallacies/ @@ -1866,87 +2894,153 @@ Dimensions: 1920x1080 @ 13&quot; (29.5x16.5 sq. cm) Termux Tandem -<p>I learnt about <code>termux</code> from a friend on IRC recently. It looked super gimmicky to me at first, but it eventually proved to be useful. Here’s what I use it for:</p> +<p>I learnt about <code>termux</code> from a friend on IRC recently. It +looked super gimmicky to me at first, but it eventually proved to be +useful. Here’s what I use it for:</p> <h3 id="rsync">rsync</h3> -<p>Ever since I degoogled my android device, syncing files between my phone and my PC has always been a pain. I’m looking at you MTP. But, with <code>termux</code> and <code>sshd</code> all set up, it’s as simple as:</p> +<p>Ever since I degoogled my android device, syncing files between my +phone and my PC has always been a pain. I’m looking at you MTP. But, +with <code>termux</code> and <code>sshd</code> all set up, it’s as +simple as:</p> <pre><code>$ arp Address HWtype HWad ... 192.168.43.187 ether d0:0 ... $ rsync -avz 192.168.43.187:~/frogs ~/pics/frogs</code></pre> <h3 id="ssh-tmux">ssh &amp; tmux</h3> -<p>My phone doubles as a secondary view into my main machine with <code>ssh</code> and <code>tmux</code>. When I am away from my PC (read: sitting across the room), I check build status and IRC messages by <code>ssh</code>ing into a tmux session running the said build or weechat.</p> +<p>My phone doubles as a secondary view into my main machine with +<code>ssh</code> and <code>tmux</code>. When I am away from my PC (read: +sitting across the room), I check build status and IRC messages by +<code>ssh</code>ing into a tmux session running the said build or +weechat.</p> <h3 id="file-uploads">file uploads</h3> -<p>Not being able to access my (ssh-only) file host was crippling. With a <code>bash</code> instance on my phone, I just copied over my ssh keys, and popped in a file upload script (a glorified <code>scp</code>). Now I just have to figure out a way to clean up these file names …</p> +<p>Not being able to access my (ssh-only) file host was crippling. With +a <code>bash</code> instance on my phone, I just copied over my ssh +keys, and popped in a file upload script (a glorified <code>scp</code>). +Now I just have to figure out a way to clean up these file names …</p> <pre><code>~/storage/pictures/ $ ls 02muf5g7b2i41.jpg 7alt3cwg77841.jpg cl4bsrge7id11.png mtZabXG.jpg p8d5c584f2841.jpg vjUxGjq.jpg</code></pre> <h3 id="cmus">cmus</h3> -<p>Alright, I don’t really listen to music via <code>cmus</code>, but I did use it a couple times when my default music player was acting up. <code>cmus</code> is a viable option:</p> -<p><a href="https://u.peppe.rs/CP.jpg"><img src="https://u.peppe.rs/CP.jpg" /></a></p> +<p>Alright, I don’t really listen to music via <code>cmus</code>, but I +did use it a couple times when my default music player was acting up. +<code>cmus</code> is a viable option:</p> +<p><a href="https://u.peppe.rs/CP.jpg"><img +src="https://u.peppe.rs/CP.jpg" /></a></p> https://peppe.rs/posts/termux_tandem/ Sat, 07 Mar 2020 18:30:00 +0000 https://peppe.rs/posts/termux_tandem/ Call To ARMs -<p>My 4th semester involves ARM programming. And proprietary tooling (Keil C). But we don’t do that here.</p> +<p>My 4th semester involves ARM programming. And proprietary tooling +(Keil C). But we don’t do that here.</p> <h3 id="building">Building</h3> -<p>Assembling and linking ARM binaries on non-ARM architecture devices is fairly trivial. I went along with the GNU cross bare metal toolchain binutils, which provides <code>arm-as</code> and <code>arm-ld</code> (among a bunch of other utils that I don’t care about for now).</p> +<p>Assembling and linking ARM binaries on non-ARM architecture devices +is fairly trivial. I went along with the GNU cross bare metal toolchain +binutils, which provides <code>arm-as</code> and <code>arm-ld</code> +(among a bunch of other utils that I don’t care about for now).</p> <p>Assemble <code>.s</code> files with:</p> <pre class="shell"><code>arm-none-eabi-as main.s -g -march=armv8.1-a -o main.out</code></pre> -<p>The <code>-g</code> flag generates extra debugging information that <code>gdb</code> picks up. The <code>-march</code> option establishes target architecture.</p> +<p>The <code>-g</code> flag generates extra debugging information that +<code>gdb</code> picks up. The <code>-march</code> option establishes +target architecture.</p> <p>Link <code>.o</code> files with:</p> <pre class="shell"><code>arm-none-eabi-ld main.out -o main</code></pre> <h3 id="running-and-debugging">Running (and Debugging)</h3> -<p>Things get interesting here. <code>gdb</code> on your x86 machine cannot read nor execute binaries compiled for ARM. So, we simulate an ARM processor using <code>qemu</code>. Now qemu allows you to run <code>gdbserver</code> on startup. Connecting our local <code>gdb</code> instance to <code>gdbserver</code> gives us a view into the program’s execution. Easy!</p> -<p>Run <code>qemu</code>, with <code>gdbserver</code> on port <code>1234</code>, with our ARM binary, <code>main</code>:</p> +<p>Things get interesting here. <code>gdb</code> on your x86 machine +cannot read nor execute binaries compiled for ARM. So, we simulate an +ARM processor using <code>qemu</code>. Now qemu allows you to run +<code>gdbserver</code> on startup. Connecting our local <code>gdb</code> +instance to <code>gdbserver</code> gives us a view into the program’s +execution. Easy!</p> +<p>Run <code>qemu</code>, with <code>gdbserver</code> on port +<code>1234</code>, with our ARM binary, <code>main</code>:</p> <pre class="shell"><code>qemu-arm -singlestep -g 1234 main</code></pre> -<p>Start up <code>gdb</code> on your machine, and connect to <code>qemu</code>’s <code>gdbserver</code>:</p> +<p>Start up <code>gdb</code> on your machine, and connect to +<code>qemu</code>’s <code>gdbserver</code>:</p> <pre><code>(gdb) set architecture armv8-a (gdb) target remote localhost:1234 (gdb) file main Reading symbols from main... # yay!</code></pre> <h3 id="gdb-enhanced">GDB Enhanced</h3> -<p><code>gdb</code> is cool, but it’s not nearly as comfortable as well fleshed out emulators/IDEs like Keil. Watching registers, CPSR and memory chunks update <em>is</em> pretty fun.</p> -<p>I came across <code>gdb</code>’s TUI mode (hit <code>C-x C-a</code> or type <code>tui enable</code> at the prompt). TUI mode is a godsend. It highlights the current line of execution, shows you disassembly outputs, updated registers, active breakpoints and more.</p> +<p><code>gdb</code> is cool, but it’s not nearly as comfortable as well +fleshed out emulators/IDEs like Keil. Watching registers, CPSR and +memory chunks update <em>is</em> pretty fun.</p> +<p>I came across <code>gdb</code>’s TUI mode (hit <code>C-x C-a</code> +or type <code>tui enable</code> at the prompt). TUI mode is a godsend. +It highlights the current line of execution, shows you disassembly +outputs, updated registers, active breakpoints and more.</p> <p><em>But</em>, it is an absolute eyesore.</p> -<p>Say hello to <a href="https://github.com/hugsy/gef">GEF</a>! “GDB Enhanced Features” teaches our old dog some cool new tricks. Here are some additions that made my ARM debugging experience loads better:</p> +<p>Say hello to <a href="https://github.com/hugsy/gef">GEF</a>! “GDB +Enhanced Features” teaches our old dog some cool new tricks. Here are +some additions that made my ARM debugging experience loads better:</p> <ul> <li>Memory watches</li> -<li>Register watches, with up to 7 levels of deref (overkill, I agree)</li> +<li>Register watches, with up to 7 levels of deref (overkill, I +agree)</li> <li>Stack tracing</li> </ul> <p>And it’s pretty! See for yourself:</p> -<p><a href="https://u.peppe.rs/wq.png"><img src="https://u.peppe.rs/wq.png" /></a></p> +<p><a href="https://u.peppe.rs/wq.png"><img +src="https://u.peppe.rs/wq.png" /></a></p> <h3 id="editing">Editing</h3> -<p>Vim, with <code>syntax off</code> because it dosen’t handle GNU ARM syntax too well.</p> +<p>Vim, with <code>syntax off</code> because it dosen’t handle GNU ARM +syntax too well.</p> https://peppe.rs/posts/call_to_ARMs/ Fri, 07 Feb 2020 18:30:00 +0000 https://peppe.rs/posts/call_to_ARMs/ Color Conundrum -<p>This piece aims to highlight (pun intended) some of the reasons behind my <a href="https://u.peppe.rs/bF.png">color free</a> editor setup.</p> -<p>Imagine highlighting an entire book because <em>all</em> of it is important. That is exactly what (most) syntax highlighting does. It is difficult for the human eye to filter out noise in rainbow barf. Use color to draw attention, not diverge it.</p> -<p>At the same time, a book devoid of color is <em>boring!</em> What is the takeaway from this 10 line paragraph? What are the technical terms used?</p> -<p>Prose and code are certainly different, but the fickle minded human eye is the same. The eye constantly looks for a frame of reference, a focal point. It grows tired when it can’t find one.</p> -<p>The following comparison does a better job of explaining (none, ample and over-the-top highlighting, from left to right):</p> -<p><a href="https://u.peppe.rs/lt.png"><img src="https://u.peppe.rs/lt.png" /></a></p> -<p>Without highlighting (far left), it is hard to differentiate between comments and code! The florid color scheme (far right) is no good either, it contains too many attention grabbers. The center sample is a healthy balance of both. Function calls and constants stand out, and repetitive keywords and other noise (<code>let</code>, <code>as</code>) are mildly dimmed out. Comments and non-code text (sign column, status text) are dimmed further.</p> -<p>I’ll stop myself before I rant about color contrast and combinations.</p> +<p>This piece aims to highlight (pun intended) some of the reasons +behind my <a href="https://u.peppe.rs/bF.png">color free</a> editor +setup.</p> +<p>Imagine highlighting an entire book because <em>all</em> of it is +important. That is exactly what (most) syntax highlighting does. It is +difficult for the human eye to filter out noise in rainbow barf. Use +color to draw attention, not diverge it.</p> +<p>At the same time, a book devoid of color is <em>boring!</em> What is +the takeaway from this 10 line paragraph? What are the technical terms +used?</p> +<p>Prose and code are certainly different, but the fickle minded human +eye is the same. The eye constantly looks for a frame of reference, a +focal point. It grows tired when it can’t find one.</p> +<p>The following comparison does a better job of explaining (none, ample +and over-the-top highlighting, from left to right):</p> +<p><a href="https://u.peppe.rs/lt.png"><img +src="https://u.peppe.rs/lt.png" /></a></p> +<p>Without highlighting (far left), it is hard to differentiate between +comments and code! The florid color scheme (far right) is no good +either, it contains too many attention grabbers. The center sample is a +healthy balance of both. Function calls and constants stand out, and +repetitive keywords and other noise (<code>let</code>, <code>as</code>) +are mildly dimmed out. Comments and non-code text (sign column, status +text) are dimmed further.</p> +<p>I’ll stop myself before I rant about color contrast and +combinations.</p> https://peppe.rs/posts/color_conundrum/ Mon, 30 Dec 2019 18:30:00 +0000 https://peppe.rs/posts/color_conundrum/ Static Sites With Bash -<p>After going through a bunch of static site generators (<a href="https://blog.getpelican.com/">pelican</a>, <a href="https://gohugo.io">hugo</a>, <a href="https://github.com/icyphox/vite">vite</a>), I decided to roll my own. If you are more of the ‘show me the code’ kinda guy, <a href="https://github.com/nerdypepper/site">here</a> you go.</p> +<p>After going through a bunch of static site generators (<a +href="https://blog.getpelican.com/">pelican</a>, <a +href="https://gohugo.io">hugo</a>, <a +href="https://github.com/icyphox/vite">vite</a>), I decided to roll my +own. If you are more of the ‘show me the code’ kinda guy, <a +href="https://github.com/nerdypepper/site">here</a> you go.</p> <h3 id="text-formatting">Text formatting</h3> -<p>I chose to write in markdown, and convert to html with <a href="https://kristaps.bsd.lv/lowdown/">lowdown</a>.</p> +<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" 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> +<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" 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> @@ -1955,19 +3049,27 @@ Reading symbols from main... # yay!</code></pre> <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" tabindex="-1"></a><span class="co"># strip file extension</span></span> +<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" 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-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="fu">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> +<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/ Fri, 22 Nov 2019 18:30:00 +0000 https://peppe.rs/posts/static_sites_with_bash/ @@ -1976,18 +3078,39 @@ Reading symbols from main... # yay!</code></pre> My Setup <p>Decided to do one of these because everyone does one of these.</p> <p><img src="https://u.peppe.rs/Hb.png" /></p> -<p>My entire setup is managed with GNU <code>stow</code>, making it easier to replicate on fresh installations. You can find my configuration files on <a href="https://github.com/nerdypepper">GitHub</a>.</p> -<p>I run Void Linux (glibc) on my <a href="https://store.hp.com/us/en/mdp/laptops/envy-13">HP Envy 13" (2018)</a>. To keep things simple, I run a raw X session with <code>2bwm</code> as my window manager, along with <code>dunst</code> (notification daemon) and Sam’s <a href="https://github.com/sdhand/compton"><code>compton</code></a> (compositor) fork.</p> -<p>I am a fan of GNU tools, so I use <code>bash</code> as my shell, and <code>coreutils</code> to manage files, archives, strings, paths etc. I edit files with <code>vim</code>, chat with <code>weechat</code>, listen to music with <code>cmus</code>, monitor processes with <code>htop</code>, manage sessions with <code>tmux</code>, read pdfs in <code>zathura</code>. I rarely ever leave the comfort of my terminal emulator, <code>urxvt</code>.</p> -<p>Most of my academic typesetting is done with TeX, and compiled with <code>xelatex</code>. Other <em>fun</em> documents are made with GIMP :).</p> +<p>My entire setup is managed with GNU <code>stow</code>, making it +easier to replicate on fresh installations. You can find my +configuration files on <a +href="https://github.com/nerdypepper">GitHub</a>.</p> +<p>I run Void Linux (glibc) on my <a +href="https://store.hp.com/us/en/mdp/laptops/envy-13">HP Envy 13” +(2018)</a>. To keep things simple, I run a raw X session with +<code>2bwm</code> as my window manager, along with <code>dunst</code> +(notification daemon) and Sam’s <a +href="https://github.com/sdhand/compton"><code>compton</code></a> +(compositor) fork.</p> +<p>I am a fan of GNU tools, so I use <code>bash</code> as my shell, and +<code>coreutils</code> to manage files, archives, strings, paths etc. I +edit files with <code>vim</code>, chat with <code>weechat</code>, listen +to music with <code>cmus</code>, monitor processes with +<code>htop</code>, manage sessions with <code>tmux</code>, read pdfs in +<code>zathura</code>. I rarely ever leave the comfort of my terminal +emulator, <code>urxvt</code>.</p> +<p>Most of my academic typesetting is done with TeX, and compiled with +<code>xelatex</code>. Other <em>fun</em> documents are made with GIMP +:).</p> https://peppe.rs/posts/my_setup/ Wed, 06 Nov 2019 18:30:00 +0000 https://peppe.rs/posts/my_setup/ WPA Woes -<p>I finally got around to installing Void GNU/Linux on my main computer. Rolling release, non-systemd, need I say more?</p> -<p>As with all GNU/Linux distributions, wireless networks had me in a fix. If you can see this post, it means I’ve managed to get online. It turns out, <code>wpa_supplicant</code> was detecting the wrong interface by default (does it ever select the right one?). Let us fix that:</p> +<p>I finally got around to installing Void GNU/Linux on my main +computer. Rolling release, non-systemd, need I say more?</p> +<p>As with all GNU/Linux distributions, wireless networks had me in a +fix. If you can see this post, it means I’ve managed to get online. It +turns out, <code>wpa_supplicant</code> was detecting the wrong interface +by default (does it ever select the right one?). Let us fix that:</p> <pre><code>$ sudo rm -r /var/service/wpa_supplicant $ sudo killall dhcpcd</code></pre> <p>What is the right interface though?</p> @@ -1995,7 +3118,8 @@ $ sudo killall dhcpcd</code></pre> ... Interface wlp2s0 ...</code></pre> -<p>Aha! Let us run <code>wpa_supplicant</code> on that interface, as a background process:</p> +<p>Aha! Let us run <code>wpa_supplicant</code> on that interface, as a +background process:</p> <pre><code>$ sudo wpa_supplicant -B -i wlp2s0 -c /etc/wpa_supplicant/wpa_supplicant.conf $ sudo dhcpcd -B wlp2s0 $ ping google.com @@ -2016,41 +3140,94 @@ $ sudo sv restart dhcpcd</code></pre> Bye Bye BDFs -<p>Glyph Bitmap Distribution Format is no more, as the creators of <a href="https://pango.org">Pango</a>, one of the most widely used text rendering libraries, <a href="https://blogs.gnome.org/mclasen/2019/05/25/pango-future-directions/">announced</a> their plans for Pango 1.44.</p> -<p>Until recently, Pango used FreeType to draw fonts. They will be moving over to <a href="https://harfbuzz.org">Harfbuzz</a>, an evolution of FreeType.</p> +<p>Glyph Bitmap Distribution Format is no more, as the creators of <a +href="https://pango.org">Pango</a>, one of the most widely used text +rendering libraries, <a +href="https://blogs.gnome.org/mclasen/2019/05/25/pango-future-directions/">announced</a> +their plans for Pango 1.44.</p> +<p>Until recently, Pango used FreeType to draw fonts. They will be +moving over to <a href="https://harfbuzz.org">Harfbuzz</a>, an evolution +of FreeType.</p> <p><em>Why?</em></p> -<p>In short, FreeType was hard to work with. It required complex logic, and provided no advantage over Harfbuzz (other than being able to fetch opentype metrics with ease).</p> -<p>Upgrading to Pango v1.44 will break your GTK applications (if you use a <code>bdf</code>/<code>pcf</code> bitmap font). Harfbuzz <em>does</em> support bitmap-only OpenType fonts, <code>otb</code>s. Convert your existing fonts over to <code>otb</code>s using <a href="https://fontforge.github.io">FontForge</a>. It is to be noted that applications such as <code>xterm</code> and <code>rxvt</code> use <code>xft</code> (X FreeType) to render fonts, and will remain unaffected by the update.</p> -<p>Both <a href="https://github.com/nerdypepper/scientifica">scientifica</a> and <a href="https://github.com/nerdypepper/curie">curie</a> will soon ship with bitmap-only OpenType font formats.</p> +<p>In short, FreeType was hard to work with. It required complex logic, +and provided no advantage over Harfbuzz (other than being able to fetch +opentype metrics with ease).</p> +<p>Upgrading to Pango v1.44 will break your GTK applications (if you use +a <code>bdf</code>/<code>pcf</code> bitmap font). Harfbuzz <em>does</em> +support bitmap-only OpenType fonts, <code>otb</code>s. Convert your +existing fonts over to <code>otb</code>s using <a +href="https://fontforge.github.io">FontForge</a>. It is to be noted that +applications such as <code>xterm</code> and <code>rxvt</code> use +<code>xft</code> (X FreeType) to render fonts, and will remain +unaffected by the update.</p> +<p>Both <a +href="https://github.com/nerdypepper/scientifica">scientifica</a> and <a +href="https://github.com/nerdypepper/curie">curie</a> will soon ship +with bitmap-only OpenType font formats.</p> https://peppe.rs/posts/bye_bye_BDFs/ Wed, 07 Aug 2019 17:26:00 +0000 https://peppe.rs/posts/bye_bye_BDFs/ Onivim Sucks -<p><a href="https://v2.onivim.io">Onivim</a> is a ‘modern modal editor’, combining fancy interface and language features with vim-style modal editing. What’s wrong you ask?</p> -<p>Apart from <a href="https://github.com/onivim/oni2/issues/550">buggy syntax highlighting</a>, <a href="https://github.com/onivim/oni2/issues/519">broken scrolling</a> and <a href="https://github.com/onivim/oni2/issues?q=is%3Aissue+label%3A%22daily+editor+blocker%22+is%3Aopen">others</a>, Onivim is <strong>proprietary</strong> software. It is licensed under a commercial <a href="https://github.com/onivim/oni1/blob/master/Outrun-Labs-EULA-v1.1.md">end user agreement license</a>, which prohibits redistribution in both object code and source code formats.</p> -<p>Onivim’s core editor logic (bits that belong to vim), have been separated from the interface, into <a href="https://github.com/onivim/libvim">libvim</a>. libvim is licensed under MIT, which means, this ‘extension’ of vim is perfectly in adherence to <a href="http://vimdoc.sourceforge.net/htmldoc/uganda.html#license">vim’s license text</a>! Outrun Labs are exploiting this loophole (distributing vim as a library) to commercialize Onivim.</p> -<p>Onivim’s source code is available on <a href="https://github.com/onivim/oni2">GitHub</a>. They do mention that the source code trickles down to the <a href="https://github.com/onivim/oni2-mit">oni2-mit</a> repository, which (not yet) contains MIT-licensed code, <strong>18 months</strong> after each commit to the original repository.</p> -<p>Want to contribute to Onivim? Don’t. They make a profit out of your contributions. Currently, Onivim is priced at $19.99, ‘pre-alpha’ pricing which is 80% off the final price! If you are on the lookout for an editor, I would suggest using <a href="https://vim.org">Vim</a>, charity ware that actually works, and costs $100 lesser.</p> +<p><a href="https://v2.onivim.io">Onivim</a> is a ‘modern modal editor’, +combining fancy interface and language features with vim-style modal +editing. What’s wrong you ask?</p> +<p>Apart from <a href="https://github.com/onivim/oni2/issues/550">buggy +syntax highlighting</a>, <a +href="https://github.com/onivim/oni2/issues/519">broken scrolling</a> +and <a +href="https://github.com/onivim/oni2/issues?q=is%3Aissue+label%3A%22daily+editor+blocker%22+is%3Aopen">others</a>, +Onivim is <strong>proprietary</strong> software. It is licensed under a +commercial <a +href="https://github.com/onivim/oni1/blob/master/Outrun-Labs-EULA-v1.1.md">end +user agreement license</a>, which prohibits redistribution in both +object code and source code formats.</p> +<p>Onivim’s core editor logic (bits that belong to vim), have been +separated from the interface, into <a +href="https://github.com/onivim/libvim">libvim</a>. libvim is licensed +under MIT, which means, this ‘extension’ of vim is perfectly in +adherence to <a +href="http://vimdoc.sourceforge.net/htmldoc/uganda.html#license">vim’s +license text</a>! Outrun Labs are exploiting this loophole (distributing +vim as a library) to commercialize Onivim.</p> +<p>Onivim’s source code is available on <a +href="https://github.com/onivim/oni2">GitHub</a>. They do mention that +the source code trickles down to the <a +href="https://github.com/onivim/oni2-mit">oni2-mit</a> repository, which +(not yet) contains MIT-licensed code, <strong>18 months</strong> after +each commit to the original repository.</p> +<p>Want to contribute to Onivim? Don’t. They make a profit out of your +contributions. Currently, Onivim is priced at $19.99, ‘pre-alpha’ +pricing which is 80% off the final price! If you are on the lookout for +an editor, I would suggest using <a href="https://vim.org">Vim</a>, +charity ware that actually works, and costs $100 lesser.</p> https://peppe.rs/posts/onivim_sucks/ Fri, 02 Aug 2019 16:32:00 +0000 https://peppe.rs/posts/onivim_sucks/ Bash Harder With Vim -<p>Bash is tricky, don’t let your editor get in your way. Here’s a couple of neat additions you could make to your <code>vimrc</code> for a better shell programming experience.</p> +<p>Bash is tricky, don’t let your editor get in your way. Here’s a +couple of neat additions you could make to your <code>vimrc</code> for a +better shell programming experience.</p> <h3 id="man-pages-inside-vim">Man pages inside vim</h3> <p>Source this script to get started:</p> <pre><code>runtime ftplugin/man.vim</code></pre> -<p>Now, you can open manpages inside vim with <code>:Man</code>! It adds nicer syntax highlighting and the ability to jump around with <code>Ctrl-]</code> and <code>Ctrl-T</code>.</p> -<p>By default, the manpage is opened in a horizontal split, I prefer using a new tab:</p> +<p>Now, you can open manpages inside vim with <code>:Man</code>! It adds +nicer syntax highlighting and the ability to jump around with +<code>Ctrl-]</code> and <code>Ctrl-T</code>.</p> +<p>By default, the manpage is opened in a horizontal split, I prefer +using a new tab:</p> <pre><code>let g:ft_man_open_mode = &#39;tab&#39;</code></pre> -<h3 id="scratchpad-to-test-your-commands">Scratchpad to test your commands</h3> -<p>I often test my <code>sed</code> substitutions, here is a sample from the script used to generate this site:</p> +<h3 id="scratchpad-to-test-your-commands">Scratchpad to test your +commands</h3> +<p>I often test my <code>sed</code> substitutions, here is a sample from +the script used to generate this site:</p> <pre><code># a substitution to convert snake_case to Title Case With Spaces echo &quot;$1&quot; | sed -E -e &quot;s/\..+$//g&quot; -e &quot;s/_(.)/ \u\1/g&quot; -e &quot;s/^(.)/\u\1/g&quot;</code></pre> -<p>Instead of dropping into a new shell, just test it out directly from vim!</p> +<p>Instead of dropping into a new shell, just test it out directly from +vim!</p> <ul> <li>Yank the line into a register:</li> </ul> @@ -2079,14 +3256,24 @@ Press ENTER or type command to continue</code></pre> Hold Position! -<p>Often times, when I run a vim command that makes “big” changes to a file (a macro or a <code>:vimgrep</code> command) I lose my original position and feel disoriented.</p> +<p>Often times, when I run a vim command that makes “big” changes to a +file (a macro or a <code>:vimgrep</code> command) I lose my original +position and feel disoriented.</p> <p><em>Save position with <code>winsaveview()</code>!</em></p> -<p>The <code>winsaveview()</code> command returns a <code>Dictionary</code> that contains information about the view of the current window. This includes the cursor line number, cursor coloumn, the top most line in the window and a couple of other values, none of which concern us.</p> -<p>Before running our command (one that jumps around the buffer, a lot), we save our view, and restore it once its done, with <code>winrestview</code>.</p> +<p>The <code>winsaveview()</code> command returns a +<code>Dictionary</code> that contains information about the view of the +current window. This includes the cursor line number, cursor coloumn, +the top most line in the window and a couple of other values, none of +which concern us.</p> +<p>Before running our command (one that jumps around the buffer, a lot), +we save our view, and restore it once its done, with +<code>winrestview</code>.</p> <pre><code>let view = winsaveview() s/\s\+$//gc &quot; find and (confirm) replace trailing blanks winrestview(view) &quot; restore our original view!</code></pre> -<p>It might seem a little overkill in the above example, just use `` (double backticks) instead, but it comes in handy when you run your file through heavier filtering.</p> +<p>It might seem a little overkill in the above example, just use `` +(double backticks) instead, but it comes in handy when you run your file +through heavier filtering.</p> https://peppe.rs/posts/hold_position!/ Tue, 30 Jul 2019 14:45:00 +0000 https://peppe.rs/posts/hold_position!/ @@ -2095,7 +3282,8 @@ winrestview(view) &quot; restore our original view!</code></ Get Better At Yanking And Putting In Vim <p>a couple of nifty tricks to help you copy-paste better:</p> <ol type="1"> -<li><p>reselecting previously selected text (i use this to fix botched selections):</p> +<li><p>reselecting previously selected text (i use this to fix botched +selections):</p> <pre><code>gv &quot; :h gv for more &quot; you can use `o` in visual mode to go to the `Other` end of the selection &quot; use a motion to fix the selection</code></pre></li> diff --git a/docs/posts/SDL2_devlog/index.html b/docs/posts/SDL2_devlog/index.html index 0e76515..e31f399 100644 --- a/docs/posts/SDL2_devlog/index.html +++ b/docs/posts/SDL2_devlog/index.html @@ -42,25 +42,60 @@ SDL2 Devlog
-

I have been working on an editor for the One Bit Image file format in Rust and SDL2. This entry in my blog follows my progress on the editor. The days are listed in reverse chronological order, begin from the bottom, if this is your first time on this page.

+

I have been working on an editor for the One Bit Image file +format in Rust and SDL2. This entry in my blog follows my progress on +the editor. The days are listed in reverse chronological order, begin +from the bottom, if this is your first time on this page.

Day 20

-

More lisp stuff! I added a new brush, for rectangular selections. While selection doesn’t do much on its own, the selected area can be passed onto a lisp procedure, for example, a procedure to draw horizontal black and white lines:

+

More lisp stuff! I added a new brush, for rectangular +selections. While selection doesn’t do much on its own, the selected +area can be passed onto a lisp procedure, for example, a +procedure to draw horizontal black and white lines:

- + +

Day 19

-

Attempted some isometric art within the editor. The angles displayed alongside the line brush are handly, however, having only a rectangular grid did not help. I implemented an isometric grid today. Isometric grids in pixel art differ in that the tangent of the isometric angle is exactly 0.5! For every pixel down, you go exactly two pixels sideways. The math works out really well in the drawing procedures too, dealing with floating points is a pain.

+

Attempted some isometric +art within the editor. The angles displayed alongside the line brush +are handly, however, having only a rectangular grid did not help. I +implemented an isometric grid today. Isometric grids in pixel art differ +in that the tangent of the isometric angle is exactly 0.5! For every +pixel down, you go exactly two pixels sideways. The math works out +really well in the drawing procedures too, dealing with floating points +is a pain.

-Day 19 +Day 19 +

Day 18

-

I added basic support for guides, they can be added and activated from the lisp REPL. Another long standing improvement I wanted to make was reworking the pixmap drawing procedure. The old procedure draws a square for each pixel in the pixmap, coloured according to its value in the pixmap. Naturally, this means, for an NxN pixmap, there are calls to SDL! I reworked this procedure to compress each line of the pixmap using RLE (run length encoding), and call out to SDL for each run in the line. This drastically improved drawing speeds on larger grids. The following is a comparison between the two procedures, the leftmost picture is the rendered image, the middle picture is the optimized drawing procedure (draws each run instead of pixel), and the right most picture is the primitive drawing procedure (draws each pixel):

+

I added basic support for guides, they can be added and activated +from the lisp REPL. Another long standing improvement I +wanted to make was reworking the pixmap drawing procedure. The old +procedure draws a square for each pixel in the pixmap, coloured +according to its value in the pixmap. Naturally, this means, for an +NxN pixmap, there are calls to SDL! +I reworked this procedure to compress each line of the pixmap using RLE +(run length encoding), and call out to SDL for each run in the line. +This drastically improved drawing speeds on larger grids. The following +is a comparison between the two procedures, the leftmost picture is the +rendered image, the middle picture is the optimized drawing procedure +(draws each run instead of pixel), and the right most picture is the +primitive drawing procedure (draws each pixel):

-Day 18 +Day 18 +

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
+

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)
@@ -77,14 +112,20 @@
 );

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
+

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)

Some aliases to switch between brushes:

-
;;; rc.lisp
+
;;; rc.lisp
 (define (brush kind)
   (cond
     ((eq? kind 'f) (brush-fill))
@@ -92,90 +133,195 @@
     ((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:

+

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)
+

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))

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:

+

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:

- + +

Day 13

-

I added a few more forms to the lisp evaluator. It handles recursion, definitions, variable mutation and more. The prelude contains 20 subroutines so far, including comparision and logic operators. The REPL interface on the SDL side requires some UX tweaks; environment based completion, readline motions sound doable.

+

I added a few more forms to the lisp evaluator. It +handles recursion, definitions, variable mutation and more. The prelude +contains 20 subroutines so far, including comparision and logic +operators. The REPL interface on the SDL side requires some UX tweaks; +environment based completion, readline motions sound doable.

- + +

Day 12

-

I lifted most of murarth/ketos into the editor. ketos’s implementation of lisp is too vast for my use case. For example, the editor does not need data types to handle raw strings or byte strings. I have got a basic evaluator running inside the SDL2 context (notice the lisp REPL at the bottom of the window). Over the following days, I intend to create a set of prelude functions to manipulate the pixmap. Users can implement their own brushes, dithering patterns, keybinds and more (hopefully).

+

I lifted most of murarth/ketos into the +editor. ketos’s implementation of lisp is too +vast for my use case. For example, the editor does not need data types +to handle raw strings or byte strings. I have got a basic evaluator +running inside the SDL2 context (notice the lisp REPL at +the bottom of the window). Over the following days, I intend to create a +set of prelude functions to manipulate the pixmap. Users can implement +their own brushes, dithering patterns, keybinds and more +(hopefully).

- + +

Day 11

-

I intend to supplement the editor with scripting language and an inbuilt REPL for the same. I began by implementing a text box widget from scratch, with history and readline like editing:

+

I intend to supplement the editor with scripting language and an +inbuilt REPL for the same. I began by implementing a text box widget +from scratch, with history and readline like editing:

- + +

Day 10

-

I started reading up on dithering methods and half-toning, I wanted to create a dithering brush that would automatically produce popular dithering patterns. The method that caught my eye (and also the one used most often in pixel art), was Bayer’s ordered dithering. When applied to a black and white image, each pixel, based on its intensity, is mapped to a 4x4 grid of pixels. A completely empty (completely black) 4x4 grid represents zero intensity, and a filled 4x4 grid represents full intensity. Bayer’s ordered dithering can produce 15 steps of intensity between zero and full (by switching on exactly 1 pixel more at each level), thus, being able to draw 17 “shades” from white to black. Creating a dithering brush from here was fairly trivial. Our pixmap is supposed to represent the final dithered image, it must be divided into 4x4 grids. Each grid is colored based on the intensity of the brush passing over it:

+

I started reading up on dithering methods and half-toning, I wanted +to create a dithering brush that would automatically produce popular +dithering patterns. The method that caught my eye (and also the one used +most often in pixel art), was Bayer’s ordered dithering. When applied to +a black and white image, each pixel, based on its intensity, is mapped +to a 4x4 grid of pixels. A completely empty (completely black) 4x4 grid +represents zero intensity, and a filled 4x4 grid represents full +intensity. Bayer’s ordered dithering can produce 15 steps of intensity +between zero and full (by switching on exactly 1 pixel more at each +level), thus, being able to draw 17 “shades” from white to black. +Creating a dithering brush from here was fairly trivial. Our pixmap is +supposed to represent the final dithered image, it must be divided into +4x4 grids. Each grid is colored based on the intensity of the brush +passing over it:

-Day 10 +Day 10 +

Day 9

-

I started working towards an interface. I like the idea of a largely read-only HUD, i. e., an interface that simply describes the state of the application. Changes to this state are initiated via keybinds or text commands. I am proud of the symmetry indicator; - for horizontal symmetry, | for vertical symmetry, + for radial symmetry.

+

I started working towards an interface. I like the idea of a largely +read-only HUD, i. e., an interface that simply describes the state of +the application. Changes to this state are initiated via keybinds or +text commands. I am proud of the symmetry indicator; - for +horizontal symmetry, | for vertical symmetry, ++ for radial symmetry.

-Day 9 +Day 9 +

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);
+

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) {
+for point on line.extend(sym_line) {
     // draw to window
 }
- + +

Day 7

-

Bresenham saves the day again! This time, I implemented his line drawing algorithm, to, well, draw lines. Each point on the line is then “buffed” based on the active brush size. Today’s changes fit in very well with the undo system and the brush size feature. Creating the right abstractions, one at a time :)

+

Bresenham saves the day again! This time, I implemented his line +drawing algorithm, to, well, draw lines. Each point on the line is then +“buffed” based on the active brush size. Today’s changes fit in very +well with the undo system and the brush size feature. Creating the right +abstractions, one at a time :)

- + +

Day 6

-

I extended Bresenham’s algorithm to draw not just circle outlines, but also generate their fills. Unlike Bresenham’s algorithm, this variant generates points for two quadrants at once, these points are mirrored over the dividing axis to generate the other two quadrants.

+

I extended Bresenham’s algorithm to draw not just circle outlines, +but also generate their fills. Unlike Bresenham’s algorithm, this +variant generates points for two quadrants at once, these points are +mirrored over the dividing axis to generate the other two quadrants.

-Day 6 +Day 6 +

Day 5

-

I discovered and implemented Bresenham’s algorithm for efficient circle drawing. The algorithm allowed for sized circular brushes, something I really liked from GIMP. Very convenient that the Wikipedia page for Bresenham’s algorithm also includes a section about optimizing for integer based arithmetic. I managed to abstract out another giant component of the application, the pixmap. Any image is just a grid of pixels (a pixmap), where the pixel’s value is decided by the application (1-bit in my case). I could potentially extend the application to a 24-bit image editor!

+

I discovered and implemented Bresenham’s algorithm for efficient +circle drawing. The algorithm allowed for sized circular brushes, +something I really liked from GIMP. Very convenient that the Wikipedia +page for Bresenham’s algorithm also includes a section about optimizing +for integer based arithmetic. I managed to abstract out another giant +component of the application, the pixmap. Any image is just a grid of +pixels (a pixmap), where the pixel’s value is decided by the application +(1-bit in my case). I could potentially extend the application to a +24-bit image editor!

- + +

Day 4

-

I created a generic “undo stack” data structure that allows for infinite “undos” and “redos”. Every modification operation to the grid is persisted to the application state. A couple of keybinds allow the user to revert and re-apply these operations! I expect abstracting this component will come in handy down the line.

+

I created a generic “undo stack” data structure that allows for +infinite “undos” and “redos”. Every modification operation to the grid +is persisted to the application state. A couple of keybinds allow the +user to revert and re-apply these operations! I expect abstracting this +component will come in handy down the line.

- + +

Day 3

-

I implemented the bare minimum required to call the program an “editor”. The application displays a grid, tracks mouse events, paints white to the canvas on left click, and black to the canvas on right click. I created a make-shift MVC architecture à la Elm in Rust.

+

I implemented the bare minimum required to call the program an +“editor”. The application displays a grid, tracks mouse events, paints +white to the canvas on left click, and black to the canvas on right +click. I created a make-shift MVC architecture à la Elm in Rust.

- + +

Day 2

-

I started figuring out event handling today. Implemented a couple of keybinds to zoom in/out of the drawing area. Conversions of SDL2 coordinates (measured in signed 32 bit integers) to my internal “drawing area” coordinates (measured in unsigned 32 bit integers) is very annoying. Hopefully the unchecked conversions won’t haunt me later.

+

I started figuring out event handling today. Implemented a couple of +keybinds to zoom in/out of the drawing area. Conversions of SDL2 +coordinates (measured in signed 32 bit integers) to my internal “drawing +area” coordinates (measured in unsigned 32 bit integers) is very +annoying. Hopefully the unchecked conversions won’t haunt me later.

- + +

Day 1

-

Getting started with Rust and SDL2 is very straightforward. The rust-sdl2 library contains some detailed examples that allowed me to get all the way to drawing a grid from a Vec<bool>:

+

Getting started with Rust and SDL2 is very straightforward. The +rust-sdl2 library contains some detailed examples that +allowed me to get all the way to drawing a grid from a +Vec<bool>:

-Day 1 +Day 1 +
diff --git a/docs/posts/WPA_woes/index.html b/docs/posts/WPA_woes/index.html index 55b2630..0a2e44c 100644 --- a/docs/posts/WPA_woes/index.html +++ b/docs/posts/WPA_woes/index.html @@ -28,7 +28,7 @@ 12/10 — 2019
- 18.37 + 18.38 cm   @@ -42,8 +42,12 @@ WPA Woes
-

I finally got around to installing Void GNU/Linux on my main computer. Rolling release, non-systemd, need I say more?

-

As with all GNU/Linux distributions, wireless networks had me in a fix. If you can see this post, it means I’ve managed to get online. It turns out, wpa_supplicant was detecting the wrong interface by default (does it ever select the right one?). Let us fix that:

+

I finally got around to installing Void GNU/Linux on my main +computer. Rolling release, non-systemd, need I say more?

+

As with all GNU/Linux distributions, wireless networks had me in a +fix. If you can see this post, it means I’ve managed to get online. It +turns out, wpa_supplicant was detecting the wrong interface +by default (does it ever select the right one?). Let us fix that:

$ sudo rm -r /var/service/wpa_supplicant
 $ sudo killall dhcpcd

What is the right interface though?

@@ -51,7 +55,8 @@ $ sudo killall dhcpcd
... Interface wlp2s0 ...
-

Aha! Let us run wpa_supplicant on that interface, as a background process:

+

Aha! Let us run wpa_supplicant on that interface, as a +background process:

$ sudo wpa_supplicant -B -i wlp2s0 -c /etc/wpa_supplicant/wpa_supplicant.conf
 $ sudo dhcpcd -B wlp2s0
 $ ping google.com
diff --git a/docs/posts/a_reference_counted_afterlife/index.html b/docs/posts/a_reference_counted_afterlife/index.html
index 67016a6..a796393 100644
--- a/docs/posts/a_reference_counted_afterlife/index.html
+++ b/docs/posts/a_reference_counted_afterlife/index.html
@@ -28,7 +28,7 @@
             02/08 — 2022
             
- 19.57 + 19.58 cm   @@ -42,9 +42,11 @@ A Reference Counted Afterlife
-

I took interest in the Egyptian rendition of the afterlife recently.

+

I took interest in the Egyptian rendition of the afterlife +recently.

Parts of the Soul

-

Ancient Egyptians believed that the soul comprised of several components:

+

Ancient Egyptians believed that the soul comprised of several +components:

  • ren
  • ka
  • @@ -52,18 +54,34 @@
  • ba
  • sheut
-

Egyptians emphasized on preserving the different parts of the soul. Mummification for example, served to preserve the physical part of the soul. The other components have their respective preservation strategies.

-

Of all of these bits, I find ren, which simply means name, to be the most interesting. Ba, the human-headed chicken that represents personality, is a close favourite.

-

Ren is the name given to a person at birth. Egyptians believed that this portion of the soul would continue to live on for as long as it was spoken. If you were someone worthy of continued existence, your name would be inscribed all over the place. If you were the type to snatch away bread from children, your name would be condemned from memory, forgotten.

+

Egyptians emphasized on preserving the different parts of the soul. +Mummification for example, served to preserve the physical part of the +soul. The other components have their respective preservation +strategies.

+

Of all of these bits, I find ren, which simply means +name, to be the most interesting. Ba, the human-headed +chicken that represents personality, is a close favourite.

+

Ren is the name given to a person at birth. Egyptians +believed that this portion of the soul would continue to live on for as +long as it was spoken. If you were someone worthy of continued +existence, your name would be inscribed all over the place. If you were +the type to snatch away bread from children, your name would be +condemned from memory, forgotten.

Garbage-collection

-

The concept of ren seems to be perfectly analogous to reference counted garbage-collection.

+

The concept of ren seems to be perfectly analogous to +reference counted garbage-collection.

    -
  • A name (ren) is assigned to an object (person) on initialization (at birth)
  • +
  • A name (ren) is assigned to an object (person) on +initialization (at birth)
  • Names are used to refer to objects
  • -
  • Objects go out of existence when there are no more references to them
  • +
  • Objects go out of existence when there are no more references to +them
-

The concept of ren seems to model human-memory. The similarity with garbage-collection is now easily explained, because garbage-collection models a program’s memory.

-

Perhaps some cheeky Egyptian has attained immortality by creating a ren-cycle.

+

The concept of ren seems to model human-memory. The +similarity with garbage-collection is now easily explained, because +garbage-collection models a program’s memory.

+

Perhaps some cheeky Egyptian has attained immortality by creating a +ren-cycle.

diff --git a/docs/posts/auto-currying_rust_functions/index.html b/docs/posts/auto-currying_rust_functions/index.html index 0d6fc77..7b05aeb 100644 --- a/docs/posts/auto-currying_rust_functions/index.html +++ b/docs/posts/auto-currying_rust_functions/index.html @@ -28,7 +28,7 @@ 09/05 — 2020
- 356.43 + 356.44 cm   @@ -42,13 +42,22 @@ Auto-currying Rust Functions
-

This post contains a gentle introduction to procedural macros in Rust and a guide to writing a procedural macro to curry Rust functions. The source code for the entire library can be found here. It is also available on crates.io.

-

The following links might prove to be useful before getting started:

+

This post contains a gentle introduction to procedural macros in Rust +and a guide to writing a procedural macro to curry Rust functions. The +source code for the entire library can be found here. It is also +available on crates.io.

+

The following links might prove to be useful before getting +started:

-

Or you can pretend you read them, because I have included a primer here :)

+

Or you can pretend you read them, because I have included a primer +here :)

Contents

  1. Currying
    @@ -73,7 +82,12 @@
  2. Conclusion

Currying

-

Currying is the process of transformation of a function call like f(a, b, c) to f(a)(b)(c). A curried function returns a concrete value only when it receives all its arguments! If it does recieve an insufficient amount of arguments, say 1 of 3, it returns a curried function, that returns after receiving 2 arguments.

+

Currying is the process of transformation of a function call like +f(a, b, c) to f(a)(b)(c). A curried function +returns a concrete value only when it receives all its arguments! If it +does recieve an insufficient amount of arguments, say 1 of 3, it returns +a curried function, that returns after receiving 2 +arguments.

curry(f(a, b, c)) = h(a)(b)(c)
 
 h(x) = g   <- curried function that takes upto 2 args (g)
@@ -82,49 +96,86 @@ k(z) = v   <- a value (v)
 
 Keen readers will conclude the following,
 h(x)(y)(z) = g(y)(z) = k(z) = v
-

Mathematically, if f is a function that takes two arguments x and y, such that x ϵ X, and y ϵ Y , we write it as:

+

Mathematically, if f is a function that takes two +arguments x and y, such that +x ϵ X, and y ϵ Y , we write it as:

f: (X × Y) -> Z
-

where × denotes the Cartesian product of set X and Y, and curried f (denoted by h here) is written as:

+

where × denotes the Cartesian product of set +X and Y, and curried f (denoted +by h here) is written as:

h: X -> (Y -> Z)

Procedural Macros

-

These are functions that take code as input and spit out modified code as output. Powerful stuff. Rust has three kinds of proc-macros:

+

These are functions that take code as input and spit out modified +code as output. Powerful stuff. Rust has three kinds of proc-macros:

  • Function like macros
  • -
  • Derive macros: #[derive(...)], used to automatically implement traits for structs/enums
    +
  • Derive macros: #[derive(...)], used to automatically +implement traits for structs/enums
  • -
  • and Attribute macros: #[test], usually slapped onto functions
  • +
  • and Attribute macros: #[test], usually slapped onto +functions
-

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).

+

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;
+

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;
 }
-

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;
+

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;
     }
   }
 }

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!

-

If you have been following along, you should be able to tell that the return type of add_curried1 is:

+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!

+

If you have been following along, you should be able to tell that the +return type of add_curried1 is:

impl Fn(u32) -> (impl Fn(u32) -> u32)
-

We can drop the parentheses because -> is right associative:

+

We can drop the parentheses because -> is right +associative:

impl Fn(u32) -> impl Fn(u32) -> u32
 

Accessing environment
-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.

+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;
+

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;
 }
-

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

+

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
   --> src/main.rs:17:37
@@ -132,21 +183,33 @@ and inherent method return types
    | fn add(x: u32) -> impl Fn(u32) -> impl Fn(u32) -> u32
    |                                   ^^^^^^^^^^^^^^^^^^^
 
-

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!
+

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;
+  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!

+

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.

-

Initialize your workspace with cargo new --lib currying. Proc-macro crates are libraries with exactly one export, the macro itself. Add a tests directory to your crate root. Your directory should look something like this:

+

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

+

Initialize your workspace with cargo new --lib currying. +Proc-macro crates are libraries with exactly one export, the macro +itself. Add a tests directory to your crate root. Your +directory should look something like this:

.
 ├── Cargo.toml
 ├── src
@@ -156,9 +219,11 @@ and inherent method return types
 

Dependencies

We will be using a total of 3 external crates:

Here’s a sample Cargo.toml:

# Cargo.toml
@@ -173,10 +238,12 @@ features = ["full"]
 
 [lib]
 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!

+

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
+
// src/lib.rs
 
 use proc_macro::TokenStream;  // 1
 use quote::quote;
@@ -190,17 +257,49 @@ proc-macro = true  # this is important!
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.

-

ItemFn from the syn crate holds the parsed TokenStream of a Rust function. parse_macro_input! is a helper macro provided by syn.

+

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.

+

ItemFn from the syn crate holds the parsed +TokenStream of a Rust function. +parse_macro_input! is a helper macro provided by +syn.

2. The lone export

-

Annotate the only pub of our crate with #[proc_macro_attribute]. This tells rustc that curry is a procedural macro, and allows us to use it as #[crate_name::curry] in other crates. Note the signature of the curry function. _attr is the TokenStream representing the attribute itself, item refers to the thing we slapped our macro into, in this case a function (like add). The return value is a modified TokenStream, this will contain our curried version of add.

+

Annotate the only pub of our crate with +#[proc_macro_attribute]. This tells rustc that +curry is a procedural macro, and allows us to use it as +#[crate_name::curry] in other crates. Note the signature of +the curry function. _attr is the +TokenStream representing the attribute itself, +item refers to the thing we slapped our macro into, in this +case a function (like add). The return value is a modified +TokenStream, this will contain our curried version of +add.

3. The helper macro

-

A TokenStream is a little hard to work with, which is why we have the syn crate, which provides types to represent Rust tokens. An RArrow struct to represent the return arrow on a function and so on. One of those types is ItemFn, that represents an entire Rust function. The parse_macro_input! automatically puts the input to our macro into an ItemFn. What a gentleman!

+

A TokenStream is a little hard to work with, which is +why we have the syn crate, which provides types to +represent Rust tokens. An RArrow struct to represent the +return arrow on a function and so on. One of those types is +ItemFn, that represents an entire Rust function. The +parse_macro_input! automatically puts the input to our +macro into an ItemFn. What a gentleman!

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
+

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
@@ -210,7 +309,9 @@ proc-macro = true  # this is important!
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:

+

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)
                       /
                  fn add(x: u32, y: u32) -> u32
@@ -220,42 +321,77 @@ syn::token::Fn --'            /               \       (output)
              Punctuated<FnArg, Comma> (inputs)

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;
+

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

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

And in general:

-
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
+
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<_>>();
+  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
+

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 {
+  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
+

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
+    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
+

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;
@@ -272,10 +408,11 @@ syn::token::Fn --'            /               \       (output)
 +  let curried_body = generate_body(&arg_idents[1..], fn_body.clone());
 +  println!("{}", curried_body);
 
-   return TokenStream::new();
+   return TokenStream::new();
  }

Add a little test to tests/:

-
// tests/smoke.rs
+
// tests/smoke.rs
 
 #[currying::curry]
 fn add(x: u32, y: u32, z: u32) -> u32 {
@@ -286,17 +423,23 @@ syn::token::Fn --'            /               \       (output)
 fn works() {
   assert!(true);
 }
-

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

+

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;
+

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;

In general:

-
type T0 = <return type>;
+
type T0 = <return type>;
 type T1 = impl Fn(<type of arg N>) -> T0;
 type T2 = impl Fn(<type of arg N - 1>) -> T1;
 .
@@ -308,42 +451,59 @@ syn::token::Fn --'            /               \       (output)
 
  • 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
    +

    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 {
    +  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<_>>();
    +  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:

    +

    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. -
    3. A ReturnType encloses the arrow of the return as well, we need to get rid of that. Recall:

      -
      type T0 = u32
      +
    4. 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.

    5. +
    6. 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
    -

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

    -
    // src/lib.rs
    +

    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 {
    +  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
    +

    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};
     
    @@ -357,7 +517,7 @@ syn::token::Fn --'            /               \       (output)
       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()) {
    +  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));
     
    @@ -366,45 +526,70 @@ syn::token::Fn --'            /               \       (output)
         });
       }
     
    -  return type_aliases;
    +  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.

    +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
    +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
    -

    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]
    +

    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 { ... }

    Here is the same but with macros expanded:

    -
    type T0 = u32;
    +
    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;
    +

    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 { ... }
    -

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

    +

    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!).

    +

    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
    +

    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;
    @@ -428,20 +613,39 @@ I’ve got some explanation to do on this line. Clearly, we are trying to write
     
     +  let return_type = format_ident!("_{}_{}", &fn_name, format!("T{}", type_aliases.len() - 1));
     
    -+  return quote! {
    ++  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.

    +

    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.

    Debugging and Testing

    Install cargo-expand via:

    cargo install cargo-expand
    -

    cargo-expand is a neat little tool that expands your macro in places where it is used, and lets you view the generated code! For example:

    +

    cargo-expand is a neat little tool that expands your +macro in places where it is used, and lets you view the generated code! +For example:

    # create a bin package hello
     $ cargo new hello
     
    @@ -463,10 +667,18 @@ 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.

    +

    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
    +
    // tests/smoke.rs
     
     #![feature(type_alias_impl_trait)]
     
    @@ -479,55 +691,81 @@ fn main() {
     fn works() {
       assert_eq!(15, add(4)(5)(6));
     }
    -

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

    +

    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;
    +

    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| {
    +  return (move |y| {
         move |z| {
    -      return x + y + 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]
    +

    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)
    +  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);
    +

    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));
    -

    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.

    +

    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

    -

    Currying may not seem to be all that useful. Curried functions are unwieldy in Rust because the standard library is not built around currying. If you enjoy the possibilities posed by currying, consider taking a look at Haskell or Scheme.

    -

    My original intention with peppe.rs was to post condensed articles, a micro blog, but this one turned out extra long.

    +

    Currying may not seem to be all that useful. Curried functions are +unwieldy in Rust because the standard library is not built around +currying. If you enjoy the possibilities posed by currying, consider +taking a look at Haskell or Scheme.

    +

    My original intention with peppe.rs +was to post condensed articles, a micro blog, but this one turned out +extra long.

    Perhaps I should call it a ‘macro’ blog :)

    -
    +

      -
    1. https://doc.rust-lang.org/book/ch13-01-closures.html↩︎

    2. -
    3. caniuse.rs contains an indexed list of features and their status.↩︎

    4. +
    5. https://doc.rust-lang.org/book/ch13-01-closures.html↩︎

    6. +
    7. caniuse.rs contains an +indexed list of features and their status.↩︎

    diff --git a/docs/posts/bash_harder_with_vim/index.html b/docs/posts/bash_harder_with_vim/index.html index 099733a..96210d5 100644 --- a/docs/posts/bash_harder_with_vim/index.html +++ b/docs/posts/bash_harder_with_vim/index.html @@ -28,7 +28,7 @@ 31/07 — 2019
    - 24.37 + 24.38 cm   @@ -42,18 +42,26 @@ Bash Harder With Vim
    -

    Bash is tricky, don’t let your editor get in your way. Here’s a couple of neat additions you could make to your vimrc for a better shell programming experience.

    +

    Bash is tricky, don’t let your editor get in your way. Here’s a +couple of neat additions you could make to your vimrc for a +better shell programming experience.

    Man pages inside vim

    Source this script to get started:

    runtime ftplugin/man.vim
    -

    Now, you can open manpages inside vim with :Man! It adds nicer syntax highlighting and the ability to jump around with Ctrl-] and Ctrl-T.

    -

    By default, the manpage is opened in a horizontal split, I prefer using a new tab:

    +

    Now, you can open manpages inside vim with :Man! It adds +nicer syntax highlighting and the ability to jump around with +Ctrl-] and Ctrl-T.

    +

    By default, the manpage is opened in a horizontal split, I prefer +using a new tab:

    let g:ft_man_open_mode = 'tab'
    -

    Scratchpad to test your commands

    -

    I often test my sed substitutions, here is a sample from the script used to generate this site:

    +

    Scratchpad to test your +commands

    +

    I often test my sed substitutions, here is a sample from +the script used to generate this site:

    # a substitution to convert snake_case to Title Case With Spaces
     echo "$1" | sed -E -e "s/\..+$//g"  -e "s/_(.)/ \u\1/g" -e "s/^(.)/\u\1/g"
    -

    Instead of dropping into a new shell, just test it out directly from vim!

    +

    Instead of dropping into a new shell, just test it out directly from +vim!

    • Yank the line into a register:
    diff --git a/docs/posts/bye_bye_BDFs/index.html b/docs/posts/bye_bye_BDFs/index.html index 4b2682c..8b9584f 100644 --- a/docs/posts/bye_bye_BDFs/index.html +++ b/docs/posts/bye_bye_BDFs/index.html @@ -42,12 +42,30 @@ Bye Bye BDFs
    -

    Glyph Bitmap Distribution Format is no more, as the creators of Pango, one of the most widely used text rendering libraries, announced their plans for Pango 1.44.

    -

    Until recently, Pango used FreeType to draw fonts. They will be moving over to Harfbuzz, an evolution of FreeType.

    +

    Glyph Bitmap Distribution Format is no more, as the creators of Pango, one of the most widely used text +rendering libraries, announced +their plans for Pango 1.44.

    +

    Until recently, Pango used FreeType to draw fonts. They will be +moving over to Harfbuzz, an evolution +of FreeType.

    Why?

    -

    In short, FreeType was hard to work with. It required complex logic, and provided no advantage over Harfbuzz (other than being able to fetch opentype metrics with ease).

    -

    Upgrading to Pango v1.44 will break your GTK applications (if you use a bdf/pcf bitmap font). Harfbuzz does support bitmap-only OpenType fonts, otbs. Convert your existing fonts over to otbs using FontForge. It is to be noted that applications such as xterm and rxvt use xft (X FreeType) to render fonts, and will remain unaffected by the update.

    -

    Both scientifica and curie will soon ship with bitmap-only OpenType font formats.

    +

    In short, FreeType was hard to work with. It required complex logic, +and provided no advantage over Harfbuzz (other than being able to fetch +opentype metrics with ease).

    +

    Upgrading to Pango v1.44 will break your GTK applications (if you use +a bdf/pcf bitmap font). Harfbuzz does +support bitmap-only OpenType fonts, otbs. Convert your +existing fonts over to otbs using FontForge. It is to be noted that +applications such as xterm and rxvt use +xft (X FreeType) to render fonts, and will remain +unaffected by the update.

    +

    Both scientifica and curie will soon ship +with bitmap-only OpenType font formats.

    diff --git a/docs/posts/call_to_ARMs/index.html b/docs/posts/call_to_ARMs/index.html index 3331107..1b13213 100644 --- a/docs/posts/call_to_ARMs/index.html +++ b/docs/posts/call_to_ARMs/index.html @@ -33,7 +33,7 @@ cm   - 2.2 + 2.3 min
    @@ -42,37 +42,60 @@ Call To ARMs
    -

    My 4th semester involves ARM programming. And proprietary tooling (Keil C). But we don’t do that here.

    +

    My 4th semester involves ARM programming. And proprietary tooling +(Keil C). But we don’t do that here.

    Building

    -

    Assembling and linking ARM binaries on non-ARM architecture devices is fairly trivial. I went along with the GNU cross bare metal toolchain binutils, which provides arm-as and arm-ld (among a bunch of other utils that I don’t care about for now).

    +

    Assembling and linking ARM binaries on non-ARM architecture devices +is fairly trivial. I went along with the GNU cross bare metal toolchain +binutils, which provides arm-as and arm-ld +(among a bunch of other utils that I don’t care about for now).

    Assemble .s files with:

    arm-none-eabi-as main.s -g -march=armv8.1-a -o main.out
    -

    The -g flag generates extra debugging information that gdb picks up. The -march option establishes target architecture.

    +

    The -g flag generates extra debugging information that +gdb picks up. The -march option establishes +target architecture.

    Link .o files with:

    arm-none-eabi-ld main.out -o main

    Running (and Debugging)

    -

    Things get interesting here. gdb on your x86 machine cannot read nor execute binaries compiled for ARM. So, we simulate an ARM processor using qemu. Now qemu allows you to run gdbserver on startup. Connecting our local gdb instance to gdbserver gives us a view into the program’s execution. Easy!

    -

    Run qemu, with gdbserver on port 1234, with our ARM binary, main:

    +

    Things get interesting here. gdb on your x86 machine +cannot read nor execute binaries compiled for ARM. So, we simulate an +ARM processor using qemu. Now qemu allows you to run +gdbserver on startup. Connecting our local gdb +instance to gdbserver gives us a view into the program’s +execution. Easy!

    +

    Run qemu, with gdbserver on port +1234, with our ARM binary, main:

    qemu-arm -singlestep -g 1234 main
    -

    Start up gdb on your machine, and connect to qemu’s gdbserver:

    +

    Start up gdb on your machine, and connect to +qemu’s gdbserver:

    (gdb) set architecture armv8-a
     (gdb) target remote localhost:1234
     (gdb) file main
     Reading symbols from main...  # yay!

    GDB Enhanced

    -

    gdb is cool, but it’s not nearly as comfortable as well fleshed out emulators/IDEs like Keil. Watching registers, CPSR and memory chunks update is pretty fun.

    -

    I came across gdb’s TUI mode (hit C-x C-a or type tui enable at the prompt). TUI mode is a godsend. It highlights the current line of execution, shows you disassembly outputs, updated registers, active breakpoints and more.

    +

    gdb is cool, but it’s not nearly as comfortable as well +fleshed out emulators/IDEs like Keil. Watching registers, CPSR and +memory chunks update is pretty fun.

    +

    I came across gdb’s TUI mode (hit C-x C-a +or type tui enable at the prompt). TUI mode is a godsend. +It highlights the current line of execution, shows you disassembly +outputs, updated registers, active breakpoints and more.

    But, it is an absolute eyesore.

    -

    Say hello to GEF! “GDB Enhanced Features” teaches our old dog some cool new tricks. Here are some additions that made my ARM debugging experience loads better:

    +

    Say hello to GEF! “GDB +Enhanced Features” teaches our old dog some cool new tricks. Here are +some additions that made my ARM debugging experience loads better:

    • Memory watches
    • -
    • Register watches, with up to 7 levels of deref (overkill, I agree)
    • +
    • Register watches, with up to 7 levels of deref (overkill, I +agree)
    • Stack tracing

    And it’s pretty! See for yourself:

    -

    +

    Editing

    -

    Vim, with syntax off because it dosen’t handle GNU ARM syntax too well.

    +

    Vim, with syntax off because it dosen’t handle GNU ARM +syntax too well.

    diff --git a/docs/posts/color_conundrum/index.html b/docs/posts/color_conundrum/index.html index 6c493c2..eeba49b 100644 --- a/docs/posts/color_conundrum/index.html +++ b/docs/posts/color_conundrum/index.html @@ -33,7 +33,7 @@ cm   - 1.3 + 1.4 min
    @@ -42,14 +42,32 @@ Color Conundrum
    -

    This piece aims to highlight (pun intended) some of the reasons behind my color free editor setup.

    -

    Imagine highlighting an entire book because all of it is important. That is exactly what (most) syntax highlighting does. It is difficult for the human eye to filter out noise in rainbow barf. Use color to draw attention, not diverge it.

    -

    At the same time, a book devoid of color is boring! What is the takeaway from this 10 line paragraph? What are the technical terms used?

    -

    Prose and code are certainly different, but the fickle minded human eye is the same. The eye constantly looks for a frame of reference, a focal point. It grows tired when it can’t find one.

    -

    The following comparison does a better job of explaining (none, ample and over-the-top highlighting, from left to right):

    -

    -

    Without highlighting (far left), it is hard to differentiate between comments and code! The florid color scheme (far right) is no good either, it contains too many attention grabbers. The center sample is a healthy balance of both. Function calls and constants stand out, and repetitive keywords and other noise (let, as) are mildly dimmed out. Comments and non-code text (sign column, status text) are dimmed further.

    -

    I’ll stop myself before I rant about color contrast and combinations.

    +

    This piece aims to highlight (pun intended) some of the reasons +behind my color free editor +setup.

    +

    Imagine highlighting an entire book because all of it is +important. That is exactly what (most) syntax highlighting does. It is +difficult for the human eye to filter out noise in rainbow barf. Use +color to draw attention, not diverge it.

    +

    At the same time, a book devoid of color is boring! What is +the takeaway from this 10 line paragraph? What are the technical terms +used?

    +

    Prose and code are certainly different, but the fickle minded human +eye is the same. The eye constantly looks for a frame of reference, a +focal point. It grows tired when it can’t find one.

    +

    The following comparison does a better job of explaining (none, ample +and over-the-top highlighting, from left to right):

    +

    +

    Without highlighting (far left), it is hard to differentiate between +comments and code! The florid color scheme (far right) is no good +either, it contains too many attention grabbers. The center sample is a +healthy balance of both. Function calls and constants stand out, and +repetitive keywords and other noise (let, as) +are mildly dimmed out. Comments and non-code text (sign column, status +text) are dimmed further.

    +

    I’ll stop myself before I rant about color contrast and +combinations.

    diff --git a/docs/posts/curing_a_case_of_git-UX/index.html b/docs/posts/curing_a_case_of_git-UX/index.html index 9c4761c..140436a 100644 --- a/docs/posts/curing_a_case_of_git-UX/index.html +++ b/docs/posts/curing_a_case_of_git-UX/index.html @@ -33,7 +33,7 @@ cm   - 9.5 + 9.6 min
    @@ -42,51 +42,86 @@ Curing A Case Of Git-UX
    -

    Git worktrees are great, but they fall behind the venerable git checkout sometimes. I attempted to fix that with fzf and a bit of bash.

    -

    -

    Fear not if you haven’t heard of “worktrees”, I have included a primer here.
    +

    Git worktrees are great, but they fall behind the venerable +git checkout sometimes. I attempted to fix that with fzf and a bit of bash.

    +

    +

    Fear not if you haven’t heard of “worktrees”, I have included a +primer here.
    Skip the primer ->.

    Why Worktrees?

    -

    Picture this. You are whacking away on a feature branch. Halfway there, in fact. Your friend asks you fix something urgently. You proceed to do one of three things:

    +

    Picture this. You are whacking away on a feature branch. Halfway +there, in fact. Your friend asks you fix something urgently. You proceed +to do one of three things:

      -
    • create a temporary branch, make a WIP commit, begin working on the fix
    • +
    • create a temporary branch, make a WIP commit, begin working on the +fix
    • stash away your changes, begin working on the fix
    • unfriend said friend for disturbing your flow
    -

    All of these options are … subpar. With the temporary branch, you are forced to create a partial, non-working commit, and then reset said commit once done with the fix. With the stash approach, you are required to now keep a mental model of the stash, be aware of untracked files that don’t get stashed by default, etc. Why won’t git just let you work on two things at the same time without thinking so much?

    -

    That is exactly what worktrees let you do. Worktrees let you have more than one checkout at a time, each checkout in a separate directory. Like creating a new clone, but safer (it disallows checking out the same branch twice) and a lot more space efficient (the new working tree is “linked” to the “main” worktree, and a good amount of stuff is shared). When your friend asks you to make the fix, you proceed like so:

    +

    All of these options are … subpar. With the temporary branch, you are +forced to create a partial, non-working commit, and then reset said +commit once done with the fix. With the stash approach, you are required +to now keep a mental model of the stash, be aware of untracked files +that don’t get stashed by default, etc. Why won’t git just let you work +on two things at the same time without thinking so much?

    +

    That is exactly what worktrees let you do. Worktrees let you have +more than one checkout at a time, each checkout in a separate directory. +Like creating a new clone, but safer (it disallows checking out the same +branch twice) and a lot more space efficient (the new working tree is +“linked” to the “main” worktree, and a good amount of stuff is shared). +When your friend asks you to make the fix, you proceed like so:

    1. Create a new working tree with:
    -
    # git worktree add -b <branch-name> <path> <from>
    +
    # git worktree add -b <branch-name> <path> <from>
     git worktree add -b fix-stuff /path/to/tree master
    1. cd into /path/to/tree
    2. Fix, test, commit, push, party
    3. Go back to your work, cd -
    -

    Easy as cake. You didn’t have to settle for a partially working commit, you didn’t to deal with this “stash” thing, and you didn’t have to unfriend your friend. Treating each branch as a directory just feels more intuitive, more UNIX-y.

    -

    A few weeks later, you find yourself singing in praise of worktrees, working on several things simultaneously. And at the same time, cursing them for being a little … clunky.

    +

    Easy as cake. You didn’t have to settle for a partially working +commit, you didn’t to deal with this “stash” thing, and you +didn’t have to unfriend your friend. Treating each branch as a directory +just feels more intuitive, more UNIX-y.

    +

    A few weeks later, you find yourself singing in praise of worktrees, +working on several things simultaneously. And at the same time, cursing +them for being a little … clunky.

    What makes them clunky?

    -

    Worktrees are great at what they claim to do. They stay out of the way when you need a checkout posthaste. However, as you start using them regularly, you realize they are not as flexible as git checkout or git switch.

    +

    Worktrees are great at what they claim to do. They stay out of the +way when you need a checkout posthaste. However, as you start using them +regularly, you realize they are not as flexible as +git checkout or git switch.

    Branch-hopping

    -

    You can git checkout <branch> from anywhere within a git repository. You can’t “jump” to a worktree in the same fashion. The closest you can get, is to run git worktree list, copy the path corresponding to your branch, and cd into it.

    +

    You can git checkout <branch> from anywhere within +a git repository. You can’t “jump” to a worktree in the same fashion. +The closest you can get, is to run git worktree list, copy +the path corresponding to your branch, and cd into it.

    Branch-hopping with the good ol’ git-checkout:

    -
    # anywhere, anytime
    +
    # anywhere, anytime
     λ git checkout feature/is-ascii-octdigit

    Meanwhile, in worktree world:

    -
    # keeping these paths in your head is hard
    +
    # keeping these paths in your head is hard
     λ git worktree list
    -~/worktrees/rustc/master                 eac6c33bc63 [master]
    -~/worktrees/rustc/improve-std-char-docs  94cba88553e [improve-std-char-docs]
    -~/worktrees/rustc/is-ascii-octdigit      bc57be3af7a [feature/is-ascii-octdigit]
    -~/my/other/path/oh/god                   op57or3ns7n [fix/some-error]
    +~/worktrees/rustc/master                 eac6c33bc63 [master]
    +~/worktrees/rustc/improve-std-char-docs  94cba88553e [improve-std-char-docs]
    +~/worktrees/rustc/is-ascii-octdigit      bc57be3af7a [feature/is-ascii-octdigit]
    +~/my/other/path/oh/god                   op57or3ns7n [fix/some-error]
     
     λ cd ~/worktrees/rustc/is-ascii-octdigit

    Branch-previewing

    -

    You can “preview” branches with git branch -v. However, to get an idea of what “recent activity” on a worktree looks like, you might need some juggling. You can’t glean much info about a worktree in a jiffy.

    +

    You can “preview” branches with git branch -v. However, +to get an idea of what “recent activity” on a worktree looks like, you +might need some juggling. You can’t glean much info about a worktree in +a jiffy.

    Branch-previewing with the good ol’ git-branch:

    -
    λ git branch -v
    +
    λ git branch -v
     + feature/is-ascii-octdigit bc57be3af7a introduce {char, u8}::is_ ...
     + improve-std-char-docs     94cba88553e add whitespace in assert ...
     * master                    eac6c33bc63 Auto merge of #100869 - n ...
    @@ -105,41 +140,60 @@ aa857eb953e Auto merge of #100537 - petrochenkov:pic ... # extra work to make the branch <-> worktree correspondence

    Shell completions

    -

    Lastly, you can bank on shell completions to fill in your branch whilst using git checkout. Worktrees have no such conveniences.

    +

    Lastly, you can bank on shell completions to fill in your branch +whilst using git checkout. Worktrees have no such +conveniences.

    We can mend these minor faults with fzf.

    Unclunkifying worktrees

    -

    I’d suggest looking up fzf (or skim or fzy). These things make it cake-easy to add interactivity to your shell. Onto fixing the first minor fault, the inability to “jump” to a worktree from anywhere within a git repository.

    -

    I have a little function called gwj which stands for “git worktree jump”. The idea is to list all the worktrees, select one with fzf, and cd to it upon selection:

    -
    gwj () {
    +

    I’d suggest looking up fzf (or skim or fzy). These things make it +cake-easy to add interactivity to your shell. Onto fixing the first +minor fault, the inability to “jump” to a worktree from anywhere within +a git repository.

    +

    I have a little function called gwj which stands for +“git worktree jump”. The idea is to list all the worktrees, select one +with fzf, and cd to it upon selection:

    +
    gwj () {
       local out
       out=$(git worktree list | fzf | awk '{print $1}')
       cd $out
     }

    That is all of it really. Head into a git repository:

    -
    # here, "master" is a directory, which contains my main
    +
    # here, "master" is a directory, which contains my main
     # worktree: a checkout of the master branch on rust-lang/rust 
     λ cd ~/worktrees/rustc/master/library/core/src
     λ # hack away

    Preferably one with a few worktrees:

    -
    λ git worktree list
    -~/worktrees/rustc/master                 eac6c33bc63 [master]
    -~/worktrees/rustc/improve-std-char-docs  94cba88553e [improve-std-char-docs]
    -~/worktrees/rustc/is-ascii-octdigit      bc57be3af7a [feature/is-ascii-octdigit]
    -

    And hit gwj (pretend that the pipe, |, is your cursor):

    -
    λ gwj
    +
    λ git worktree list
    +~/worktrees/rustc/master                 eac6c33bc63 [master]
    +~/worktrees/rustc/improve-std-char-docs  94cba88553e [improve-std-char-docs]
    +~/worktrees/rustc/is-ascii-octdigit      bc57be3af7a [feature/is-ascii-octdigit]
    +

    And hit gwj (pretend that the pipe, |, is your +cursor):

    +
    λ gwj
     > |
       4/4
    -> ~/worktrees/rustc/master                 eac6c33bc63 [master]
    -  ~/worktrees/rustc/improve-std-char-docs  94cba88553e [improve-std-char-docs]
    -  ~/worktrees/rustc/is-ascii-octdigit      bc57be3af7a [feature/is-ascii-octdigit]
    +> ~/worktrees/rustc/master eac6c33bc63 [master] + ~/worktrees/rustc/improve-std-char-docs 94cba88553e [improve-std-char-docs] + ~/worktrees/rustc/is-ascii-octdigit bc57be3af7a [feature/is-ascii-octdigit]

    Approximately type in your branch of choice:

    -
    λ gwj
    +
    λ gwj
     > docs|
       4/4
    -> ~/worktrees/rustc/improve-std-char-docs  94cba88553e [improve-std-char-docs]
    +> ~/worktrees/rustc/improve-std-char-docs 94cba88553e [improve-std-char-docs]

    And hit enter. You should find yourself in the selected worktree.

    -

    Onward, to the next fault, lack of preview-bility. We can utilize fzf’s aptly named --preview flag, to, well, preview our worktree before performing a selection:

    -
    gwj () {
    +

    Onward, to the next fault, lack of preview-bility. We can utilize +fzf’s aptly named --preview flag, to, well, preview our +worktree before performing a selection:

    +
    gwj () {
       local out
       out=$(
         git worktree list |
    @@ -148,8 +202,10 @@ aa857eb953e Auto merge of #100537 - petrochenkov:pic ...
       )
       cd $out
     }
    -

    Once again, hit gwj inside a git repository with linked worktrees:

    -
    λ gwj
    +

    Once again, hit gwj inside a git repository with linked +worktrees:

    +
    λ gwj
     ╭─────────────────────────────────────────────────────────╮
      eac6c33bc63 Auto merge of 100869 nnethercote:replace... │
      b32223fec10 Auto merge of 100707 dzvon:fix-typo, r=d... │
    @@ -167,9 +223,16 @@ aa857eb953e Auto merge of #100537 - petrochenkov:pic ...
     > /home/np/worktrees/compiler/master                 eac6c...
       /home/np/worktrees/compiler/improve-std-char-docs  94cba...
       /home/np/worktrees/compiler/is-ascii-octdigit      bc57b...
    -

    A fancy preview of the last 10 commits on the branch that the selected worktree corresponds to. In other words, sight for sore eyes. Our little script is already shaping up to be useful, you hit gwj, browse through your worktrees, preview each one and automatically cd to your selection. But we are not done yet.

    -

    The last fault was lack shell completions. A quick review of what a shell completion really does:

    -
    λ git checkout f<tab>
    +

    A fancy preview of the last 10 commits on the branch that the +selected worktree corresponds to. In other words, sight for sore eyes. +Our little script is already shaping up to be useful, you hit +gwj, browse through your worktrees, preview each one and +automatically cd to your selection. But we are not done +yet.

    +

    The last fault was lack shell completions. A quick review of what a +shell completion really does:

    +
    λ git checkout f<tab>
     feature/is-ascii-octdigit
     fix/some-error
     format-doc-tests
    @@ -177,16 +240,22 @@ aa857eb953e Auto merge of #100537 - petrochenkov:pic ...
     λ git checkout feat<tab>
     
     λ git checkout feature/is-ascii-octdigit
    -

    Each time you hit “tab”, the shell produces a few “completion candidates”, and once you have just a single candidate left, the shell inserts that for you directly into your edit line. Of course, this process varies from shell to shell.

    -

    fzf narrows down your options as you type into the prompt, but you still have to:

    +

    Each time you hit “tab”, the shell produces a few “completion +candidates”, and once you have just a single candidate left, the shell +inserts that for you directly into your edit line. Of course, this +process varies from shell to shell.

    +

    fzf narrows down your options as you type into the prompt, but you +still have to:

    1. Type gwj
    2. Hit enter
    3. Type out a query and narrow down your search
    4. Hit enter
    -

    We can speed that up a bit, have fzf narrow down the candidates on startup, just like our shell does:

    -
    gwj () {
    +

    We can speed that up a bit, have fzf narrow down the candidates on +startup, just like our shell does:

    +
    gwj () {
       local out query
       query="${1:- }"
       out=$(
    @@ -196,8 +265,12 @@ aa857eb953e Auto merge of #100537 - petrochenkov:pic ...
       )
       cd $out
     }
    -

    The change is extremely tiny, blink-and-you’ll-miss-it kinda tiny. We added a little --query flag, that allows you to prefill the prompt, and the -1 flag, that avoids the interactive finder if only one match exists on startup:

    -
    # skip through the fzf prompt:
    +

    The change is extremely tiny, blink-and-you’ll-miss-it kinda tiny. We +added a little --query flag, that allows you to prefill the +prompt, and the -1 flag, that avoids the interactive finder +if only one match exists on startup:

    +
    # skip through the fzf prompt:
     λ gwj master
     # cd -- ~/worktrees/rustc/master
     
    @@ -212,8 +285,11 @@ aa857eb953e Auto merge of #100537 - petrochenkov:pic ...
       2/2
     > /home/np/worktrees/compiler/improve-const-perf     eac6c...
       /home/np/worktrees/compiler/improve-std-char-docs  94cba...
    -

    Throw some error handling in there, hook up a similar script to improve the UX of git worktree remove, go wild. A few more helpers I’ve got:

    -
    # gwa /path/to/branch-name
    +

    Throw some error handling in there, hook up a similar script to +improve the UX of git worktree remove, go wild. A few more +helpers I’ve got:

    +
    # gwa /path/to/branch-name
     # creates a new branch and "switches" to it
     function gwa () {
       git worktree add "$1" && cd "$1"
    diff --git a/docs/posts/font_size_fallacies/index.html b/docs/posts/font_size_fallacies/index.html
    index 9577376..51f5b4b 100644
    --- a/docs/posts/font_size_fallacies/index.html
    +++ b/docs/posts/font_size_fallacies/index.html
    @@ -28,12 +28,12 @@
                 17/03 — 2020
                 
    - 32.36 + 32.37 cm   - 3.2 + 3.3 min
    @@ -42,34 +42,75 @@ Font Size Fallacies
    -

    I am not an expert with fonts, but I do have some experience 1, and common sense. This post aims to debunk some misconceptions about font sizes!

    -

    11 px on your display is probably not 11 px on my display. Let’s do some quick math. I have two displays, 1366x768 @ 21" and another with 1920x1080 @ 13", call them A and B for now.

    -

    Display A has 1,049,088 pixels. A pixel is a square, of side say, s cm. The total area covered by my 21" display is about 1,066 cm^2 (41x26). Thus,

    +

    I am not an expert with fonts, but I do have some experience 1, and common sense. This post aims to +debunk some misconceptions about font sizes!

    +

    11 px on your display is probably not 11 px on my display. +Let’s do some quick math. I have two displays, 1366x768 @ 21” and +another with 1920x1080 @ 13”, call them A and +B for now.

    +

    Display A has 1,049,088 pixels. A pixel is a square, of +side say, s cm. The total area covered by my 21” display is +about 1,066 cm^2 (41x26). Thus,

    Display A
     Dimensions: 1366x768 @ 21" (41x26 sq. cm)
     1,049,088 s^2 = 1066
                 s = 0.0318 cm (side of a pixel on Display A)
    -

    Bear with me, as I repeat the number crunching for Display B:

    +

    Bear with me, as I repeat the number crunching for Display +B:

    Display B
     Dimensions: 1920x1080 @ 13" (29.5x16.5 sq. cm)
     2,073,600 s^2 = 486.75
                 s = 0.0153 cm (side of a pixel on Display B)
    -

    The width of a pixel on Display A is double the width of a pixel on Display B. The area occupied by a pixel on Display A is 4 times the area occupied by a pixel on Display B.

    +

    The width of a pixel on Display A is double the +width of a pixel on Display B. The area occupied by a pixel +on Display A is 4 times the area occupied by a +pixel on Display B.

    The size of a pixel varies from display to display!

    -

    A 5x11 bitmap font on Display A would be around 4 mm tall whereas the same bitmap font on Display B would be around 1.9 mm tall. A 11 px tall character on B is visually equivalent to a 5 px character on A. When you view a screenshot of Display A on Display B, the contents are shrunk down by a factor of 2!

    -

    So screen resolution is not enough, how else do we measure size? Pixel Density! Keen readers will realize that the 5^th grade math problem we solved up there showcases pixel density, or, pixels per cm (PPCM). Usually we deal with pixels per inch (PPI).

    -

    Note: PPI is not to be confused with DPI 2 (dots per inch). DPI is defined for printers.

    -

    In our example, A is a 75 ppi display and B is around 165 ppi 3. A low ppi display appears to be ‘pixelated’, because the pixels are more prominent, much like Display A. A higher ppi usually means you can view larger images and render crispier fonts. The average desktop display can stuff 100-200 pixels per inch. Smart phones usually fall into the 400-600 ppi (XXXHDPI) category. The human eye fails to differentiate detail past 300 ppi.

    -

    So … streaming an 8K video on a 60" TV provides the same clarity as a HD video on a smart phone?

    -

    Absolutely. Well, clarity is subjective, but the amount of detail you can discern on mobile displays has always been limited. Salty consumers of the Xperia 1 4 will say otherwise.

    -

    Maybe I will talk about font rendering in another post, but thats all for now. Don’t judge a font size by its screenshot.

    -
    +

    A 5x11 bitmap font on Display A would be around 4 mm +tall whereas the same bitmap font on Display B would be +around 1.9 mm tall. A 11 px tall character on B is visually +equivalent to a 5 px character on A. When you view a +screenshot of Display A on Display B, the +contents are shrunk down by a factor of 2!

    +

    So screen resolution is not enough, how else do we measure size? +Pixel Density! Keen readers will realize that the 5^th grade math +problem we solved up there showcases pixel density, or, pixels per cm +(PPCM). Usually we deal with pixels per inch (PPI).

    +

    Note: PPI is not to be confused with DPI 2 (dots per inch). DPI is defined for +printers.

    +

    In our example, A is a 75 ppi display and B +is around 165 ppi 3. A low ppi display appears to be +‘pixelated’, because the pixels are more prominent, much like Display +A. A higher ppi usually means you can view larger images +and render crispier fonts. The average desktop display can stuff 100-200 +pixels per inch. Smart phones usually fall into the 400-600 ppi +(XXXHDPI) category. The human eye fails to differentiate detail past 300 +ppi.

    +

    So … streaming an 8K video on a 60” TV provides the same clarity +as a HD video on a smart phone?

    +

    Absolutely. Well, clarity is subjective, but the amount of detail you +can discern on mobile displays has always been limited. Salty consumers +of the Xperia 1 4 will say otherwise.

    +

    Maybe I will talk about font rendering in another post, but thats all +for now. Don’t judge a font size by its screenshot.

    +

      -
    1. https://github.com/nerdypepper/scientifica↩︎

    2. -
    3. https://en.wikipedia.org/wiki/Dots_per_inch↩︎

    4. -
    5. https://www.sven.de/dpi/↩︎

    6. -
    7. https://en.wikipedia.org/wiki/Sony_Xperia_1↩︎

    8. +
    9. https://github.com/nerdypepper/scientifica↩︎

    10. +
    11. https://en.wikipedia.org/wiki/Dots_per_inch↩︎

    12. +
    13. https://www.sven.de/dpi/↩︎

    14. +
    15. https://en.wikipedia.org/wiki/Sony_Xperia_1↩︎

    diff --git a/docs/posts/get_better_at_yanking_and_putting_in_vim/index.html b/docs/posts/get_better_at_yanking_and_putting_in_vim/index.html index 469afe5..c6d3368 100644 --- a/docs/posts/get_better_at_yanking_and_putting_in_vim/index.html +++ b/docs/posts/get_better_at_yanking_and_putting_in_vim/index.html @@ -28,7 +28,7 @@ 30/07 — 2019
    - 10.78 + 10.79 cm   @@ -44,7 +44,8 @@

    a couple of nifty tricks to help you copy-paste better:

      -
    1. reselecting previously selected text (i use this to fix botched selections):

      +
    2. reselecting previously selected text (i use this to fix botched +selections):

      gv  " :h gv for more
           " you can use `o` in visual mode to go to the `Other` end of the selection
           " use a motion to fix the selection
    3. diff --git a/docs/posts/gripes_with_go/index.html b/docs/posts/gripes_with_go/index.html index 1551fe6..74d6995 100644 --- a/docs/posts/gripes_with_go/index.html +++ b/docs/posts/gripes_with_go/index.html @@ -28,7 +28,7 @@ 01/08 — 2020
      - 76.71 + 76.72 cm   @@ -42,17 +42,24 @@ Gripes With Go
      -

      You’ve read a lot of posts about the shortcomings of the Go programming language, so what’s one more.

      +

      You’ve read a lot of posts about the shortcomings of the Go +programming language, so what’s one more.

      1. Lack of sum types
      2. Type assertions
      3. Date and Time
      4. -
      5. Statements over Expressions
      6. -
      7. Erroring out on unused variables
      8. +
      9. Statements over +Expressions
      10. +
      11. Erroring out on unused +variables
      12. Error handling

      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 “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
       
      @@ -67,17 +74,18 @@
       // 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"
      +    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
      +
      data Gender = Male
                   | Female
                   | Other
                   deriving (Show)
      @@ -88,7 +96,7 @@
       

      Type assertions in Go allow you to do:

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

      The error check however is optional:

      @@ -98,18 +106,32 @@ // 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:

      +

      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:

      +

      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:

      +

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

      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 …

      +

      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 = {
      +

      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
      @@ -120,17 +142,25 @@
       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.

      +

      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. -
      3. Errors are propagated via a clunky if + return statement
      4. +
      5. 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
      +

      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
      @@ -144,13 +174,16 @@
       fn main() {
           // `contents` is an enum known as Result:
           let contents = foo();
      -    match contents {
      +    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.

      +

      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/hold_position!/index.html b/docs/posts/hold_position!/index.html index ec63508..68955fe 100644 --- a/docs/posts/hold_position!/index.html +++ b/docs/posts/hold_position!/index.html @@ -28,7 +28,7 @@ 30/07 — 2019
      - 9.18 + 9.19 cm   @@ -42,14 +42,24 @@ Hold Position!
      -

      Often times, when I run a vim command that makes “big” changes to a file (a macro or a :vimgrep command) I lose my original position and feel disoriented.

      +

      Often times, when I run a vim command that makes “big” changes to a +file (a macro or a :vimgrep command) I lose my original +position and feel disoriented.

      Save position with winsaveview()!

      -

      The winsaveview() command returns a Dictionary that contains information about the view of the current window. This includes the cursor line number, cursor coloumn, the top most line in the window and a couple of other values, none of which concern us.

      -

      Before running our command (one that jumps around the buffer, a lot), we save our view, and restore it once its done, with winrestview.

      +

      The winsaveview() command returns a +Dictionary that contains information about the view of the +current window. This includes the cursor line number, cursor coloumn, +the top most line in the window and a couple of other values, none of +which concern us.

      +

      Before running our command (one that jumps around the buffer, a lot), +we save our view, and restore it once its done, with +winrestview.

      let view = winsaveview()
       s/\s\+$//gc              " find and (confirm) replace trailing blanks
       winrestview(view)        " restore our original view!
      -

      It might seem a little overkill in the above example, just use `` (double backticks) instead, but it comes in handy when you run your file through heavier filtering.

      +

      It might seem a little overkill in the above example, just use `` +(double backticks) instead, but it comes in handy when you run your file +through heavier filtering.

      diff --git a/docs/posts/index.html b/docs/posts/index.html index 48452c0..8caab03 100644 --- a/docs/posts/index.html +++ b/docs/posts/index.html @@ -35,7 +35,7 @@ - 9.5 + 9.6 min @@ -86,7 +86,7 @@ - 4.7 + 4.8 min @@ -103,7 +103,7 @@ - 8.5 + 8.6 min @@ -171,7 +171,7 @@ - 3.3 + 3.4 min @@ -273,7 +273,7 @@ - 3.2 + 3.3 min @@ -307,7 +307,7 @@ - 2.2 + 2.3 min @@ -324,7 +324,7 @@ - 1.3 + 1.4 min diff --git a/docs/posts/lightweight_linting/index.html b/docs/posts/lightweight_linting/index.html index 9bc84f2..b30c719 100644 --- a/docs/posts/lightweight_linting/index.html +++ b/docs/posts/lightweight_linting/index.html @@ -28,12 +28,12 @@ 26/01 — 2022
      - 170.62 + 170.63 cm   - 8.5 + 8.6 min
      @@ -42,14 +42,23 @@ Lightweight Linting
      -

      Tree-sitter queries allow you to search for patterns in syntax trees, much like a regex would, in text. Combine that with some Rust glue to write simple, custom linters.

      +

      Tree-sitter +queries allow you to search for patterns in syntax trees, much like a +regex would, in text. Combine that with some Rust glue to write simple, +custom linters.

      Tree-sitter syntax trees

      -

      Here is a quick crash course on syntax trees generated by tree-sitter. Syntax trees produced by tree-sitter are represented by S-expressions. The generated S-expression for the following Rust code,

      -
      fn main() {
      +

      Here is a quick crash course on syntax trees generated by +tree-sitter. Syntax trees produced by tree-sitter are represented by +S-expressions. The generated S-expression for the following Rust +code,

      +
      fn main() {
           let x = 2;
       }

      would be:

      -
      (source_file
      +
      (source_file
        (function_item
         name: (identifier)
         parameters: (parameters)
      @@ -58,13 +67,19 @@
          (let_declaration 
           pattern: (identifier)
           value: (integer_literal)))))
      -

      Syntax trees generated by tree-sitter have a couple of other cool properties: they are lossless syntax trees. Given a lossless syntax tree, you can regenerate the original source code in its entirety. Consider the following addition to our example:

      -
       fn main() {
      +

      Syntax trees generated by tree-sitter have a couple of other cool +properties: they are lossless syntax trees. Given a lossless +syntax tree, you can regenerate the original source code in its +entirety. Consider the following addition to our example:

      +
       fn main() {
       +    // a comment goes here
            let x = 2;
        }
      -

      The tree-sitter syntax tree preserves the comment, while the typical abstract syntax tree wouldn’t:

      -
       (source_file
      +

      The tree-sitter syntax tree preserves the comment, while the typical +abstract syntax tree wouldn’t:

      +
       (source_file
         (function_item
          name: (identifier)
          parameters: (parameters)
      @@ -75,25 +90,34 @@
            pattern: (identifier)
            value: (integer_literal)))))

      Tree-sitter queries

      -

      Tree-sitter provides a DSL to match over CSTs. These queries resemble our S-expression syntax trees, here is a query to match all line comments in a Rust CST:

      -
      (line_comment)
      +

      Tree-sitter provides a DSL to match over CSTs. These queries resemble +our S-expression syntax trees, here is a query to match all line +comments in a Rust CST:

      +
      (line_comment)
       
       ; matches the following rust code
       ; // a comment goes here
      -

      Neat, eh? But don’t take my word for it, give it a go on the tree-sitter playground. Type in a query like so:

      -
      ; the web playground requires you to specify a "capture"
      +

      Neat, eh? But don’t take my word for it, give it a go on the tree-sitter +playground. Type in a query like so:

      +
      ; the web playground requires you to specify a "capture"
       ; you will notice the capture and the nodes it captured
       ; turn blue
       (line_comment) @capture
      -

      Here’s another to match let expressions that bind an integer to an identifier:

      -
      (let_declaration
      +

      Here’s another to match let expressions that bind an +integer to an identifier:

      +
      (let_declaration
        pattern: (identifier)
        value: (integer_literal))
        
       ; matches:
       ; let foo = 2;

      We can capture nodes into variables:

      -
      (let_declaration 
      +
      (let_declaration 
        pattern: (identifier) @my-capture
        value: (integer_literal))
        
      @@ -103,7 +127,8 @@
       ; captures:
       ; foo

      And apply certain predicates to captures:

      -
      ((let_declaration
      +
      ((let_declaration
         pattern: (identifier) @my-capture
         value: (integer_literal))
        (#eq? @my-capture "foo"))
      @@ -113,8 +138,10 @@
       
       ; and not:
       ; let bar = 2;
      -

      The #match? predicate checks if a capture matches a regex:

      -
      ((let_declaration
      +

      The #match? predicate checks if a capture matches a +regex:

      +
      ((let_declaration
         pattern: (identifier) @my-capture
         value: (integer_literal))
        (#match? @my-capture "foo|bar"))
      @@ -122,8 +149,10 @@
       ; matches both `foo` and `bar`:
       ; let foo = 2;
       ; let bar = 2;
      -

      Exhibit indifference, as a stoic programmer would, with the wildcard pattern:

      -
      (let_declaration
      +

      Exhibit indifference, as a stoic programmer would, with the +wildcard pattern:

      +
      (let_declaration
        pattern: (identifier)
        value: (_))
        
      @@ -131,73 +160,106 @@
       ; let foo = "foo";
       ; let foo = 42;
       ; let foo = bar;
      -

      The documentation does the tree-sitter query DSL more justice, but we now know enough to write our first lint.

      +

      The +documentation does the tree-sitter query DSL more justice, but we +now know enough to write our first lint.

      Write you a tree-sitter lint

      Strings in std::env functions are error prone:

      -
      std::env::remove_var("RUST_BACKTACE");
      +
      std::env::remove_var("RUST_BACKTACE");
                                   // ^^^^ "TACE" instead of "TRACE"

      I prefer this instead:

      -
      // somewhere in a module that is well spellchecked
      +
      // somewhere in a module that is well spellchecked
       static BACKTRACE: &str = "RUST_BACKTRACE";
       
       // rest of the codebase
       std::env::remove_var(BACKTRACE);
      -

      Let’s write a lint to find std::env functions that use strings. Put aside the effectiveness of this lint for the moment, and take a stab at writing a tree-sitter query. For reference, a function call like so:

      -
      remove_var("RUST_BACKTRACE")
      +

      Let’s write a lint to find std::env functions that use +strings. Put aside the effectiveness of this lint for the moment, and +take a stab at writing a tree-sitter query. For reference, a function +call like so:

      +
      remove_var("RUST_BACKTRACE")

      Produces the following S-expression:

      -
      (call_expression
      +
      (call_expression
         function: (identifier)
         arguments: (arguments (string_literal)))

      We are definitely looking for a call_expression:

      -
      (call_expression) @raise
      -

      Whose function name matches std::env::var or std::env::remove_var at the very least (I know, I know, this isn’t the most optimal regex):

      -
      ((call_expression
      +
      (call_expression) @raise
      +

      Whose function name matches std::env::var or +std::env::remove_var at the very least (I know, I know, +this isn’t the most optimal regex):

      +
      ((call_expression
         function: (_) @fn-name) @raise
        (#match? @fn-name "std::env::(var|remove_var)"))

      Let’s turn that std:: prefix optional:

      -
      ((call_expression
      +
      ((call_expression
         function: (_) @fn-name) @raise
        (#match? @fn-name "(std::|)env::(var|remove_var)"))

      And ensure that arguments is a string:

      -
      ((call_expression
      +
      ((call_expression
         function: (_) @fn-name
         arguments: (arguments (string_literal)))
        (#match? @fn-name "(std::|)env::(var|remove_var)"))

      Running our linter

      -

      We could always plug our query into the web playground, but let’s go a step further:

      -
      cargo new --bin toy-lint
      -

      Add tree-sitter and tree-sitter-rust to your dependencies:

      -
      # within Cargo.toml
      +

      We could always plug our query into the web playground, but let’s go +a step further:

      +
      cargo new --bin toy-lint
      +

      Add tree-sitter and tree-sitter-rust to +your dependencies:

      +
      # within Cargo.toml
       [dependencies]
       tree-sitter = "0.20"
       
       [dependencies.tree-sitter-rust]
       git = "https://github.com/tree-sitter/tree-sitter-rust"
      -

      Let’s load in some Rust code to work with. As an ode to Gödel (Godel?), why not load in our linter itself:

      -
      fn main() {
      +

      Let’s load in some Rust code to work with. As an ode to Gödel +(Godel?), why not load in our linter itself:

      +
      fn main() {
           let src = include_str!("main.rs");
       }
      -

      Most tree-sitter APIs require a reference to a Language struct, we will be working with Rust if you haven’t already guessed:

      -
      use tree_sitter::Language;
      +

      Most tree-sitter APIs require a reference to a Language +struct, we will be working with Rust if you haven’t already guessed:

      +
      use tree_sitter::Language;
       
       let rust_lang: Language = tree_sitter_rust::language();

      Enough scaffolding, let’s parse some Rust:

      -
      use tree_sitter::Parser;
      +
      use tree_sitter::Parser;
       
       let mut parser = Parser::new();
       parser.set_language(rust_lang).unwrap();
       
       let parse_tree = parser.parse(&src, None).unwrap();
      -

      The second argument to Parser::parse may be of interest. Tree-sitter has this cool feature that allows for quick reparsing of existing parse trees if they contain edits. If you do happen to want to reparse a source file, you can pass in the old tree:

      -
      // if you wish to reparse instead of parse
      +

      The second argument to Parser::parse may be of interest. +Tree-sitter has this cool feature that allows for quick reparsing of +existing parse trees if they contain edits. If you do happen to want to +reparse a source file, you can pass in the old tree:

      +
      // if you wish to reparse instead of parse
       old_tree.edit(/* redacted */);
       
       // generate shiny new reparsed tree
       let new_tree = parser.parse(&src, Some(old_tree)).unwrap()
      -

      Anyhow (hah!), now that we have a parse tree, we can inspect it:

      -
      println!("{}", parse_tree.root_node().to_sexp());
      +

      Anyhow (hah!), now +that we have a parse tree, we can inspect it:

      +
      println!("{}", parse_tree.root_node().to_sexp());

      Or better yet, run a query on it:

      -
      use tree_sitter::Query;
      +
      use tree_sitter::Query;
       
       let query = Query::new(
           rust_lang,
      @@ -209,8 +271,11 @@
           "#
       )
       .unwrap();
      -

      A QueryCursor is tree-sitter’s way of maintaining state as we iterate through the matches or captures produced by running a query on the parse tree. Observe:

      -
      use tree_sitter::QueryCursor;
      +

      A QueryCursor is tree-sitter’s way of maintaining state +as we iterate through the matches or captures produced by running a +query on the parse tree. Observe:

      +
      use tree_sitter::QueryCursor;
       
       let mut query_cursor = QueryCursor::new();
       let all_matches = query_cursor.matches(
      @@ -218,15 +283,22 @@
           parse_tree.root_node(),
           src.as_bytes(),
       );
      -

      We begin by passing our query to the cursor, followed by the “root node”, which is another way of saying, “start from the top”, and lastly, the source itself. If you have already taken a look at the C API, you will notice that the last argument, the source (known as the TextProvider), is not required. The Rust bindings seem to require this argument to provide predicate functionality such as #match? and #eq?.

      +

      We begin by passing our query to the cursor, followed by the “root +node”, which is another way of saying, “start from the top”, and lastly, +the source itself. If you have already taken a look at the C API, you +will notice that the last argument, the source (known as the +TextProvider), is not required. The Rust bindings seem to +require this argument to provide predicate functionality such as +#match? and #eq?.

      Do something with the matches:

      -
      // get the index of the capture named "raise"
      +
      // get the index of the capture named "raise"
       let raise_idx = query.capture_index_for_name("raise").unwrap();
       
      -for each_match in all_matches {
      +for each_match in all_matches {
           // iterate over all captures called "raise"
           // ignore captures such as "fn-name"
      -    for capture in each_match
      +    for capture in each_match
               .captures
               .iter()
               .filter(|c| c.idx == raise_idx)
      @@ -241,8 +313,10 @@
               );
           }
       }
      -

      Lastly, add the following line to your source code, to get the linter to catch something:

      -
      env::remove_var("RUST_BACKTRACE");
      +

      Lastly, add the following line to your source code, to get the linter +to catch something:

      +
      env::remove_var("RUST_BACKTRACE");

      And cargo run:

      λ cargo run
          Compiling toy-lint v0.1.0 (/redacted/path/to/toy-lint)
      @@ -251,17 +325,33 @@
       [Line: 40, Col: 4] Offending source code: `env::remove_var("RUST_BACKTRACE")`

      Thank you tree-sitter!

      Bonus

      -

      Keen readers will notice that I avoided std::env::set_var. Because set_var is called with two arguments, a “key” and a “value”, unlike env::var and env::remove_var. As a result, it requires more juggling:

      -
      ((call_expression
      +

      Keen readers will notice that I avoided +std::env::set_var. Because set_var is called +with two arguments, a “key” and a “value”, unlike env::var +and env::remove_var. As a result, it requires more +juggling:

      +
      ((call_expression
         function: (_) @fn-name
         arguments: (arguments . (string_literal)? . (string_literal) .)) @raise
        (#match? @fn-name "(std::|)env::(var|remove_var|set_var)"))
      -

      The interesting part of this query is the humble ., the anchor operator. Anchors help constrain child nodes in certain ways. In this case, it ensures that we match exactly two string_literals who are siblings or exactly one string_literal with no siblings. Unfortunately, this query also matches the following invalid Rust code:

      -
      // remove_var accepts only 1 arg!
      +

      The interesting part of this query is the humble ., the +anchor operator. Anchors help constrain child nodes in certain +ways. In this case, it ensures that we match exactly two +string_literals who are siblings or exactly one +string_literal with no siblings. Unfortunately, this query +also matches the following invalid Rust code:

      +
      // remove_var accepts only 1 arg!
       std::env::remove_var("RUST_BACKTRACE", "1");

      Notes

      -

      All-in-all, the query DSL does a great job in lowering the bar to writing language tools. The knowledge gained from mastering the query DSL can be applied to other languages that have tree-sitter grammars too. This query detects to_json methods that do not accept additional arguments, in Ruby:

      -
      ((method
      +

      All-in-all, the query DSL does a great job in lowering the bar to +writing language tools. The knowledge gained from mastering the query +DSL can be applied to other languages that have tree-sitter grammars +too. This query detects to_json methods that do not accept +additional arguments, in Ruby:

      +
      ((method
         name: (identifier) @fn
         !parameters)
        (#is? @fn "to_json"))
      diff --git a/docs/posts/lotus58/index.html b/docs/posts/lotus58/index.html index 44a3c96..f4a07a2 100644 --- a/docs/posts/lotus58/index.html +++ b/docs/posts/lotus58/index.html @@ -33,7 +33,7 @@ cm   - 4.7 + 4.8 min
      @@ -42,29 +42,46 @@ Lotus58
      -

      Earlier this month, I decided that I would laugh at Indian customs in the face by building a split-ergo mechanical keyboard from scratch rather than purchasing a Moonlander.

      +

      Earlier this month, I decided that I would laugh at Indian customs in +the face by building a split-ergo mechanical keyboard from scratch +rather than purchasing a Moonlander.

      -The finished product +The finished product +

      Sourcing the parts

      -

      If you, like me, live in India, you might find this section useful. My approach to finding parts:

      +

      If you, like me, live in India, you might find this section useful. +My approach to finding parts:

      • Check reputed, local online stores
      • Check physical hardware stores
      • Import the part

      PCBs

      -

      This was by far the hardest component to procure. Fabrication services have certain capabilities. Capabilities are the limitations of a fabrication service. For example, a service may be capable of drilling holes no smaller than 0.3mm in diameter. Most sites have a verification process to check if their capabilities meet your design’s requirements. I tried a few local PCB fabrication services:

      +

      This was by far the hardest component to procure. Fabrication +services have certain capabilities. Capabilities are the +limitations of a fabrication service. For example, a service may be +capable of drilling holes no smaller than 0.3mm in diameter. Most sites +have a verification process to check if their capabilities meet your +design’s requirements. I tried a few local PCB fabrication services:

      • Lion PCB: Capabilities did not meet my requirements
      • PCBPower: Capabilities did not meet my requirements
      • Circuitwala: Capabilities did not meet my requirements
      -

      I settled for JLCPCB, a Chinese service. PCBs themselves were 16 USD, shipping was another 35 USD, and customs was another 3.5K INR (ouch).

      +

      I settled for JLCPCB, a Chinese service. PCBs themselves were 16 USD, +shipping was another 35 USD, and customs was another 3.5K INR +(ouch).

      Case material

      -

      I don’t really have a case for the Lotus58, it is more of a “plastic sandwich”. I purchased acrylic plates from Robu. Cheap, fast, solid, and customizable. I cannot recommend Robu enough. A full set of plates (2 top plates and 2 bottom plates) cost me about 500 INR. I also bought a pair of laptop height raisers on Amazon to create a budget tenting setup.

      +

      I don’t really have a case for the Lotus58, it is more of a “plastic +sandwich”. I purchased acrylic plates from Robu. Cheap, fast, solid, and +customizable. I cannot recommend Robu enough. A full set of plates (2 +top plates and 2 bottom plates) cost me about 500 INR. I also bought a +pair of laptop height raisers on Amazon to create a budget tenting +setup.

      Electronics

      -

      You’ll need a few rather specific electronic components such as hotswap sockets and TRRS mounts, the rest are commonly available:

      +

      You’ll need a few rather specific electronic components such as +hotswap sockets and TRRS mounts, the rest are commonly available:

      • Hotswap sockets: StacksKB
      • TRRS mounts (PJ 320A): StacksKB
      • @@ -73,7 +90,8 @@
      • M2 spacers: ThinkRobotics
      • Arduino Pro Micro: Robu
      -

      I skimped out on optional components such as OLEDs and rotary encoders.

      +

      I skimped out on optional components such as OLEDs and rotary +encoders.

      Switches and Keycaps

      Arguably the most fun part of the build:

        @@ -81,30 +99,57 @@
      • DSA blanks: Meckeys

      Building the keyboard

      -

      The the build is extremely straightforward. Through hole components are easy to solder. Be wary of component placement and orientation. Check thrice, solder once. Few debugging tips:

      +

      The the build is extremely straightforward. Through hole components +are easy to solder. Be wary of component placement and orientation. +Check thrice, solder once. Few debugging tips:

        -
      • if a single key does not actuate, check the hotswap for poor soldering (reflow the joint), and the switch pins for deformation during installation
      • -
      • if an entire column or row activates on a single key-press, a connection has been shorted
      • -
      • if only some of the keys on a given row actuate, a diode has been soldered on the wrong way
      • +
      • if a single key does not actuate, check the hotswap for poor +soldering (reflow the joint), and the switch pins for deformation during +installation
      • +
      • if an entire column or row activates on a single key-press, a +connection has been shorted
      • +
      • if only some of the keys on a given row actuate, a diode has been +soldered on the wrong way

      The typing experience

      -

      I decidede to give QWERTY the boot and learn Colemak along with the new keyboard. The first few weeks were terrible because I could neither type QWERTY nor Colemak, but I got the hang of it pretty quickly. Typing websites do help, but it is best to simply use it in your daily workflow. No site can help you get accustomed to the various things you use your keyboard for such as switching windows or navigating vim/tmux.

      +

      I decidede to give QWERTY the boot and learn Colemak along with the +new keyboard. The first few weeks were terrible because I could neither +type QWERTY nor Colemak, but I got the hang of it pretty quickly. Typing +websites do help, but it is best to simply use it in your daily +workflow. No site can help you get accustomed to the various things you +use your keyboard for such as switching windows or navigating +vim/tmux.

      Colemak

      -

      Alt layouts such as Colemak are definitely worth it. I find that Colemak reduces finger movement a lot, a good portion of the keys on the left hand are the same as QWERTY, it is fairly easy to pick up as well.

      +

      Alt layouts such as Colemak are definitely worth it. I find that +Colemak reduces finger movement a lot, a good portion of the keys on the +left hand are the same as QWERTY, it is fairly easy to pick up as +well.

      Vim

      -

      Using an alt layout means most programs with keyboard shortcuts are not going to work as expected, HJKL on vim for movements being one of them. I took the short route out by creating a new layer with arrow keys on the home row:

      +

      Using an alt layout means most programs with keyboard shortcuts are +not going to work as expected, HJKL on vim for movements +being one of them. I took the short route out by creating a new layer +with arrow keys on the home row:

      default homerow:
       H N E I
       
       "nav" layer:
       < v ^ >
      -

      The remaining commands in vim are largely mnemonics. Navigating with home-row arrow keys also means that I can use “HJKL” globally, to scroll a website, for example.

      +

      The remaining commands in vim are largely mnemonics. Navigating with +home-row arrow keys also means that I can use “HJKL” globally, to scroll +a website, for example.

      Cutting down to 34 keys

      -

      A couple months into my ergo journey, I realized that I could get away by moving my fingers even lesser. I moved modifiers such as Super, Ctrl, Alt and Shift to the home-row as QMK Mod Taps. The rest of the keys are cleverly placed in layers, not too much unlike the Miryoku layout. Even for someone that writes Rust (a symbol-heavy grammar), I find 34-keys to be sufficient.

      +

      A couple months into my ergo journey, I realized that I could get +away by moving my fingers even lesser. I moved modifiers such as +Super, Ctrl, Alt and +Shift to the home-row as QMK Mod Taps. The rest of the keys +are cleverly placed in layers, not too much unlike the Miryoku layout. +Even for someone that writes Rust (a symbol-heavy grammar), I find +34-keys to be sufficient.

      Conclusion

      I have been bitten by the ergomech bug.

      -The Lotus58 in action +The Lotus58 in action +
      diff --git a/docs/posts/my_setup/index.html b/docs/posts/my_setup/index.html index 34d07af..e35a33c 100644 --- a/docs/posts/my_setup/index.html +++ b/docs/posts/my_setup/index.html @@ -44,10 +44,27 @@

      Decided to do one of these because everyone does one of these.

      -

      My entire setup is managed with GNU stow, making it easier to replicate on fresh installations. You can find my configuration files on GitHub.

      -

      I run Void Linux (glibc) on my HP Envy 13" (2018). To keep things simple, I run a raw X session with 2bwm as my window manager, along with dunst (notification daemon) and Sam’s compton (compositor) fork.

      -

      I am a fan of GNU tools, so I use bash as my shell, and coreutils to manage files, archives, strings, paths etc. I edit files with vim, chat with weechat, listen to music with cmus, monitor processes with htop, manage sessions with tmux, read pdfs in zathura. I rarely ever leave the comfort of my terminal emulator, urxvt.

      -

      Most of my academic typesetting is done with TeX, and compiled with xelatex. Other fun documents are made with GIMP :).

      +

      My entire setup is managed with GNU stow, making it +easier to replicate on fresh installations. You can find my +configuration files on GitHub.

      +

      I run Void Linux (glibc) on my HP Envy 13” +(2018). To keep things simple, I run a raw X session with +2bwm as my window manager, along with dunst +(notification daemon) and Sam’s compton +(compositor) fork.

      +

      I am a fan of GNU tools, so I use bash as my shell, and +coreutils to manage files, archives, strings, paths etc. I +edit files with vim, chat with weechat, listen +to music with cmus, monitor processes with +htop, manage sessions with tmux, read pdfs in +zathura. I rarely ever leave the comfort of my terminal +emulator, urxvt.

      +

      Most of my academic typesetting is done with TeX, and compiled with +xelatex. Other fun documents are made with GIMP +:).

      diff --git a/docs/posts/nixOS/index.html b/docs/posts/nixOS/index.html index 75be58f..9650bdd 100644 --- a/docs/posts/nixOS/index.html +++ b/docs/posts/nixOS/index.html @@ -33,7 +33,7 @@ cm   - 3.3 + 3.4 min
      @@ -42,11 +42,24 @@ NixOS
      -

      I have been eyeing operating systems with functional package managers for a while now, aka, NixOS or Guix. Reproducible builds, declarative and rollback-able system configuration, system consistency, all sound pretty cool. I have been using NixOS for about a month now.

      +

      I have been eyeing operating systems with functional package managers +for a while now, aka, NixOS or Guix. Reproducible builds, declarative +and rollback-able system configuration, system consistency, all sound +pretty cool. I have been using NixOS for about a month now.

      Installation

      -

      I went with their minimal installation ISO. The installation was pretty smooth from start to end, no hitches there. The entire manual is available offline, and is accessible during the installation. Very handy.

      +

      I went with their minimal installation ISO. The installation was +pretty smooth from start to end, no hitches there. The entire manual is available +offline, and is accessible during the installation. Very handy.

      Setup

      -

      The entire system is configured via /etc/nixos/configuration.nix. Wifi, libinput gestures, audio, locale settings, there are options for literally everything. You can declaratively write down the packages you want installed too. With fresh installs of most distros, I usually fumble with getting things like screen backlight and media keys to work. If I do manage to fix it, I can’t carry it forward to future installations trivially. Getting all my hardware to work on NixOS is as easy as:

      +

      The entire system is configured via +/etc/nixos/configuration.nix. Wifi, libinput +gestures, audio, locale settings, there are options for literally +everything. You can declaratively write down the packages you want +installed too. With fresh installs of most distros, I usually fumble +with getting things like screen backlight and media keys to work. If I +do manage to fix it, I can’t carry it forward to future installations +trivially. Getting all my hardware to work on NixOS is as easy as:

      {
           server.xserver.libinput.enable = true;  # touchpad
           programs.light.enable = true;           # backlight
      @@ -54,20 +67,53 @@
           networking.wireless.enable = true;      # wifi
       }

      Developing with Nix

      -

      Nix makes it easy to enter environments that aren’t affected by your system configuration using nix-shell.

      -

      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 makes it easy to enter environments that aren’t affected by your +system configuration using nix-shell.

      +

      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 ;)
      -

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

      +

      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).

      -

      Being able to rollback changes at a system level is cool. Package broke something? Just nixos-rebuild switch --rollback! Deleted nix by mistake? Find the binary in /nix/store and rollback! You aren’t punished for not thinking twice.

      -

      I don’t see myself switching to anything else in the near future, NixOS does a lot of things right. If I ever need to reinstall NixOS, I can generate an image of my current system.

      -

      +

      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).

      +

      Being able to rollback changes at a system level is cool. Package +broke something? Just nixos-rebuild switch --rollback! +Deleted nix by mistake? Find the binary in +/nix/store and rollback! You aren’t punished for not +thinking twice.

      +

      I don’t see myself switching to anything else in the near future, +NixOS does a lot of things right. If I ever need to reinstall NixOS, I +can generate an image of my +current system.

      +

      diff --git a/docs/posts/novice_nix:_flake_templates/index.html b/docs/posts/novice_nix:_flake_templates/index.html index 480f85d..302bafe 100644 --- a/docs/posts/novice_nix:_flake_templates/index.html +++ b/docs/posts/novice_nix:_flake_templates/index.html @@ -42,13 +42,25 @@ Novice Nix: Flake Templates
      -

      Flakes are very handy to setup entirely pure, project-specific dependencies (not just dependencies, but build steps, shell environments and more) in a declarative way. Writing Flake expressions can get repetitive though, oftentimes, you’d much rather start off with a skeleton. Luckily, nix already supports templates!

      -

      You might already be familiar with nix flake init, that drops a “default” flake expression into your current working directory. If you head over to the manpage:

      -
      nix flake init --help
      -

      You will read that nix flake init creates a flake using the “default template”. Additionally, you can create a flake from a specific template by passing the -t flag. Where does this default originate from?

      +

      Flakes are very handy to setup entirely pure, project-specific +dependencies (not just dependencies, but build steps, shell environments +and more) in a declarative way. Writing Flake expressions can get +repetitive though, oftentimes, you’d much rather start off with a +skeleton. Luckily, nix already supports templates!

      +

      You might already be familiar with nix flake init, that +drops a “default” flake expression into your current working directory. +If you head over to the manpage:

      +
      nix flake init --help
      +

      You will read that nix flake init creates a flake using +the “default template”. Additionally, you can create a flake from a +specific template by passing the -t flag. Where does this +default originate from?

      Flake Registries

      -

      Quick detour into registries! Registries are a way to alias popular flakes using identifiers:

      -
      # list a few predefined registries
      +

      Quick detour into registries! Registries are a way to alias popular +flakes using identifiers:

      +
      # list a few predefined registries
       $ nix registry list
       . . . 
       global flake:nixpkgs github:NixOS/nixpkgs
      @@ -66,8 +78,11 @@
       
       # which is short for
       $ nix flake show git+https://github.com/tweag/nickel
      -

      You might notice a registry called templates aliased to github:NixOS/templates. Take a peek with nix flake show:

      -
      $ nix flake show templates
      +

      You might notice a registry called templates aliased to +github:NixOS/templates. Take a peek with +nix flake show:

      +
      $ nix flake show templates
       github:NixOS/templates/79f48a7b822f35c068c5e235da2e9fbd154cecee
       ├───defaultTemplate: template: A very basic flake
       └───templates
      @@ -76,8 +91,12 @@
           ├───rust-web-server: template: A Rust web server including a NixOS module
           ├───simpleContainer: template: A NixOS container running apache-httpd
           └───trivial: template: A very basic flake
      -

      Aha! There is a flake output called defaultTemplate. This is the template being sourced when you run nix flake init. Astute readers may conclude the following:

      -
      $ nix flake init
      +

      Aha! There is a flake output called defaultTemplate. +This is the template being sourced when you run +nix flake init. Astute readers may conclude the +following:

      +
      $ nix flake init
       
       # is equivalent to
       $ nix flake init -t templates#defaultTemplate
      @@ -88,7 +107,8 @@
       # which is short for
       $ nix flake init -t git+https://github.com/NixOS/templates#defaultTemplate

      Similarly, the other templates can be accessed via:

      -
      $ nix flake init -t templates#c-hello
      +
      $ nix flake init -t templates#c-hello
       $ nix flake init -t templates#simpleContainer
       # I think you get the drift ...

      Rolling your own templates

      @@ -96,38 +116,52 @@
      • create a flake with a templates output
      • populate our template directories with content
      • -
      • (optionally) alias our custom templates flake to an identifier using registries, for easier access
      • +
      • (optionally) alias our custom templates flake to an +identifier using registries, for easier access
      -

      Start off by creating a directory to store your templates in (we will be converting this to a registry later):

      -
      $ mkdir ~/mytemplates
      -

      A flake that exposes a “template” as its output looks something like this:

      -
      # inside ~/mytemplates/flake.nix
      +

      Start off by creating a directory to store your templates in (we will +be converting this to a registry later):

      +
      $ mkdir ~/mytemplates
      +

      A flake that exposes a “template” as its output looks something like +this:

      +
      # inside ~/mytemplates/flake.nix
       
      -{
      -  description = "Pepper's flake templates";
      +{
      +  description = "Pepper's flake templates";
       
      -  outputs = { self, ... }: {
      -    templates = {
      -      latex-report = {
      -        path = ./latex-report-template;
      -        description = "A latex whitepaper project";
      -      };
      -      rust-hello = {
      -        path = ./rust-hello-template;
      -        description = "Simple Hello World in Rust";
      -      };
      -    };
      -  };
      -}
      -

      The path attribute to each template is what gets copied over when you initialize a flake. Running nix flake init -t .#latex-report will initialize the current directory with the contents of ./latex-report-template (we are yet to populate these directories).

      -

      The output of nix flake show should be something like:

      -
      $ nix flake show
      +  outputs = { self, ... }: {
      +    templates = {
      +      latex-report = {
      +        path = ./latex-report-template;
      +        description = "A latex whitepaper project";
      +      };
      +      rust-hello = {
      +        path = ./rust-hello-template;
      +        description = "Simple Hello World in Rust";
      +      };
      +    };
      +  };
      +}
      +

      The path attribute to each template is what gets copied +over when you initialize a flake. Running +nix flake init -t .#latex-report will initialize the +current directory with the contents of +./latex-report-template (we are yet to populate these +directories).

      +

      The output of nix flake show should be something +like:

      +
      $ nix flake show
       path:/home/np/code/nix-stuff/template-tests?narHash=sha256-{...}
       └───templates
           ├───latex-report: template: A latex whitepaper project
           └───rust-hello: template: Simple Hello World in Rust
      -

      Populate your template directories with content, here are my template directories for example:

      -
      $ tree mytemplates
      +

      Populate your template directories with content, here are my template +directories for example:

      +
      $ tree mytemplates
       mytemplates/
       ├── flake.nix
       ├── latex-report-template
      @@ -142,15 +176,18 @@
           └── src
               └── main.rs

      And that’s it! Start using your templates with:

      -
      $ nix flake init -t ~/mytemplates#rust-hello
      +
      $ nix flake init -t ~/mytemplates#rust-hello
       $ tree .
       .
       ├── Cargo.toml
       ├── flake.nix
       └── src
           └── main.rs
      -

      To avoid writing ~/mytemplates each time, simply alias it to a registry:

      -
      # alias it to `biscuits`
      +

      To avoid writing ~/mytemplates each time, simply alias +it to a registry:

      +
      # alias it to `biscuits`
       $ nix registry add biscuits ~/mytemplates
       
       # you will see it listed under `user` registries
      @@ -160,34 +197,42 @@
       . . .
       
       $ nix flake init -t biscuits#latex-report
      -

      Extending the official templates

      -

      I personally, would like the biscuits registry to include not just my homemade templates, but also the templates from NixOS/templates (and maybe a couple of other repositories in the wild):

      -
       {
      -   description = "Pepper's flake templates";
      +

      Extending the official +templates

      +

      I personally, would like the biscuits registry to +include not just my homemade templates, but also the templates from +NixOS/templates (and maybe a couple of other repositories +in the wild):

      +
       {
      +   description = "Pepper's flake templates";
        
      -+  inputs = {
      -+    official-templates.url = github:NixOS/templates;
      -+    other-templates.url = github:some-other/templates;
      -+  };
      ++  inputs = {
      ++    official-templates.url = github:NixOS/templates;
      ++    other-templates.url = github:some-other/templates;
      ++  };
        
      -   outputs = { self, official-templates, other-templates ... }: {
      +   outputs = { self, official-templates, other-templates ... }: {
        
      -     templates = {
      -       latex-report = {
      -         path = ./latex-report-template;
      -         description = "A latex whitepaper project";
      -       };
      -       rust-hello = {
      -         path = ./rust-hello-template;
      -         description = "Simple Hello World in Rust, with overloaded Rust toolchain";
      -       };
      -     }
      -+    // official-templates.templates
      -+    // other-templates.templates;
      +     templates = {
      +       latex-report = {
      +         path = ./latex-report-template;
      +         description = "A latex whitepaper project";
      +       };
      +       rust-hello = {
      +         path = ./rust-hello-template;
      +         description = "Simple Hello World in Rust, with overloaded Rust toolchain";
      +       };
      +     }
      ++    // official-templates.templates
      ++    // other-templates.templates;
        
      -   };
      - }
      -

      Running nix flake show biscuits will now list templates from the biscuits registry as well as the ones from NixOS/templates. Ensure that the names don’t collide though.

      + }; + }
      +

      Running nix flake show biscuits will now list templates +from the biscuits registry as well as the ones from +NixOS/templates. Ensure that the names don’t collide +though.

      diff --git a/docs/posts/onivim_sucks/index.html b/docs/posts/onivim_sucks/index.html index 0f10018..23bbedc 100644 --- a/docs/posts/onivim_sucks/index.html +++ b/docs/posts/onivim_sucks/index.html @@ -28,7 +28,7 @@ 02/08 — 2019
      - 11.18 + 11.19 cm   @@ -42,11 +42,38 @@ Onivim Sucks
      -

      Onivim is a ‘modern modal editor’, combining fancy interface and language features with vim-style modal editing. What’s wrong you ask?

      -

      Apart from buggy syntax highlighting, broken scrolling and others, Onivim is proprietary software. It is licensed under a commercial end user agreement license, which prohibits redistribution in both object code and source code formats.

      -

      Onivim’s core editor logic (bits that belong to vim), have been separated from the interface, into libvim. libvim is licensed under MIT, which means, this ‘extension’ of vim is perfectly in adherence to vim’s license text! Outrun Labs are exploiting this loophole (distributing vim as a library) to commercialize Onivim.

      -

      Onivim’s source code is available on GitHub. They do mention that the source code trickles down to the oni2-mit repository, which (not yet) contains MIT-licensed code, 18 months after each commit to the original repository.

      -

      Want to contribute to Onivim? Don’t. They make a profit out of your contributions. Currently, Onivim is priced at $19.99, ‘pre-alpha’ pricing which is 80% off the final price! If you are on the lookout for an editor, I would suggest using Vim, charity ware that actually works, and costs $100 lesser.

      +

      Onivim is a ‘modern modal editor’, +combining fancy interface and language features with vim-style modal +editing. What’s wrong you ask?

      +

      Apart from buggy +syntax highlighting, broken scrolling +and others, +Onivim is proprietary software. It is licensed under a +commercial end +user agreement license, which prohibits redistribution in both +object code and source code formats.

      +

      Onivim’s core editor logic (bits that belong to vim), have been +separated from the interface, into libvim. libvim is licensed +under MIT, which means, this ‘extension’ of vim is perfectly in +adherence to vim’s +license text! Outrun Labs are exploiting this loophole (distributing +vim as a library) to commercialize Onivim.

      +

      Onivim’s source code is available on GitHub. They do mention that +the source code trickles down to the oni2-mit repository, which +(not yet) contains MIT-licensed code, 18 months after +each commit to the original repository.

      +

      Want to contribute to Onivim? Don’t. They make a profit out of your +contributions. Currently, Onivim is priced at $19.99, ‘pre-alpha’ +pricing which is 80% off the final price! If you are on the lookout for +an editor, I would suggest using Vim, +charity ware that actually works, and costs $100 lesser.

      diff --git a/docs/posts/pixel_art_in_GIMP/index.html b/docs/posts/pixel_art_in_GIMP/index.html index a095961..a9cc1b4 100644 --- a/docs/posts/pixel_art_in_GIMP/index.html +++ b/docs/posts/pixel_art_in_GIMP/index.html @@ -28,7 +28,7 @@ 09/04 — 2020
      - 55.53 + 55.54 cm   @@ -42,54 +42,105 @@ Pixel Art In GIMP
      -

      I’ve always been an admirer of pixel art, because of it’s simplicity and it’s resemblance to bitmap font design. Recently, I decided to take the dive and make some art of my own.

      -

      I used GIMP because I am fairly familiar with it. Aseprite seems to be the editor of choice for animated pixel art though.

      +

      I’ve always been an admirer of pixel art, because of it’s simplicity +and it’s resemblance to bitmap font design. Recently, I decided to take +the dive and make some art of my own.

      +

      I used GIMP because I am fairly familiar with it. Aseprite seems to +be the editor of choice for animated pixel art though.

      Setting up the canvas

      -

      Picking a canvas size is daunting. Too small, and you won’t be able to fit in enough detail to make a legible piece. Too big and you’ve got too many pixels to work with!

      -

      I would suggest starting out with anywhere between 100x100 and 200x200. Here’s a sample configuration.

      -

      Sometimes I use a 10x10 grid, View > Show Grid and Edit > Preferences > Default Grid > Spacing, but that can get jarring, so I throw down a couple of guides, drag right or down from the left or top gutters for vertical and horizontal guides respectively.

      +

      Picking a canvas size is daunting. Too small, and you won’t be able +to fit in enough detail to make a legible piece. Too big and you’ve got +too many pixels to work with!

      +

      I would suggest starting out with anywhere between 100x100 and +200x200. Here’s a sample +configuration.

      +

      Sometimes I use a 10x10 grid, View > Show Grid and +Edit > Preferences > Default Grid > Spacing, but +that can get jarring, so I throw down a couple of guides, drag right or +down from the left or top gutters for vertical and horizontal guides +respectively.

      Choosing a Brush

      -

      The most important part of our setup is the brush. Use the Pencil Tool (n on the keyboard) for hard edge drawings. Here’s a small comparison if you don’t know the difference between a hard edge and a soft edge:

      +

      The most important part of our setup is the brush. Use the Pencil +Tool (n on the keyboard) for hard edge drawings. Here’s a +small comparison if you don’t know the difference between a hard edge +and a soft edge:

      -Hard edge vs Soft Edge +Hard edge vs Soft Edge +
      -

      I turn the size down all the way to 1 ([ on the keyboard). Set Dynamics off. Here’s a sample brush configuration.

      +

      I turn the size down all the way to 1 ([ on the +keyboard). Set Dynamics off. Here’s a sample brush +configuration.

      Laying down the pixels!

      -

      With the boring stuff out of the way, we can start with our piece. I usually follow a three step process:

      +

      With the boring stuff out of the way, we can start with our piece. I +usually follow a three step process:

      • draw a rough outline
      • fill in the shadows
      • add highlights
      -

      But this process is better explained with an example: an onigiri. Let us start off with a 100x100 canvas.

      +

      But this process is better explained with an example: an onigiri. Let +us start off with a 100x100 canvas.

      Drawing the outline

      -

      For the most part, our figure will be symmetric. If you are on GIMP 2.10+, you can take advantage of the Symmetry Painting feature. Go ahead and enable vertical symmetry, Window > Dockable Dialogs > Symmetry Painting and Symmetry Painting > Symmetry > Mirror > Vertical.

      -

      If you are running an older version of GIMP, draw in the left side, duplicate the layer, flip it horizontally, and merge it with the original.

      +

      For the most part, our figure will be symmetric. If you are on GIMP +2.10+, you can take advantage of the Symmetry Painting feature. Go ahead +and enable vertical symmetry, +Window > Dockable Dialogs > Symmetry Painting and +Symmetry Painting > Symmetry > Mirror > Vertical.

      +

      If you are running an older version of GIMP, draw in the left side, +duplicate the layer, flip it horizontally, and merge it with the +original.

      Your outline might look something like this:

      -

      Go ahead and fill it in with the fill tool (Shift + b on the keyboard), add in some seaweed as well, preferably on a different layer. You can toggle symmetry on and off to save yourself some time.

      +

      Go ahead and fill it in with the fill tool (Shift + b on +the keyboard), add in some seaweed as well, preferably on a different +layer. You can toggle symmetry on and off to save yourself some +time.

      Shadows

      -

      For now, let us focus on the shadows on the object itself, we’ll come back to the shadows cast by the object on the surface later.

      -

      Shadows on any surface always follow the shape of the surface. A spherical onigiri would have a circular shadow:

      +

      For now, let us focus on the shadows on the object itself, we’ll come +back to the shadows cast by the object on the surface later.

      +

      Shadows on any surface always follow the shape of the surface. A +spherical onigiri would have a circular shadow:

      A couple of noticeable changes:

      -

      Layers: The layer containing the seaweed has been hidden.
      -Color: The color of the shadow is just a slightly lighter version of the original object (reduce the Value on the HSV scale).
      -Area: The shadow does not go all the way (notice the bottom edges).

      -

      The shadow does not go all the way because we will be filling in that area with another, darker shadow! An image might explain better:

      +

      Layers: The layer containing the seaweed has been +hidden.
      +Color: The color of the shadow is just a slightly +lighter version of the original object (reduce the Value on the HSV +scale).
      +Area: The shadow does not go all the way (notice the +bottom edges).

      +

      The shadow does not go all the way because we will be filling in that +area with another, darker shadow! An image might explain better:

      -

      To emulate soft lights, reduce the value by 2 to 3 points every iteration. Notice how area 1 is much larger than area 4. This is because an onigiri resembles a bottom heavy oblate spheroid, a sphere that is slightly fatter around the lower bottom, and areas 1 and 2 catch more light than areas 3 and 4.

      -

      Do the same with the seaweed. The seaweed, being a smaller, flatter object, doesn’t cast much of a shadow, so stop with 1 or 2 iterations of the gradient:

      +

      To emulate soft lights, reduce the value by 2 to 3 points every +iteration. Notice how area 1 is much larger than area +4. This is because an onigiri resembles a bottom heavy +oblate spheroid, a sphere that is slightly fatter around the lower +bottom, and areas 1 and 2 catch more light +than areas 3 and 4.

      +

      Do the same with the seaweed. The seaweed, being a smaller, flatter +object, doesn’t cast much of a shadow, so stop with 1 or 2 iterations of +the gradient:

      We’re getting there!

      Highlights

      -

      This step handles the details on the strongly illuminated portions of the object. Seaweed is a bit glossy, lighten the edges to make it seem shiny. The rice is not as shiny, but it does form an uneven surface. Add in some shadows to promote the idea of rice grains. Here is the finished result:

      +

      This step handles the details on the strongly illuminated portions of +the object. Seaweed is a bit glossy, lighten the edges to make it seem +shiny. The rice is not as shiny, but it does form an uneven surface. Add +in some shadows to promote the idea of rice grains. Here is the finished +result:

      Finishing Touches

      -

      Some color correction and a e s t h e t i c Japanese text later, our piece is complete!

      +

      Some color correction and a e s t h e t i c Japanese +text later, our piece is complete!

      -

      Hold on, why is it so tiny? Well, that’s because our canvas was 100x100, head over to Image > Scale Image, set Quality > Interpolation to None and scale it up to 700x700, et voilà!

      +

      Hold on, why is it so tiny? Well, that’s because our canvas was +100x100, head over to Image > Scale Image, set +Quality > Interpolation to None and scale +it up to 700x700, et voilà!

      diff --git a/docs/posts/programming_on_34_keys/index.html b/docs/posts/programming_on_34_keys/index.html index 8667701..37ccfe6 100644 --- a/docs/posts/programming_on_34_keys/index.html +++ b/docs/posts/programming_on_34_keys/index.html @@ -28,7 +28,7 @@ 28/08 — 2022
      - 63.53 + 63.54 cm   @@ -42,79 +42,164 @@ Programming On 34 Keys
      -

      Minimizing your keyboard layout is a slippery slope. A few months ago, I built the Ferricy, a 34-key-split-ortho-ergo keyboard. The Ferricy is a fork of the Ferris Sweep MX Bling.

      +

      Minimizing your keyboard layout is a slippery slope. A few months +ago, I built the Ferricy, a +34-key-split-ortho-ergo keyboard. The Ferricy is a fork of the Ferris +Sweep MX Bling.

      -The Ferricy, designed by icyphox + +
      -

      My daily use consists of a bit of prose and a lot of program, my layout has evolved accordingly.

      +

      My daily use consists of a bit of prose and a lot of program, my +layout has evolved accordingly.

      Base Layer

      -Colemak with no mods +Colemak with no mods +
      -

      The base layer contains alphabets, four symbols and four whitespace keys:

      +

      The base layer contains alphabets, four symbols and four whitespace +keys:

      • Alphas: Stock Colemak, with no modifications whatsoever
      • Symbols: . , / ;
      • Whitespace: tab, space, enter, backspace (from left to right)

      Layers

      -

      Keyboard input is complex and it is impossible to skirt around it. You can either use a keyboard with enough keys to supply all possible inputs (a mechanical burden), or you can use firmware to supply all possible inputs (a cognitive burden). Layers are a cognitive burden.

      -

      I use 3 layers, heavily inspired by Miryoku, but tuned for programming. Excluding the base Colemak layer:

      +

      Keyboard input is complex and it is impossible to skirt around it. +You can either use a keyboard with enough keys to supply all possible +inputs (a mechanical burden), or you can use firmware to supply all +possible inputs (a cognitive burden). Layers are a cognitive burden.

      +

      I use 3 layers, heavily inspired by Miryoku, but tuned +for programming. Excluding the base Colemak layer:

        -
      • NAV: activated on holding space (left thumb)
      • -
      • NUM: activated on holding tab (left thumb)
      • -
      • SYM: activated on holding enter (right thumb)
      • +
      • NAV: activated on holding space (left +thumb)
      • +
      • NUM: activated on holding tab (left +thumb)
      • +
      • SYM: activated on holding enter (right +thumb)

      The NAV Layer

      -

      As the name suggests, this layer is focused on navigation. Arrow keys and the likes.

      +

      As the name suggests, this layer is focused on navigation. Arrow keys +and the likes.

      -NAV, on holding space +NAV, on holding space +
      -

      Using Vim and Colemak means you lose out on HJKL navigation. However, on activating the NAV layer, the right home-row is converted into arrow keys. In essence, by holding space, I can navigate Vim with the home-row, or Firefox, or my PDF reader. I no longer need to look for software that allows Vim navigation keys, because it is baked into the firmware!

      -

      My Vim motions are not limited to HJKL. In fact, my Vim motions are rarely HJKL. I tend to use } (next paragraph) and ) (next sentence) more often. As a result, these have found their way into my NAV layer, over the likes of PgDown and End. Having brackets at my index and middle fingers is nice for programming too.

      +

      Using Vim and Colemak means you lose out on HJKL navigation. However, +on activating the NAV layer, the right home-row is +converted into arrow keys. In essence, by holding space, I can navigate +Vim with the home-row, or Firefox, or my PDF reader. I no longer need to +look for software that allows Vim navigation keys, because it is baked +into the firmware!

      +

      My Vim motions are not limited to HJKL. In fact, my Vim motions are +rarely HJKL. I tend to use } (next paragraph) and +) (next sentence) more often. As a result, these have found +their way into my NAV layer, over the likes of +PgDown and End. Having brackets at my index +and middle fingers is nice for programming too.

      The SYM Layer

      -SYM, on holding enter +SYM, on holding enter +
      -

      This layer contains all the symbols that you would find by hitting Shift and a key on the number row. Probably noteworthy to Vim users: the symbols are arranged in the form of a mirrored numpad for exactly one reason: to move $ to the left of ^. It has always annoyed me that $ moves the cursor to the end of the line and ^ moves it to the beginning, but their position on a typical number row are reversed, 4 comes before 6.

      +

      This layer contains all the symbols that you would find by hitting +Shift and a key on the number row. Probably noteworthy to +Vim users: the symbols are arranged in the form of a mirrored numpad for +exactly one reason: to move $ to the left of +^. It has always annoyed me that $ moves the +cursor to the end of the line and ^ moves it to the +beginning, but their position on a typical number row are reversed, 4 +comes before 6.

      The NUM layer

      -NUM, on holding tab +NUM, on holding tab +
      -

      Another deviation from Miryoku, the numpad just feels right on my right hand.

      +

      Another deviation from Miryoku, the numpad just feels right +on my right hand.

      ZMK Combos

      -

      If you have been paying close attention, you might have noticed that escape didn’t make it to any layer. escape is too crucial to put on a non-base layer, but at the same time, not as important to deserve a place on the base layer. That is where ZMK’s combos come in. Combos let you tap any number of keys, and combine them to form a single key. I have combos set up for underscore, minus, escape and caps-word (more on caps-word later):

      +

      If you have been paying close attention, you might have noticed that +escape didn’t make it to any layer. escape is +too crucial to put on a non-base layer, but at the same time, not as +important to deserve a place on the base layer. That is where ZMK’s +combos come in. Combos let you tap any number of keys, and combine them +to form a single key. I have combos set up for underscore, minus, escape +and caps-word (more on caps-word later):

      -Combos are almost piano-like + +

      Home-row Mods

      -

      Inherited from Miryoku, I have home-row mods for activating Super, Alt, Shift, Ctrl and Hyper (Ctrl + Shift + Alt + Super). The idea is to send T on tap and Ctrl on hold. Home-row mods are fairly popular, so I’ll not go into the details.

      +

      Inherited from Miryoku, I have home-row mods for activating +Super, Alt, Shift, +Ctrl and Hyper +(Ctrl + Shift + Alt + Super). The idea is to send +T on tap and Ctrl on hold. Home-row mods are +fairly popular, so I’ll not go into the details.

      -Super, Alt, Shift, Ctrl, Hyper; on the left half, and mirrored on the right half + +
      -

      Hyper bridges the gap between firmware and software. You can never configure key combination that, opens Firefox, for example, through firmware alone. However, with the Hyper key, and some sxhkd magic, you can emulate that. Pressing Hyper + F on a keyboard is just two keys, but the key codes sent are Ctrl + Shift + Alt + Super + F. That key combination is not intercepted by any application as a shortcut, except for the following sxhkd stanza:

      -
      super + alt + shift + ctrl + f
      +

      Hyper bridges the gap between firmware and software. You +can never configure key combination that, opens Firefox, for example, +through firmware alone. However, with the Hyper key, and +some sxhkd magic, you can emulate that. Pressing +Hyper + F on a keyboard is just two keys, but the key codes +sent are Ctrl + Shift + Alt + Super + F. That key +combination is not intercepted by any application as a shortcut, except +for the following sxhkd stanza:

      +
      super + alt + shift + ctrl + f
         xdotool search "Mozilla Firefox" windowactivate
      -

      Alternatively, you can intercept unused F keys: F13 through F24.

      -

      Home-row mods are mirrored on each half because it would be impossible to hit Ctrl + T if not; they lie on the same key.

      +

      Alternatively, you can intercept unused F keys: +F13 through F24.

      +

      Home-row mods are mirrored on each half because it would be +impossible to hit Ctrl + T if not; they lie on the same +key.

      Caps-word

      -

      Caps-word is a clever caps-lock, built into ZMK. Typing out constants such as PORT with home-row mods would look like this:

      +

      Caps-word is a clever caps-lock, built into ZMK. Typing out constants +such as PORT with home-row mods would look like this:

        -
      • hold e (shift) on left hand, and tap p on right hand
      • -
      • hold e (shift) on left hand, and tap o on right hand
      • -
      • hold s (shift) on right hand, and tap r on left hand
      • -
      • hold s (shift) on right hand, and tap t on left hand
      • +
      • hold e (shift) on left hand, and tap p on +right hand
      • +
      • hold e (shift) on left hand, and tap o on +right hand
      • +
      • hold s (shift) on right hand, and tap r on +left hand
      • +
      • hold s (shift) on right hand, and tap t on +left hand
      -

      This hold-alternate-hold dance gets tiring quickly. With caps-word, however:

      +

      This hold-alternate-hold dance gets tiring quickly. With caps-word, +however:

      • toggle caps_word
      • -
      • type out p, o, r, t
      • +
      • type out p, o, r, +t
      • hit a break character (space, enter will do)
      • continue
      -

      Caps-word automatically disables capitalization upon encountering a breaking character, (which are space, enter or any modifier, by default) right in the firmware!

      +

      Caps-word automatically disables capitalization upon encountering a +breaking character, (which are space, enter or any modifier, by default) +right in the firmware!

      Findings

      -

      34-keys has been reasonably comfortable to use, for both prose and program. My palms do not move across the desk at all, as I reach for keys. I mostly write Rust and Bash, and my layout has evolved to accomodate special characters from their grammars (angled brackets and hyphens, specifically). If you are on a similar journey, I would suggest focusing on accuracy and comfort over speed. Speed comes with time.

      +

      34-keys has been reasonably comfortable to use, for both prose and +program. My palms do not move across the desk at all, as I reach for +keys. I mostly write Rust and Bash, and my layout has evolved to +accomodate special characters from their grammars (angled brackets and +hyphens, specifically). If you are on a similar journey, I would suggest +focusing on accuracy and comfort over speed. Speed comes with time.

      diff --git a/docs/posts/rapid_refactoring_with_vim/index.html b/docs/posts/rapid_refactoring_with_vim/index.html index 3d867a3..e240da7 100644 --- a/docs/posts/rapid_refactoring_with_vim/index.html +++ b/docs/posts/rapid_refactoring_with_vim/index.html @@ -42,9 +42,14 @@ Rapid Refactoring With Vim
      -

      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};
      +            

      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() {
      @@ -54,7 +59,8 @@
               );
         }

      had to be converted to:

      -
      use serde_json::{from_value};
      +
      use serde_json::{from_value};
         
         #[test]
         fn deserialize() {
      @@ -64,19 +70,38 @@
               );
         }

      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
      +

      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
      -

      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:

      +

      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

      The quickfix list

      -

      Next up, replacing r#" ... "# with json!( ... ). I couldn’t search and replace that trivially, so I went with a macro call 2 instead, starting with the cursor on ‘r’, represented by the caret, in my attempt to breakdown the process:

      +

      Next up, replacing r#" ... "# with +json!( ... ). I couldn’t search and replace that trivially, +so I went with a macro call 2 instead, starting with +the cursor on ‘r’, represented by the caret, in my attempt to breakdown +the process:

      BUFFER:    r#" ... "#;
                  ^
       
      @@ -93,42 +118,80 @@ BUFFER:    json!( ... "#;
       ACTION:    vhs)<esc>
       
       BUFFER:    json!( ... );
      -

      Here’s the recorded 3 macro in all its glory: vllsjson!(<esc>$F#vhs)<esc>.

      -

      Great! So now we just go ahead, find every occurrence of r# and apply the macro right? Unfortunately, there were more than a few occurrences of raw strings that had to stay raw strings. Enter, the quickfix list.

      -

      The idea behind the quickfix list is to jump from one position in a file to another (maybe in a different file), much like how the arglist lets you jump from one file to another.

      -

      One of the easiest ways to populate this list with a bunch of positions is to use vimgrep:

      +

      Here’s the recorded 3 macro in all its glory: +vllsjson!(<esc>$F#vhs)<esc>.

      +

      Great! So now we just go ahead, find every occurrence of +r# and apply the macro right? Unfortunately, there were +more than a few occurrences of raw strings that had to stay raw strings. +Enter, the quickfix list.

      +

      The idea behind the quickfix list is to jump from one position in a +file to another (maybe in a different file), much like how the arglist +lets you jump from one file to another.

      +

      One of the easiest ways to populate this list with a bunch of +positions is to use vimgrep:

      # basic usage
       :vimgrep pattern files
       
       # search for raw strings
       :vimgrep 'r#' ./**/*.rs
      -

      Like :next and :prev, you can navigate the quickfix list with :cnext and :cprev. Every time you move up or down the list, vim indicates your index:

      +

      Like :next and :prev, you can navigate the +quickfix list with :cnext and :cprev. Every +time you move up or down the list, vim indicates your index:

      (1 of 131): r#"{"set_tweak": "highlight"}"#;
      -

      And just like argdo, you can cdo to apply commands to every match in the quickfix list:

      +

      And just like argdo, you can cdo to apply +commands to every match in the quickfix list:

      :cdo norm! @q
      -

      But, I had to manually pick out matches, and it involved some button mashing.

      +

      But, I had to manually pick out matches, and it involved some button +mashing.

      External Filtering

      -

      Some code reviews later, I was asked to format all the json inside the json! macro. All you have to do is pass a visual selection through a pretty json printer. Select the range to be formatted in visual mode, and hit :, you will notice the command line displaying what seems to be gibberish:

      +

      Some code reviews later, I was asked to format all the json inside +the json! macro. All you have to do is pass a visual +selection through a pretty json printer. Select the range to be +formatted in visual mode, and hit :, you will notice the +command line displaying what seems to be gibberish:

      :'<,'>
      -

      '< and '> are marks 4. More specifically, they are marks that vim sets automatically every time you make a visual selection, denoting the start and end of the selection.

      -

      A range is one or more line specifiers separated by a ,:

      +

      '< and '> are marks 4. More specifically, they are marks +that vim sets automatically every time you make a visual selection, +denoting the start and end of the selection.

      +

      A range is one or more line specifiers separated by a +,:

      :1,7       lines 1 through 7
       :32        just line 32
       :.         the current line
       :.,$       the current line to the last line
       :'a,'b     mark 'a' to mark 'b'
      -

      Most : commands can be prefixed by ranges. :help usr_10.txt for more on that.

      -

      Alright, lets pass json through python -m json.tool, a json formatter that accepts stdin (note the use of ! to make use of an external program):

      +

      Most : commands can be prefixed by ranges. +:help usr_10.txt for more on that.

      +

      Alright, lets pass json through python -m json.tool, a +json formatter that accepts stdin (note the use of +! to make use of an external program):

      :'<,'>!python -m json.tool
      -

      Unfortunately that didn’t quite work for me because the range included some non-json text as well, a mix of regex and macros helped fix that. I think you get the drift.

      -

      Another fun filter I use from time to time is :!sort, to sort css attributes, or :!uniq to remove repeated imports.

      -
      +

      Unfortunately that didn’t quite work for me because the range +included some non-json text as well, a mix of regex and macros helped +fix that. I think you get the drift.

      +

      Another fun filter I use from time to time is :!sort, to +sort css attributes, or :!uniq to remove repeated +imports.

      +

        -
      1. https://github.com/tpope/vim-unimpaired It also handles various other mappings, ]q and [q to navigate the quickfix list for example↩︎

      2. -
      3. :help recording↩︎

      4. -
      5. When I’m recording a macro, I prefer starting out by storing it in register q, and then copying it over to another register if it works as intended. I think of qq as ‘quick record’.↩︎

      6. -
      7. :help mark-motions↩︎

      8. +
      9. https://github.com/tpope/vim-unimpaired It also handles +various other mappings, ]q and [q to navigate +the quickfix list for example↩︎

      10. +
      11. :help recording↩︎

      12. +
      13. When I’m recording a macro, I prefer starting out by +storing it in register q, and then copying it over to +another register if it works as intended. I think of qq as +‘quick record’.↩︎

      14. +
      15. :help mark-motions↩︎

      diff --git a/docs/posts/self-hosting_git/index.html b/docs/posts/self-hosting_git/index.html index f41a591..d927e95 100644 --- a/docs/posts/self-hosting_git/index.html +++ b/docs/posts/self-hosting_git/index.html @@ -28,7 +28,7 @@ 17/10 — 2020
      - 87.90 + 87.91 cm   @@ -42,11 +42,21 @@ Self-hosting Git
      -

      Earlier this week, I began migrating my repositories from Github to cgit. If you care at all about big corporates turning open-source into a T-shirt farming service, this is the way to go.

      +

      Earlier this week, I began migrating my repositories from Github to +cgit. If you care at all +about big corporates turning open-source into a T-shirt farming service, +this is the way to go.

      Offerings

      -

      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.

      +

      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:

      +

      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
      @@ -55,9 +65,16 @@
       # 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.

      +

      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,

      +

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

      sudo apt install fcgiwrap
       sudo systemctl start fcgiwrap.socket

      Expose the cgit cgi script to the web via nginx:

      @@ -81,15 +98,21 @@ server {

      Point cgit to your git repositories:

      # /etc/cgitrc
       scan-path=/path/to/git/repos
      -

      Note: scan-path works best if you stick it at the end of your cgitrc.

      -

      You may now create remote repositories at /path/to/git/repos, via:

      +

      Note: scan-path works best +if you stick it at the end of your cgitrc.

      +

      You may now create remote repositories at +/path/to/git/repos, via:

      git init --bare

      Add the remote to your local repository:

      git remote set-url origin user@remote:/above/path
       git push origin master

      Configuration

      -

      cgit is fairly easy to configure, all configuration options can be found in the manual, here are a couple of cool ones though:

      -

      enable-commit-graph: Generates a text based graphical representation of the commit history, similar to git log --graph --oneline.

      +

      cgit is fairly easy to configure, all configuration options can be +found in the +manual, here are a couple of cool ones though:

      +

      enable-commit-graph: Generates a text based +graphical representation of the commit history, similar to +git log --graph --oneline.

      | * |    Add support for configuration file
       * | |    simplify command parsing logic
       * | |    Refactor parsers
      @@ -110,7 +133,11 @@ git push origin master
      | | * | Merge branch 'fix/duplicate-habits' | | |\ \ | | | * | move duplicate check to command parsing blo...
      -

      section-from-path: This option paired with scan-path will automatically generate sections in your cgit index page, from the path to each repo. For example, the directory structure used to generate sections on my cgit instance looks like this:

      +

      section-from-path: This option paired with +scan-path will automatically generate sections in your cgit +index page, from the path to each repo. For example, the directory +structure used to generate sections on my +cgit instance looks like this:

      ├── cli
       │   ├── dijo
       │   ├── eva
      @@ -134,11 +161,18 @@ git push origin master
      └── web └── isostatic

      Ease of use

      -

      As I mentioned before, cgit is simply a view into your git repositories, you will have to manually create new repositories by entering your remote and using git init --bare. Here are a couple of scripts I wrote to perform actions on remotes, think of it as a smaller version of Github’s gh program.

      -

      You may save these scripts as git-script-name and drop them in your $PATH, and git will automatically add an alias called script-name, callable via:

      +

      As I mentioned before, cgit is simply a view into your +git repositories, you will have to manually create new repositories by +entering your remote and using git init --bare. Here are a +couple of scripts I wrote to perform actions on remotes, think of it as +a smaller version of Github’s gh program.

      +

      You may save these scripts as git-script-name and drop +them in your $PATH, and git will automatically add an alias +called script-name, callable via:

      git script-name

      git-new-repo

      -

      Creates a new repository on your remote, the first arg may be a path (section/repo-name) or just the repo name:

      +

      Creates a new repository on your remote, the first arg may be a path +(section/repo-name) or just the repo name:

      #! /usr/bin/env bash
       #
       # usage:
      @@ -155,7 +189,10 @@ fi
       
       ssh user@remote git init --bare "$1";

      git-set-desc

      -

      To set a one line repository description. It simply copies the local .git/description, into remote/description. cgit displays the contents of this file on the index page:

      +

      To set a one line repository description. It simply copies the local +.git/description, into remote/description. +cgit displays the contents of this file on the index +page:

      #! /usr/bin/env bash
       #
       # usage:
      diff --git a/docs/posts/static_sites_with_bash/index.html b/docs/posts/static_sites_with_bash/index.html
      index 07313be..6921529 100644
      --- a/docs/posts/static_sites_with_bash/index.html
      +++ b/docs/posts/static_sites_with_bash/index.html
      @@ -28,7 +28,7 @@
                   23/11 — 2019
                   
      - 21.17 + 21.18 cm   @@ -42,12 +42,22 @@ Static Sites With Bash
      -

      After going through a bunch of static site generators (pelican, hugo, vite), I decided to roll my own. If you are more of the ‘show me the code’ kinda guy, here you go.

      +

      After going through a bunch of static site generators (pelican, hugo, vite), I decided to roll my +own. If you are more of the ‘show me the code’ kinda guy, here you go.

      Text formatting

      -

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

      +

      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!
      +

      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"
      @@ -56,19 +66,27 @@
           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
      +

      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=$( 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!

      +

      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!

      diff --git a/docs/posts/termux_tandem/index.html b/docs/posts/termux_tandem/index.html index 9f2e708..71c4731 100644 --- a/docs/posts/termux_tandem/index.html +++ b/docs/posts/termux_tandem/index.html @@ -28,7 +28,7 @@ 08/03 — 2020
      - 19.17 + 19.18 cm   @@ -42,24 +42,39 @@ Termux Tandem
      -

      I learnt about termux from a friend on IRC recently. It looked super gimmicky to me at first, but it eventually proved to be useful. Here’s what I use it for:

      +

      I learnt about termux from a friend on IRC recently. It +looked super gimmicky to me at first, but it eventually proved to be +useful. Here’s what I use it for:

      rsync

      -

      Ever since I degoogled my android device, syncing files between my phone and my PC has always been a pain. I’m looking at you MTP. But, with termux and sshd all set up, it’s as simple as:

      +

      Ever since I degoogled my android device, syncing files between my +phone and my PC has always been a pain. I’m looking at you MTP. But, +with termux and sshd all set up, it’s as +simple as:

      $ arp
       Address         HWtype  HWad ...
       192.168.43.187  ether   d0:0 ...
       
       $ rsync -avz 192.168.43.187:~/frogs ~/pics/frogs

      ssh & tmux

      -

      My phone doubles as a secondary view into my main machine with ssh and tmux. When I am away from my PC (read: sitting across the room), I check build status and IRC messages by sshing into a tmux session running the said build or weechat.

      +

      My phone doubles as a secondary view into my main machine with +ssh and tmux. When I am away from my PC (read: +sitting across the room), I check build status and IRC messages by +sshing into a tmux session running the said build or +weechat.

      file uploads

      -

      Not being able to access my (ssh-only) file host was crippling. With a bash instance on my phone, I just copied over my ssh keys, and popped in a file upload script (a glorified scp). Now I just have to figure out a way to clean up these file names …

      +

      Not being able to access my (ssh-only) file host was crippling. With +a bash instance on my phone, I just copied over my ssh +keys, and popped in a file upload script (a glorified scp). +Now I just have to figure out a way to clean up these file names …

      ~/storage/pictures/ $ ls
       02muf5g7b2i41.jpg  7alt3cwg77841.jpg  cl4bsrge7id11.png
       mtZabXG.jpg        p8d5c584f2841.jpg  vjUxGjq.jpg

      cmus

      -

      Alright, I don’t really listen to music via cmus, but I did use it a couple times when my default music player was acting up. cmus is a viable option:

      -

      +

      Alright, I don’t really listen to music via cmus, but I +did use it a couple times when my default music player was acting up. +cmus is a viable option:

      +

      diff --git a/docs/posts/turing_complete_type_systems/index.html b/docs/posts/turing_complete_type_systems/index.html index 1f6fd4c..2a9361e 100644 --- a/docs/posts/turing_complete_type_systems/index.html +++ b/docs/posts/turing_complete_type_systems/index.html @@ -28,7 +28,7 @@ 18/06 — 2020
      - 9.18 + 9.19 cm   @@ -44,12 +44,26 @@

      Rust’s type system is Turing complete:

      -

      It is impossible to determine if a program written in a generally Turing complete system will ever stop. That is, it is impossible to write a program f that determines if a program g, where g is written in a Turing complete programming language, will ever halt. The Halting Problem is in fact, an undecidable problem.

      +

      It is impossible to determine if a program written in a generally +Turing complete system will ever stop. That is, it is impossible to +write a program f that determines if a program +g, where g is written in a Turing complete +programming language, will ever halt. The Halting Problem +is in fact, an undecidable +problem.

      How is any of this relevant?

      -

      Rust performs compile-time type inference. The type checker, in turn, compiles and infers types, I would describe it as a compiler inside a compiler. It is possible that rustc may never finish compiling your Rust program! I lied, rustc stops after a while, after hitting the recursion limit.

      +

      Rust performs compile-time type inference. The type checker, in turn, +compiles and infers types, I would describe it as a compiler inside a +compiler. It is possible that rustc may never finish +compiling your Rust program! I lied, rustc stops after a +while, after hitting the recursion limit.

      I understand that this post lacks content.

      -- cgit v1.2.3