From fb61d3d063555a9183fab0ec78bb0f4c3cbf0e82 Mon Sep 17 00:00:00 2001 From: Akshay Date: Wed, 26 Jan 2022 18:26:32 +0530 Subject: new post: Lightweight Linting --- docs/index.html | 16 +- docs/index.xml | 229 ++++++++++++++++ docs/posts/index.html | 17 ++ docs/posts/lightweight_linting/index.html | 298 +++++++++++++++++++++ docs/style.css | 6 + posts/lightweight_linting.md | 427 ++++++++++++++++++++++++++++++ 6 files changed, 985 insertions(+), 8 deletions(-) create mode 100644 docs/posts/lightweight_linting/index.html create mode 100644 posts/lightweight_linting.md diff --git a/docs/index.html b/docs/index.html index 4993863..89b04d4 100644 --- a/docs/index.html +++ b/docs/index.html @@ -42,15 +42,15 @@
- 05/10 — 2021 + 26/01 — 2022
- - Novice Nix: Flake Templates + + Lightweight Linting - 5.5 + 8.5 min @@ -59,15 +59,15 @@
- 11/04 — 2021 + 05/10 — 2021
- - SDL2 Devlog + + Novice Nix: Flake Templates - 10.0 + 5.5 min diff --git a/docs/index.xml b/docs/index.xml index b0ca956..c2ba3ca 100644 --- a/docs/index.xml +++ b/docs/index.xml @@ -12,6 +12,235 @@ en-us Creative Commons BY-NC-SA 4.0 +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> +<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> +<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> +<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> +<span id="cb2-5"><a href="#cb2-5" aria-hidden="true" tabindex="-1"></a> body: </span> +<span id="cb2-6"><a href="#cb2-6" aria-hidden="true" tabindex="-1"></a> (block</span> +<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> +<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> +<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> +<span id="cb4-5"><a href="#cb4-5" aria-hidden="true" tabindex="-1"></a> body:</span> +<span id="cb4-6"><a href="#cb4-6" aria-hidden="true" tabindex="-1"></a> (block</span> +<span id="cb4-7"><a href="#cb4-7" aria-hidden="true" tabindex="-1"></a><span class="op">+</span> (line_comment)</span> +<span id="cb4-8"><a href="#cb4-8" aria-hidden="true" tabindex="-1"></a> (let_declaration</span> +<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> +<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> +<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> +<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> +<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> +<span id="cb8-5"><a href="#cb8-5" aria-hidden="true" tabindex="-1"></a><span class="co">; matches:</span></span> +<span id="cb8-6"><a href="#cb8-6" aria-hidden="true" tabindex="-1"></a><span class="co">; let foo = 2;</span></span> +<span id="cb8-7"><a href="#cb8-7" aria-hidden="true" tabindex="-1"></a></span> +<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> +<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> +<span id="cb9-5"><a href="#cb9-5" aria-hidden="true" tabindex="-1"></a> </span> +<span id="cb9-6"><a href="#cb9-6" aria-hidden="true" tabindex="-1"></a><span class="co">; matches:</span></span> +<span id="cb9-7"><a href="#cb9-7" aria-hidden="true" tabindex="-1"></a><span class="co">; let foo = 2;</span></span> +<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> +<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> +<span id="cb10-5"><a href="#cb10-5" aria-hidden="true" tabindex="-1"></a> </span> +<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> +<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> +<span id="cb11-5"><a href="#cb11-5" aria-hidden="true" tabindex="-1"></a><span class="co">; matches:</span></span> +<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> +<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> +<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> +<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>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> +<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> +<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> +<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> +<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> +<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> +<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> +<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> +<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> +<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>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> +<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> +<span id="cb27-5"><a href="#cb27-5" aria-hidden="true" tabindex="-1"></a> <span class="st">r#&quot;</span></span> +<span id="cb27-6"><a href="#cb27-6" aria-hidden="true" tabindex="-1"></a><span class="st"> ((call_expression</span></span> +<span id="cb27-7"><a href="#cb27-7" aria-hidden="true" tabindex="-1"></a><span class="st"> function: (_) @fn-name</span></span> +<span id="cb27-8"><a href="#cb27-8" aria-hidden="true" tabindex="-1"></a><span class="st"> arguments: (arguments (string_literal))) @raise</span></span> +<span id="cb27-9"><a href="#cb27-9" aria-hidden="true" tabindex="-1"></a><span class="st"> (#match? @fn-name &quot;(std::|)env::(var|remove_var)&quot;))</span></span> +<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> +<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> +<span id="cb28-5"><a href="#cb28-5" aria-hidden="true" tabindex="-1"></a> <span class="op">&amp;</span>query<span class="op">,</span></span> +<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>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> +<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-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-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> +<span id="cb29-11"><a href="#cb29-11" aria-hidden="true" tabindex="-1"></a> <span class="op">{</span></span> +<span id="cb29-12"><a href="#cb29-12" aria-hidden="true" tabindex="-1"></a> <span class="kw">let</span> range <span class="op">=</span> capture<span class="op">.</span>node<span class="op">.</span>range()<span class="op">;</span></span> +<span id="cb29-13"><a href="#cb29-13" aria-hidden="true" tabindex="-1"></a> <span class="kw">let</span> text <span class="op">=</span> <span class="op">&amp;</span>src[range<span class="op">.</span>start_byte<span class="op">..</span>range<span class="op">.</span>end_byte]<span class="op">;</span></span> +<span id="cb29-14"><a href="#cb29-14" aria-hidden="true" tabindex="-1"></a> <span class="kw">let</span> line <span class="op">=</span> range<span class="op">.</span>start_point<span class="op">.</span>row<span class="op">;</span></span> +<span id="cb29-15"><a href="#cb29-15" aria-hidden="true" tabindex="-1"></a> <span class="kw">let</span> col <span class="op">=</span> range<span class="op">.</span>start_point<span class="op">.</span>column<span class="op">;</span></span> +<span id="cb29-16"><a href="#cb29-16" aria-hidden="true" tabindex="-1"></a> <span class="pp">println!</span>(</span> +<span id="cb29-17"><a href="#cb29-17" aria-hidden="true" tabindex="-1"></a> <span class="st">&quot;[Line: {}, Col: {}] Offending source code: `{}`&quot;</span><span class="op">,</span></span> +<span id="cb29-18"><a href="#cb29-18" aria-hidden="true" tabindex="-1"></a> line<span class="op">,</span> col<span class="op">,</span> text</span> +<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>And <code>cargo run</code>:</p> +<pre class="shell"><code>λ cargo run + Compiling toy-lint v0.1.0 (/redacted/path/to/toy-lint) + Finished dev [unoptimized + debuginfo] target(s) in 0.74s + Running `target/debug/toy-lint` +[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> +<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> +<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> +<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> +https://peppe.rs/posts/lightweight_linting/ +Wed, 26 Jan 2022 12:52:00 +0000 +https://peppe.rs/posts/lightweight_linting/ + + 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> diff --git a/docs/posts/index.html b/docs/posts/index.html index d15342d..68d5d60 100644 --- a/docs/posts/index.html +++ b/docs/posts/index.html @@ -24,6 +24,23 @@
+ + + + +
+
+ 26/01 — 2022 +
+ + Lightweight Linting + +
+ + 8.5 + + min +
diff --git a/docs/posts/lightweight_linting/index.html b/docs/posts/lightweight_linting/index.html new file mode 100644 index 0000000..9bc84f2 --- /dev/null +++ b/docs/posts/lightweight_linting/index.html @@ -0,0 +1,298 @@ + + + + + + + + + + + + + + + Lightweight Linting · peppe.rs + +
+
+ Home + / + Posts + / + Lightweight Linting + View Raw +
+
+ 26/01 — 2022 +
+ + 170.62 + + cm +   + + 8.5 + + min +
+
+

+ 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 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() {
+    let x = 2;
+}
+

would be:

+
(source_file
+ (function_item
+  name: (identifier)
+  parameters: (parameters)
+  body: 
+  (block
+   (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() {
++    // 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
+  (function_item
+   name: (identifier)
+   parameters: (parameters)
+   body:
+   (block
++   (line_comment)
+    (let_declaration
+     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)
+
+; 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"
+; 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
+ pattern: (identifier)
+ value: (integer_literal))
+ 
+; matches:
+; let foo = 2;
+

We can capture nodes into variables:

+
(let_declaration 
+ pattern: (identifier) @my-capture
+ value: (integer_literal))
+ 
+; matches:
+; let foo = 2;
+
+; captures:
+; foo
+

And apply certain predicates to captures:

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

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

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

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

+
(let_declaration
+ pattern: (identifier)
+ value: (_))
+ 
+; matches:
+; 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.

+

Write you a tree-sitter lint

+

Strings in std::env functions are error prone:

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

I prefer this instead:

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

Produces the following S-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
+  function: (_) @fn-name) @raise
+ (#match? @fn-name "std::env::(var|remove_var)"))
+

Let’s turn that std:: prefix optional:

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

And ensure that arguments is a string:

+
((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
+[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 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;
+
+let rust_lang: Language = tree_sitter_rust::language();
+

Enough scaffolding, let’s parse some Rust:

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

Or better yet, run a query on it:

+
use tree_sitter::Query;
+
+let query = Query::new(
+    rust_lang,
+    r#"
+    ((call_expression
+      function: (_) @fn-name
+      arguments: (arguments (string_literal))) @raise
+     (#match? @fn-name "(std::|)env::(var|remove_var)"))
+    "#
+)
+.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;
+
+let mut query_cursor = QueryCursor::new();
+let all_matches = query_cursor.matches(
+    &query,
+    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?.

+

Do something with the matches:

+
// get the index of the capture named "raise"
+let raise_idx = query.capture_index_for_name("raise").unwrap();
+
+for each_match in all_matches {
+    // iterate over all captures called "raise"
+    // ignore captures such as "fn-name"
+    for capture in each_match
+        .captures
+        .iter()
+        .filter(|c| c.idx == raise_idx)
+    {
+        let range = capture.node.range();
+        let text = &src[range.start_byte..range.end_byte];
+        let line = range.start_point.row;
+        let col = range.start_point.column;
+        println!(
+            "[Line: {}, Col: {}] Offending source code: `{}`",
+            line, col, text
+        );
+    }
+}
+

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)
+    Finished dev [unoptimized + debuginfo] target(s) in 0.74s
+     Running `target/debug/toy-lint`
+[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
+  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!
+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
+  name: (identifier) @fn
+  !parameters)
+ (#is? @fn "to_json"))
+ +
+ +
+ Hi. + +

I'm Akshay, I go by nerd or nerdypepper on the internet.

+

+ I am a compsci undergrad, Rust programmer and an enthusiastic Vimmer. + I write open-source stuff to pass time. + I also design fonts: + scientifica, + curie. +

+

Send me a mail at nerdy@peppe.rs or a message at nerdypepper@irc.rizon.net.

+
+ + Home + / + Posts + / + Lightweight Linting + View Raw +
+
+ + diff --git a/docs/style.css b/docs/style.css index 133b193..5767d9f 100644 --- a/docs/style.css +++ b/docs/style.css @@ -390,3 +390,9 @@ ul { box-shadow: none; } +blockquote { + margin: 0; + padding-left: 0.8rem; + border-left: 2px solid var(--dark-white); +} + diff --git a/posts/lightweight_linting.md b/posts/lightweight_linting.md new file mode 100644 index 0000000..2436f30 --- /dev/null +++ b/posts/lightweight_linting.md @@ -0,0 +1,427 @@ +[Tree-sitter](https://tree-sitter.github.io/tree-sitter/using-parsers#pattern-matching-with-queries) +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, + +```rust +fn main() { + let x = 2; +} +``` + +would be: + +```scheme +(source_file + (function_item + name: (identifier) + parameters: (parameters) + body: + (block + (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: + +```rust + 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: + +```scheme + (source_file + (function_item + name: (identifier) + parameters: (parameters) + body: + (block ++ (line_comment) + (let_declaration + 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: + +```scheme +(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](https://tree-sitter.github.io/tree-sitter/playground). +Type in a query like so: + +```scheme +; 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: + +```scheme +(let_declaration + pattern: (identifier) + value: (integer_literal)) + +; matches: +; let foo = 2; +``` + +We can _capture_ nodes into variables: + +```scheme +(let_declaration + pattern: (identifier) @my-capture + value: (integer_literal)) + +; matches: +; let foo = 2; + +; captures: +; foo +``` + +And apply certain _predicates_ to captures: + +```scheme +((let_declaration + pattern: (identifier) @my-capture + value: (integer_literal)) + (#eq? @my-capture "foo")) + +; matches: +; let foo = 2; + +; and not: +; let bar = 2; +``` + +The `#match?` predicate checks if a capture matches a regex: + +```scheme +((let_declaration + pattern: (identifier) @my-capture + value: (integer_literal)) + (#match? @my-capture "foo|bar")) + +; matches both `foo` and `bar`: +; let foo = 2; +; let bar = 2; +``` + +Exhibit indifference, as a stoic programmer would, with the +_wildcard_ pattern: + +```scheme +(let_declaration + pattern: (identifier) + value: (_)) + +; matches: +; let foo = "foo"; +; let foo = 42; +; let foo = bar; +``` + +[The +documentation](https://tree-sitter.github.io/tree-sitter/using-parsers#pattern-matching-with-queries) +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: + +```rust +std::env::remove_var("RUST_BACKTACE"); + // ^^^^ "TACE" instead of "TRACE" +``` + +I prefer this instead: + +```rust +// 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: + +```rust +remove_var("RUST_BACKTRACE") +``` + +Produces the following S-expression: + +```scheme +(call_expression + function: (identifier) + arguments: (arguments (string_literal))) +``` + +We are definitely looking for a `call_expression`: + +```scheme +(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): + +```scheme +((call_expression + function: (_) @fn-name) @raise + (#match? @fn-name "std::env::(var|remove_var)")) +``` + +Let's turn that `std::` prefix optional: + +```scheme +((call_expression + function: (_) @fn-name) @raise + (#match? @fn-name "(std::|)env::(var|remove_var)")) +``` + +And ensure that `arguments` is a string: + +```scheme +((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: + +```bash +cargo new --bin toy-lint +``` + +Add `tree-sitter` and `tree-sitter-rust` to your +dependencies: + +```toml +# 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](https://en.wikipedia.org/wiki/Self-reference) +(G`ode`l?), why not load in our linter itself: + +```rust +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: + +```rust +use tree_sitter::Language; + +let rust_lang: Language = tree_sitter_rust::language(); +``` + +Enough scaffolding, let's parse some Rust: + +```rust +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: + +```rust +// 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!](http://github.com/dtolnay/anyhow)), now that we have a parse tree, we can inspect it: + +```rust +println!("{}", parse_tree.root_node().to_sexp()); +``` + +Or better yet, run a query on it: + +```rust +use tree_sitter::Query; + +let query = Query::new( + rust_lang, + r#" + ((call_expression + function: (_) @fn-name + arguments: (arguments (string_literal))) @raise + (#match? @fn-name "(std::|)env::(var|remove_var)")) + "# +) +.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: + +```rust +use tree_sitter::QueryCursor; + +let mut query_cursor = QueryCursor::new(); +let all_matches = query_cursor.matches( + &query, + 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?`. + +Do something with the matches: + +```rust +// get the index of the capture named "raise" +let raise_idx = query.capture_index_for_name("raise").unwrap(); + +for each_match in all_matches { + // iterate over all captures called "raise" + // ignore captures such as "fn-name" + for capture in each_match + .captures + .iter() + .filter(|c| c.idx == raise_idx) + { + let range = capture.node.range(); + let text = &src[range.start_byte..range.end_byte]; + let line = range.start_point.row; + let col = range.start_point.column; + println!( + "[Line: {}, Col: {}] Offending source code: `{}`", + line, col, text + ); + } +} +``` + +Lastly, add the following line to your source code, to get +the linter to catch something: + +```rust +env::remove_var("RUST_BACKTRACE"); +``` + +And `cargo run`: + +```shell +λ cargo run + Compiling toy-lint v0.1.0 (/redacted/path/to/toy-lint) + Finished dev [unoptimized + debuginfo] target(s) in 0.74s + Running `target/debug/toy-lint` +[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: + +```scheme +((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_literal`s who are siblings or exactly one +`string_literal` with no siblings. Unfortunately, this query +also matches the following invalid Rust code: + +```rust +// 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: + +```scheme +((method + name: (identifier) @fn + !parameters) + (#is? @fn "to_json")) +``` -- cgit v1.2.3