<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/">
  <channel>
    <title>ARNΛV — All editions</title>
    <link>https://blog.15.134.14.153.sslip.io/feed.xml</link>
    <description>Every dispatch from the Devlog and the Journal.</description>
    <language>en</language>
    <lastBuildDate>Mon, 02 Nov 2026 16:24:54 +0530</lastBuildDate>
    <atom:link href="https://blog.15.134.14.153.sslip.io/feed.xml" rel="self" type="application/rss+xml"/>
    
    <item>
      <title>A parser in Reverse</title>
      <link>https://blog.15.134.14.153.sslip.io/devlog/a-parser-in-reverse</link>
      <guid isPermaLink="true">https://blog.15.134.14.153.sslip.io/devlog/a-parser-in-reverse</guid>
      <pubDate>Wed, 28 Oct 2026 09:22:00 +0000</pubDate>
      <description>Devlog following the need and creation of an infinite structurally correct code generator from first principles.</description>
      <content:encoded><![CDATA[<p>What do you call a reverse parser?
Speed-typing, the “peaceful and relaxing” sport that breaks keyboard when you cannot get in that damn flow is actually very fun. If you haven’t tried it, good for you but basically you go onto websites like monkeytype and it presents you with words and as you start typing it times you on your words per minute so you have to type as fast as you can minimizing errors.
<span class="md-figure"><img src="https://blog.15.134.14.153.sslip.io/media/20261028-143751-image-0bff49.png" alt="pasted image" loading="lazy" decoding="async"></span>
I wanted to make a similar website, but for coders, where instead of typing through these random snippets, you type through code. I even have a working prototype..Its a WIP. You open it up, choose any language and it presents you with a snippet to type and we time you on that…simple.</p>
<p><span class="md-figure"><img src="https://blog.15.134.14.153.sslip.io/media/20261028-143830-image-53a639.png" alt="pasted image" loading="lazy" decoding="async"></span></p>
<h1 id="the-problem">The Problem?</h1>
<p>These snippets themselves. for monkeytype, its easy, you can just paste random english words with variations and you got a good singleplayer experience. But we cannot just throw in random tokens and call it a day. Sure the code does not have to compile but it also cannot be nonsensical. If the person chooses Golang, the snippet should resemble golang.</p>
<p>So what do we do? We really have two options.</p>
<ul>
<li>Make a database with snippets of each language and randomly pick one and send it there, can work but again its not elegant and would be taxing on the server if someone wants to just practice on the singleplayer which will be most of the real usecase for it.</li>
<li>Generate code on the client’s device on the fly, and this had so many advantages. The real backend server won’t be bothered as much and its bandwidth wont be piled up with sending code everywhere. And the app would be very snappy.</li>
</ul>
<p><strong>And that is why, I made Resrap, the reverse parser.</strong></p>
<h2 id="but-what-is-a-parser">But what is a Parser?</h2>
<p>Traditional Parsers take the “grammar” of the programming language, which contains all the rules to write syntactically correct code and using it validates the given code for its structure and reports syntax errors. It is a step while interpreting or compiling languages. What Resrap does, it reverses the parser’s role. It takes the Grammar and itself generates a syntactically correct snippet from it.</p>
<p>It is a substep in interpreting or compiling the code. We start off with Scanning or Tokenizing. A token (Not in LLM terms ffs) is the smallest piece of a language like</p>
<div class="code-block" data-lang=""><pre class="chroma"><code>a=b+c
</code></pre><button class="code-copy" type="button" aria-label="Copy code">Copy</button></div><p>Here a,=,b,+,c and ; all are tokens.</p>
<p>So we first define what all type of tokens there are in a language, and scan through its text to get a list of the tokens.</p>
<p>Parsing comes right next to that step. We take the tokens and generate a Abstract Syntax Tree from it of the code. Then if you are making an interpreter you simply start at the leaf nodes and start collapsing the AST to run the code, a classic Tree Walking Interpreter or You could be making a compiler which is way more complex or a Just in Time compiler which are just legendary. ANYWAYS back to parsing.</p>
<p><span class="md-figure"><img src="https://blog.15.134.14.153.sslip.io/media/20261028-144016-image-404cd5.png" alt="pasted image" loading="lazy" decoding="async"></span></p>
<h1 id="grammar-lesson">Grammar Lesson</h1>
<p>There is this one major difference between English and Java, every statement of the latter is deterministic. That is it always means the same thing. It won’t change what it does with change in context. And this level of precision has pushed us to develop grammars for languages. I learnt about from this book “Crafting Interpreters” you can check them out <a href="https://craftinginterpreters.com/">https://craftinginterpreters.com/</a></p>
<p><span class="md-figure"><img src="https://blog.15.134.14.153.sslip.io/media/20261028-144052-image-2e45d7.png" alt="pasted image" loading="lazy" decoding="async"></span>
Back to Grammar. So, one of the most successful grammars for defining programming languages has been BNF. It will become obvious with a simple example</p>
<div class="code-block" data-lang=""><pre class="chroma"><code>&lt;sentence&gt; ::= &lt;noun&gt; &lt;verb&gt; &lt;object&gt;
&lt;noun&gt; ::= Sam | Ali | Rohan
&lt;verb&gt; ::= ate | fought | saw
&lt;object&gt; ::= the robot | the food
</code></pre><button class="code-copy" type="button" aria-label="Copy code">Copy</button></div><p>We are just breaking down the structure and specifying what is a valid order for them. In the example, a sentence is made of noun verb and object. The noun further can be defined as being proper or not and the definitions can go till you have reached the simplest forms. More info about at Computerphile.
But obviously BNF is very verbose so modern iterations like EBNF came over it to make it more readable, introducing more operators.</p>
<div class="code-block" data-lang=""><pre class="chroma"><code>+ -&gt; One or More
program: function+ 
Means a program is made with one or more functions
* -&gt; Zero or More
function: statements*
Means A function is made with zero or more statements
? -&gt; One or None
function: statement* return?
A function is made of one of more statements and it may or may not have a return
</code></pre><button class="code-copy" type="button" aria-label="Copy code">Copy</button></div><p>Lets right a (minimal) C grammar with it It’ll all make sense.</p>
<div class="code-block" data-lang=""><pre class="chroma"><code>program :  function+;
function:functionheader'{''\n'functioncontent'}';
functionheader:datatype ' ' identifier '(' ')' ;
functioncontent:block+;
block:(statement+) | ifblock | whileblock ;
ifblock: 'if(' conditionalexpression '){\n' statement+ '}\n';
whileblock :'while(' conditionalexpression '){\n' statement+ '}\n';
conditionalexpression: conditionalexpone (conditionaljoin conditionalexpone)*;
conditionalexpone: (identifier conditionaloperation operand);
conditionaloperation: ' &lt; ' | ' &gt; ';
conditionaljoin: ' &amp;&amp; ' | ' || ';
statement:assignment;
assignment: datatype ' ' identifier ' = ' expression ';\n';
expression: operand (operator (operand | '(' expression ')'))*;
operand: identifier | integer | float;
operator : ' + ' | ' - ' | ' * ' | ' / ';
datatype: 'int'|'float'|'double';
identifier: (A|a|B|b)+;
integer:(0|1|2|3|4|5)+;
whitespace: ' ';
</code></pre><button class="code-copy" type="button" aria-label="Copy code">Copy</button></div><p>Great now that we are on the same page, lets think</p>
<h2 id="how-do-we-generate-from-this-grammar">How do we generate from this grammar?</h2>
<p>My first guess? Make it a graph I mean it literally looks like it is waiting to be converted to a graph! and that is exactly what I did in my first trial. Converting it to a simple graph and just walking it randomly. Just Connect what it needs to go next to and…</p>
<p><span class="md-figure"><img src="https://blog.15.134.14.153.sslip.io/media/20261028-144225-image-43be80.png" alt="pasted image" loading="lazy" decoding="async"></span>
Then I was shot 50 times cuz that needed a lot of “state management” and was not a good idea. The problem was that if I am randomly walking, I would have to keep managing where I came from, and where to go from there. For example if I am in “Statement” node, I have no idea where on earth did I come from and what all came before. This would just get worse when we have to generate nested blocks and stuff so we totally could not do that.</p>
<p>To add to our troubles, the special operators like <code>+</code> would over-complicate it tenfold.</p>
<p>Plus we also had to code a recursion free solution since I wanted a more performant solution and easier on the RAM.</p>
<h3 id="wrapping-every-node">Wrapping every Node</h3>
<p>If you look closely at the grammar, it has the special characters +,.* etc and then apart from that there are two main nodes,</p>
<div class="code-block" data-lang=""><pre class="chroma"><code>functionheader:datatype ' ' identifier '(' ')' ;
</code></pre><button class="code-copy" type="button" aria-label="Copy code">Copy</button></div><p>Here, identifier will invoke the identifier: … statement
And ‘{‘ will print something</p>
<p>We take them and wrap them up, with two empty nodes in out graph
Lets ignore everything else right now and look into this structure. It makes applying the operators to the graphs super easy just see.</p>
<p><span class="md-figure"><img src="https://blog.15.134.14.153.sslip.io/media/20261028-144320-image-122ee6.png" alt="pasted image" loading="lazy" decoding="async"></span></p>
<h2 id="state-of-the-operators">State of The Operators</h2>
<p><span class="md-figure"><img src="https://blog.15.134.14.153.sslip.io/media/20261028-144342-image-015474.png" alt="pasted image" loading="lazy" decoding="async"></span></p>
<p><span class="md-figure"><img src="https://blog.15.134.14.153.sslip.io/media/20261028-144402-image-3e1ecf.png" alt="pasted image" loading="lazy" decoding="async"></span></p>
<p><span class="md-figure"><img src="https://blog.15.134.14.153.sslip.io/media/20261028-144412-image-8bd16d.png" alt="pasted image" loading="lazy" decoding="async"></span></p>
<h3 id="how-a-whole-statement-would-play-out">How a whole statement would play out</h3>
<p><span class="md-figure"><img src="https://blog.15.134.14.153.sslip.io/media/20261028-144426-image-0637ad.png" alt="pasted image" loading="lazy" decoding="async"></span>
Now, we can simply iterate through this mini graph randomly we have made for each statement and it would print things out perfectly</p>
<p>Now we make these mini graphs for each statement. A different one for each and can save them in a map just like:</p>
<p><span class="md-figure"><img src="https://blog.15.134.14.153.sslip.io/media/20261028-144448-image-7d5f08.png" alt="pasted image" loading="lazy" decoding="async"></span>
All we need to do is figure out a way if a node references statement1 how do jump and track out last position and make it work.</p>
<h2 id="the-stack">The Stack</h2>
<p>So now we have a map of graphs we need to iterate through it. For single statement it works, generating that specific sequence perfectly, however we still need a state management for cases like such:</p>
<p><span class="md-figure"><img src="https://blog.15.134.14.153.sslip.io/media/20261028-144516-image-0c807a.png" alt="pasted image" loading="lazy" decoding="async"></span>
The graph starts at A, then it needs to go to abra, and safely return back to A again. For this, we just use the trusty stack. A simple integer stack whenever you need to jump to a different statement, you will save the id of that node’s inter in the stack. Then the flow can switch to the other graph. And it can happen any number of times, since each jump is only filling a single integer in the stack, we can have practically endlessly deep references. Then when you hit the end node of any statement, you check the stack for what is the top value. You then shift back the control to the top value from the stack and pop that. Simple and elegant</p>
<p><span class="md-figure"><img src="https://blog.15.134.14.153.sslip.io/media/20261028-144531-image-e579f3.png" alt="pasted image" loading="lazy" decoding="async"></span></p>
<h2 id="placing-the-seed">Placing the Seed</h2>
<p>This structure can generate code randomly at this point. But lets remember the original problem. It will work just fine with the OSDType interface you provide the grammar and get back a random script that too very fast. But what if you want to play multiplayer. Two players are to be given the same snippet to see who writes that the fastest. How do we build that!?</p>
<p>This is where Pseudo Random Numbers (PRN) help us. We set up a “Seed” initially which is something you would be familiar if you have played minecraft before.</p>
<p><span class="md-figure"><img src="https://blog.15.134.14.153.sslip.io/media/20261028-144601-image-8f9ee8.png" alt="pasted image" loading="lazy" decoding="async"></span>
When you first load a Minecraft world, it generates everything you see the biomes, the villages the mountains everything right there. It appears random but is not. All the random numbers needed in its generation are sourced from a single number, the seed. If like a huge integer code in minecraft. If you want the same world loaded into you as a friend or as a youtuber, you would get their world’s seed and enter that. While generating, now all the random numbers used in generation of the world will be same for everyone using the seed.</p>
<p>See: <a href="https://minecraft.wiki/w/World_generation">https://minecraft.wiki/w/World_generation</a></p>
<p><em>123 -&gt; 432 -&gt; 5435 -&gt; 4123 -&gt; 901
We start from a seed, here its 123 and genrate anay number of random numbers from it</em></p>
<p>Hence its called Pseudo Random Number Generation. These values are seemingly random, but they are sourced from a single Seed.</p>
<p>Similarly, when I say I am walking the graph inside Resrap, I am not randomly going. I am using PRNG to get values where to go. If the user sets no seed, it picks a random seed, if we get a seed while generation, then the snippet generated will always be identical.</p>
<p>Now think about it, in a multiplayer typing contest where there are a thousand players playing simultaneously say, the server only needs to forward on 64 bit integer to every player and it would automatically be converted to full on snippets on everyone’’s devices. No load on the server at all, and an amazing snappy experience for all the users.</p>
<h2 id="inventing-new-operators">Inventing New Operators</h2>
<p>EBNF is amazing but the specific needs of a language generation needs some more operators in order to generate realistic snippets.</p>
<h3 id="making-it-truly-infinite">Making it truly infinite</h3>
<p>We cannot specify how many tokens it will generate. Sure we can specify a max cap to generate after which we can stop the program, but its not guaranteed to reach that specific number, it can go through the graph and reach the end and check the stack and there would be nowhere to go. The program will just stop then. If you want a million tokens you literally cannot.</p>
<p>Hence introducing the infinity operator tadaa:
<code>program : functions^</code>
This specifies that program is made of infinite functions. Hence, whenever we reach the end of a statement, and the stack is empty, then we jump to the function node. So now we can generate absurdly long pieces of code, in benchmarks I have gone well over 50 million tokens in a single run.</p>
<h3 id="the-regex-er">The Regex-er</h3>
<p>We need random numbers and strings to be generated, and to make that less tiresome, I added a “syntax sugar”. Here you can define a simple regex of the code you want to generate and it will generate those. More work needs to be done to make it more adaptable, but it can generate simple identifiers like variable names and all.</p>
<div class="code-block" data-lang=""><pre class="chroma"><code>identifier: [a-z];
integer:[0-9];
</code></pre><button class="code-copy" type="button" aria-label="Copy code">Copy</button></div><p>To make them sound less random, we also have a bias function placed which gives a bias to all the numbers like e get highest then other common characters. This allows us to make normal sounding random words. Would probably add support for random real words if that does not cost us too much performance.</p>
<h3 id="cumulative-frequency-distribution-something-something">Cumulative Frequency Distribution something something</h3>
<p>The final one, and this is for the aesthetics of the code itself. In my code, I would prefer there be more normal block statements than if or while blocks in general . Or maybe there be a longer number of statements in a block before it exits.</p>
<p>For this we introduce the probability operator:</p>
<div class="code-block" data-lang=""><pre class="chroma"><code>block:(statement+)&lt;0.8&gt; | ifblock&lt;0.1&gt; | whileblock&lt;0.1&gt; ;
</code></pre><button class="code-copy" type="button" aria-label="Copy code">Copy</button></div><p><span class="md-figure"><img src="https://blog.15.134.14.153.sslip.io/media/20261028-144834-image-833d0d.png" alt="pasted image" loading="lazy" decoding="async"></span>
Underneath, after we have generated the graph, we call a Normalize function, which normalizes all the probabilities to 1. Where there are no probabilities, we add them to ensure a common structure throughout. So each edge has a probability. Now for a node A which has 3 next options to go to. we make a Cumulative Frequency Distribution, which is just an array where we add keep adding the last sum of frequencies. It should make the last value 1.</p>
<p>With this, all we need to do while iterating is generate a random number with prng and normalize it such that it lies below 0 and 1 (evenly). Now all we have to do is iterate through this array and find the first number that is larger than out generated number.</p>
<p>If we get 0.8 for example, then we pick C because its CF index reads 0.9.</p>
<p>We can optimize it even further but altering the position of the elements such that the one with the probabilities are in descending order such that we will usually find the solution in the earlier tries. Something like:</p>
<p><span class="md-figure"><img src="https://blog.15.134.14.153.sslip.io/media/20261028-144853-image-712188.png" alt="pasted image" loading="lazy" decoding="async"></span></p>
<p>So now 70 percent of the times we will get the value on the very first value of the structure.
And that is how we over engineer Random Code Generation</p>
<p>— &gt; Now we can generate infinitely nonsensical code very efficiently</p>
<h1 id="multi-threading-without-safety">Multi threading Without Safety</h1>
<p>If you have one data structure, and many threads accessing it, you need to introduce locks to avoid two threads accessing at once which may lead to race conditions. There is a classic “Readers Writers Problem” in CS which is that what to do when many threads which only read and other threads which also write are accessing the same data structure.</p>
<p>A common solution to this is when the data structure needs to be written to, it blocks everything, every other reader, writer etc. Others have to wait till they acquire the lock before proceeding. However, if a reader gets the lock, every other reader is allowed to access the data structure, and all writers are blocked. This way we can get a good throughput and not lock everyone all the time. Readers can have this selective read only lock.</p>
<p>In our codebase however, there are two distinct phases, One when the graph is being built, and the other when we iterate through it. This means we can have a writer stage in single threaded mode, and then we can literally freeze the ds from any further changes so multiple threads can in parallel access it increasing the throughput substantially. Thanks to this, we can convert the code to walk the graph in parallel once the graph is generated. So we do not need to implement locks and it can safely do that without them.</p>
<h2 id="contributing">Contributing</h2>
<p>I have made this an actual Golang (and rust) library with docs published. You can find more about this project at <a href="https://resrap.osdc.dev/">https://resrap.osdc.dev/</a>, it comes with documentation and a in browser tester running on a WASM engine.</p>
<p><span class="md-figure"><img src="https://blog.15.134.14.153.sslip.io/media/20261028-145011-image-54ab90.png" alt="pasted image" loading="lazy" decoding="async"></span></p>
]]></content:encoded>
    </item>
    
    <item>
      <title>Inventing a New Language</title>
      <link>https://blog.15.134.14.153.sslip.io/devlog/inventing-a-new-language</link>
      <guid isPermaLink="true">https://blog.15.134.14.153.sslip.io/devlog/inventing-a-new-language</guid>
      <pubDate>Wed, 28 Oct 2026 09:00:00 +0000</pubDate>
      <description>How Do We Run This File? Imagine we&#39;re handed a file with the following code: How on earth are we supposed to make sense of this string of text?! That&#39;s where an interpreter swoops in to save the day. The Job of an Interpreter The…</description>
      <content:encoded><![CDATA[<h1 id="how-do-we-run-this-file">How Do We Run This File?</h1>
<p>Imagine we&rsquo;re handed a file with the following code:</p>
<div class="code-block" data-lang=""><pre class="chroma"><code>let a = 2;
let b = a * 2;
console.log(&quot;The Solution is &quot;, b);
</code></pre><button class="code-copy" type="button" aria-label="Copy code">Copy</button></div><p>How on earth are we supposed to make sense of this string of text?!</p>
<p>That&rsquo;s where an interpreter swoops in to save the day.</p>
<h2 id="the-job-of-an-interpreter">The Job of an Interpreter</h2>
<p>The interpreter&rsquo;s main task is to turn this cryptic text into something meaningful that a computer can execute. How does it do that? By following 3 steps:</p>
<h3 id="step-1-scanning-and-tokenizing">Step 1: Scanning and Tokenizing</h3>
<p>The first thing we need to do is scan the text and break it into tokens. A token is the smallest meaningful piece of code. Think of it like the building blocks of the program:</p>
<ul>
<li>Keywords (e.g., <code>let</code>, <code>function</code>)</li>
<li>Literals (e.g., numbers like <code>2</code>, strings like <code>&quot;hello&quot;</code>)</li>
<li>Identifiers (e.g., variable names like <code>a</code>, <code>b</code>)</li>
<li>Operators (e.g., <code>=</code>, <code>*</code>)</li>
</ul>
<p>In any programming language, tokens usually have:</p>
<ul>
<li>A <strong>type</strong> (e.g., <code>IDENTIFIER</code>, <code>NUMBER_LITERAL</code>)</li>
<li>A <strong>value</strong>, if it holds one (e.g., <code>2</code> is a <code>NUMBER_LITERAL</code> with a value of <code>2</code>)</li>
</ul>
<p>For example:</p>
<div class="code-block" data-lang=""><pre class="chroma"><code>let -&gt; LET_KEYWORD
a   -&gt; IDENTIFIER   &quot;a&quot;
=   -&gt; EQUAL_SIGN   (no value, type says it all)
2   -&gt; NUMBER_LITERAL 2
...etc
</code></pre><button class="code-copy" type="button" aria-label="Copy code">Copy</button></div><p>This process of scanning and tokenizing is done by the <strong>Scanner</strong> (or <strong>Lexer</strong>), which transforms the raw code into a list of meaningful tokens.</p>
<p>For example:</p>
<p>Code: <code>let a = 2;</code></p>
<p>Tokens:</p>
<ol>
<li><code>{ type: LET_KEYWORD }</code></li>
<li><code>{ type: IDENTIFIER, value: &quot;a&quot; }</code></li>
<li><code>{ type: EQUAL_SIGN }</code></li>
<li><code>{ type: NUMBER_LITERAL, value: 2 }</code></li>
</ol>
<h3 id="step-2-parsing-the-text">Step 2: Parsing the Text</h3>
<p>Now that we have the list of tokens, we need to parse it. Parsing is all about making sense of it and converting it into an <strong>Abstract Syntax Tree (AST)</strong>.</p>
<p>But before diving into parsing, let&rsquo;s quickly recap how trees work in programming.</p>
<h4 id="what-is-a-tree-in-programming">What is a Tree in Programming?</h4>
<p>A tree is a special type of data structure that resembles a hierarchy. Think of it like a family tree or the folder structure on your computer.</p>
<p>Here&rsquo;s how it works:</p>
<ul>
<li>The topmost element is called the <strong>root</strong>.</li>
<li>Every item (called a <strong>node</strong>) can have <strong>children</strong> nodes branching out below it.</li>
<li>Nodes with no children are called <strong>leaves</strong>.</li>
<li>The connections between nodes are called <strong>edges</strong>.</li>
</ul>
<h4 id="key-features-of-trees">Key Features of Trees</h4>
<p><strong>Parent-Child Relationship:</strong>
Each node is connected to its parent and may have zero or more children. For example:</p>
<div class="code-block" data-lang=""><pre class="chroma"><code>     Root
     /  \
  Node1  Node2
   /       \
Leaf1     Leaf2
</code></pre><button class="code-copy" type="button" aria-label="Copy code">Copy</button></div><p><strong>Single Path Rule:</strong>
There is only one path between any two nodes, meaning no cycles! It&rsquo;s not a tree if you can loop back to the root.</p>
<p>Now, let&rsquo;s see how this logic is used to build an Abstract Syntax Tree (AST).</p>
<h4 id="quick-quiz-which-of-these-makes-sense">Quick Quiz: Which of These Makes Sense?</h4>
<div class="code-block" data-lang=""><pre class="chroma"><code>let a = 2 + 3;
let = a + 2 3;
</code></pre><button class="code-copy" type="button" aria-label="Copy code">Copy</button></div><p>The first one, right?</p>
<p>That&rsquo;s because the second one breaks the rules of grammar! Without proper grammar, we&rsquo;d all be speaking gibberish, and both humans and computers would have a hard time deciphering meaning.</p>
<h2 id="grammar">Grammar</h2>
<p>There are two basic terms in Parsing Grammar: <strong>Terminals</strong> and <strong>Non-Terminals</strong>. If you imagine a tree analogy, terminals are essentially the leaf nodes, while non-terminals are all the other nodes.</p>
<h3 id="example-1">Example 1</h3>
<p>Let&rsquo;s illustrate this with an example:</p>
<p>Consider:</p>
<div class="code-block" data-lang=""><pre class="chroma"><code>a = b + c
</code></pre><button class="code-copy" type="button" aria-label="Copy code">Copy</button></div><p>This is converted into a tree branch that looks like this:</p>
<div class="code-block" data-lang=""><pre class="chroma"><code>       =
     /  \
    a    +
        / \
       b   c
</code></pre><button class="code-copy" type="button" aria-label="Copy code">Copy</button></div><p>(Notice I&rsquo;m calling it a branch because it is part of a much larger tree representing the whole program. This is just a single statement within that tree)</p>
<p>Makes sense? We&rsquo;re breaking it down into a meaningful structure!</p>
<h4 id="explanation">Explanation</h4>
<ul>
<li><strong>Non-terminals</strong>: <code>=</code>, <code>+</code>
<ul>
<li>If these are present, it implies there should be something to the left, right, or both for the given statement to be grammatically correct.</li>
</ul>
</li>
<li><strong>Terminals</strong>: <code>a</code>, <code>b</code>, <code>c</code>
<ul>
<li>These are the leaf nodes and do not enforce any further structure.</li>
</ul>
</li>
</ul>
<h3 id="example-2">Example 2</h3>
<p>Let&rsquo;s enhance this logic with another example:</p>
<p>Consider:</p>
<div class="code-block" data-lang=""><pre class="chroma"><code>a = b + c * d
</code></pre><button class="code-copy" type="button" aria-label="Copy code">Copy</button></div><p>This converts into the following branch of the tree:</p>
<div class="code-block" data-lang=""><pre class="chroma"><code>       =
     /  \
     a    +
         / \
        b   *
           /  \
          c    d
</code></pre><button class="code-copy" type="button" aria-label="Copy code">Copy</button></div><p>Now it&rsquo;s even clearer:</p>
<ul>
<li><strong>Terminals</strong>: <code>a</code>, <code>b</code>, <code>c</code>, <code>d</code></li>
<li><strong>Non-terminals</strong>: <code>=</code>, <code>+</code>, <code>*</code></li>
</ul>
<h3 id="summary">Summary</h3>
<p>Operators (<code>=</code>, <code>+</code>, <code>*</code>) are non-terminals, as they structure the statement. Variables (<code>a</code>, <code>b</code>, <code>c</code>, <code>d</code>) are terminals, as they represent the final values.</p>
<p>Great! Now, how do we actually define the rules we need to play with?</p>
<h2 id="syntax-for-grammar">Syntax for Grammar</h2>
<p>There is a popular formal syntax for grammar called <strong>BNF</strong>. You can look it up — Computerphile has some amazing videos on it! However, I&rsquo;ll discuss a much simpler regex-like syntax as explained in the book <em>Crafting Interpreters</em>.</p>
<p>I don&rsquo;t want to overwhelm you with learning the entire thing, as there isn&rsquo;t much to it. Instead, let&rsquo;s construct our grammar for a language side by side.</p>
<h3 id="dummy-language-example">Dummy Language Example</h3>
<p>Here&rsquo;s a dummy language whose syntax we will build:</p>
<div class="code-block" data-lang=""><pre class="chroma"><code>void name{
a = 2 + 3;
b = 10 + 20;
}
</code></pre><button class="code-copy" type="button" aria-label="Copy code">Copy</button></div><p>This language has no arguments in functions for simplicity, avoiding messy string handling for now. Let&rsquo;s keep things clean!</p>
<h3 id="building-the-grammar">Building the Grammar</h3>
<p>Let&rsquo;s break down the hierarchy of components in our code and build the structure step by step.</p>
<h4 id="what-is-a-program-made-of">What is a program made of?</h4>
<p>A program is made of functions, which we can write in our syntax as:</p>
<div class="code-block" data-lang=""><pre class="chroma"><code>Program = Function+
</code></pre><button class="code-copy" type="button" aria-label="Copy code">Copy</button></div><ul>
<li><code>+</code> means 1 or more.</li>
<li>Similarly, <code>*</code> means 0 or more.</li>
<li>Since a program needs at least one function, we use <code>+</code>.</li>
</ul>
<h4 id="what-is-a-function">What is a function?</h4>
<div class="code-block" data-lang=""><pre class="chroma"><code>Function = header '{' body '}'
</code></pre><button class="code-copy" type="button" aria-label="Copy code">Copy</button></div><p>Here:</p>
<ul>
<li><strong>header</strong>: <code>void name</code></li>
<li><strong>body</strong>: The statements inside the curly braces.</li>
</ul>
<h4 id="defining-header-and-body">Defining Header and Body</h4>
<div class="code-block" data-lang=""><pre class="chroma"><code>header = DataType Identifier
body = Statement+
</code></pre><button class="code-copy" type="button" aria-label="Copy code">Copy</button></div><ul>
<li><strong>header</strong>: Contains a <code>DataType</code> and an <code>Identifier</code> in this order.</li>
<li><strong>body</strong>: Contains 1 or more statements.</li>
</ul>
<h4 id="defining-datatype-and-identifier">Defining DataType and Identifier</h4>
<div class="code-block" data-lang=""><pre class="chroma"><code>DataType = int | float | char | void
Identifier = (alphabet | _ ) (alphanumeric | _ )*
</code></pre><button class="code-copy" type="button" aria-label="Copy code">Copy</button></div><ul>
<li><code>|</code> means &ldquo;or&rdquo;.</li>
<li>A <code>DataType</code> can be any of the listed types.</li>
<li>An <code>Identifier</code> starts with an alphabet or an underscore, followed by any number of alphanumeric or underscore characters.</li>
</ul>
<p>The <code>*</code> here allows 0 or more characters after the first one.</p>
<h4 id="diagnosing-statements">Diagnosing Statements</h4>
<div class="code-block" data-lang=""><pre class="chroma"><code>Statement = identifier '=' expression;
</code></pre><button class="code-copy" type="button" aria-label="Copy code">Copy</button></div><h4 id="defining-an-expression">Defining an Expression</h4>
<p>For simplicity, let&rsquo;s say an expression consists of numbers, identifiers, and operators (<code>+</code>, <code>*</code>):</p>
<div class="code-block" data-lang=""><pre class="chroma"><code>expression = terminal | (expression operator expression)
operator = + | *
terminal = identifier | number
</code></pre><button class="code-copy" type="button" aria-label="Copy code">Copy</button></div><p>This definition is simple and elegant but lacks operator precedence rules, which are critical for order of operations (BODMAS).</p>
<h3 id="addressing-operator-precedence">Addressing Operator Precedence</h3>
<p><strong>Issue:</strong></p>
<p>Given an expression like:</p>
<div class="code-block" data-lang=""><pre class="chroma"><code>2 + 3 * 4
</code></pre><button class="code-copy" type="button" aria-label="Copy code">Copy</button></div><p>Our current grammar might parse it as:</p>
<div class="code-block" data-lang=""><pre class="chroma"><code>(2 + 3) * 4
</code></pre><button class="code-copy" type="button" aria-label="Copy code">Copy</button></div><p>Instead of the correct BODMAS evaluation:</p>
<div class="code-block" data-lang=""><pre class="chroma"><code>2 + (3 * 4)
</code></pre><button class="code-copy" type="button" aria-label="Copy code">Copy</button></div><p><strong>Solution:</strong></p>
<p>To fix this, we adjust the grammar to handle precedence by splitting it into levels:</p>
<div class="code-block" data-lang=""><pre class="chroma"><code>expression = term ( '+' term )*
term = factor ( '*' factor )*
factor = identifier | number | '(' expression ')'
</code></pre><button class="code-copy" type="button" aria-label="Copy code">Copy</button></div><p><strong>Explanation:</strong></p>
<ul>
<li><code>term</code> resolves multiplication first.</li>
<li><code>expression</code> handles addition after terms are resolved.</li>
<li><code>factor</code> includes parentheses to allow manual precedence overriding.</li>
</ul>
<p>With this grammar, the expression <code>2 + 3 * 4</code> is correctly parsed as:</p>
<div class="code-block" data-lang=""><pre class="chroma"><code>2 + (3 * 4)
</code></pre><button class="code-copy" type="button" aria-label="Copy code">Copy</button></div><p><strong>How Does This Work?</strong></p>
<p><code>term</code> handles multiplication first because it&rsquo;s defined at a lower level.</p>
<ul>
<li><code>expression</code> handles addition only after terms are resolved.</li>
<li><code>factor</code> includes parentheses to allow overriding precedence manually.</li>
</ul>
<p>Using this grammar, the expression <code>2 + 3 * 4</code> is parsed as:</p>
<div class="code-block" data-lang=""><pre class="chroma"><code>expression -&gt; term '+' term
term -&gt; factor '*' factor
factor -&gt; 3, 4
</code></pre><button class="code-copy" type="button" aria-label="Copy code">Copy</button></div><p>This ensures multiplication (<code>3 * 4</code>) happens first, followed by addition (<code>2 + 12</code>), yielding the correct result <code>14</code>.</p>
<h3 id="the-parse-tree-in-action">The parse tree in Action</h3>
<p>Grammar till now:</p>
<div class="code-block" data-lang=""><pre class="chroma"><code>Program = Function+
Function = Header '{' Body '}'
Header = DataType Identifier
Body = Statement+
Statement = Identifier '=' Expression
Expression = Terminal | (Expression Operator Expression)
Operator = '+' | '*'
Terminal = Identifier | Number
DataType = 'int' | 'float' | 'char' | 'void'
Identifier = (alphabet | _ ) (alphanumeric | _ )*
</code></pre><button class="code-copy" type="button" aria-label="Copy code">Copy</button></div><p>Example Code:</p>
<div class="code-block" data-lang=""><pre class="chroma"><code>void func1 {
 a = b + c * d;
}
void func2 {
 x = y + z;
}
</code></pre><button class="code-copy" type="button" aria-label="Copy code">Copy</button></div><h4 id="parse-tree-ascii-style">Parse Tree (ASCII Style)</h4>
<div class="code-block" data-lang=""><pre class="chroma"><code>Program
├── Function (func1)
│   ├── Header
│   │   ├── DataType (void)
│   │   └── Identifier (func1)
│   ├── Body
│   │   └── Statement
│   │       ├── Identifier (a)
│   │       ├── '='
│   │       └── Expression
│   │           ├── Identifier (b)
│   │           ├── '+'
│   │           └── Expression
│   │               ├── Identifier (c)
│   │               ├── '*'
│   │               └── Identifier (d)
├── Function (func2)
│   ├── Header
│   │   ├── DataType (void)
│   │   └── Identifier (func2)
│   ├── Body
│   │   └── Statement
│   │       ├── Identifier (x)
│   │       ├── '='
│   │       └── Expression
│   │           ├── Identifier (y)
│   │           ├── '+'
│   │           └── Identifier (z)
</code></pre><button class="code-copy" type="button" aria-label="Copy code">Copy</button></div><p>Here is the continuation, word by word, starting from Parse Tree (Lateral Style):</p>
<h4 id="parse-tree-lateral-style">Parse Tree (Lateral Style)</h4>
<p>For Function func1:</p>
<div class="code-block" data-lang=""><pre class="chroma"><code>=
             /   \
            a     +
                 / \
                b   *
                   / \
                  c   d
</code></pre><button class="code-copy" type="button" aria-label="Copy code">Copy</button></div><p>For Function func2:</p>
<div class="code-block" data-lang=""><pre class="chroma"><code>=
             /   \
            x     +
                 / \
                y   z
</code></pre><button class="code-copy" type="button" aria-label="Copy code">Copy</button></div><h4 id="full-program-tree">Full Program Tree:</h4>
<div class="code-block" data-lang=""><pre class="chroma"><code>Program
   ├── Function (func1)
   │         \
   │          =
   │         / \
   │        a   +
   │           / \
   │          b   *
   │             / \
   │            c   d
   └── Function (func2)
             \
              =
             / \
            x   +
               / \
              y   z
</code></pre><button class="code-copy" type="button" aria-label="Copy code">Copy</button></div><p>This breakdown shows how the program can be parsed into a tree format for easier interpretation.</p>
<h2 id="sneak-peek-into-the-implementation">Sneak Peek into the implementation</h2>
<p>I would encourage you to go ahead and try writing a small piece of code, maybe just a calculator (That&rsquo;s what I did first) to experiment with making a parse tree. A very good explanation and a highly detailed one is given in <em>Crafting Interpreters</em>, and you should check that out for constructing the parse tree. However, here is a look into how that&rsquo;s done:</p>
<p>So we have a counter that keeps track of the current token&rsquo;s index. It will start at 0 and go all the way till the length of the list of tokens. Now we have two functions, <code>match</code> and <code>consume</code>. <code>match(token)</code> will take a token and check if the current token is the same as the one sent in it and return a boolean.</p>
<p><code>consume(token, errorMsg)</code> will take the type of token expected there and an error message. If the token is not the one we sent, it will crash the code with the given error message. Again, for implementation details check the book, it&rsquo;s a goldmine. I am here just to give you the gist of it.</p>
<h2 id="the-walker-and-post-order-traversal">The Walker and Post Order Traversal</h2>
<p>Now, we have constructed a complete tree and have to go ahead and parse the tree gracefully, executing it. For that, we will start at the root and do a post-order traversal.</p>
<p>Here is some theory, and then I will give an example with expressions.</p>
<h3 id="post-order-traversal-l-r-root">Post-Order Traversal (L-R-Root)</h3>
<p>In post-order traversal, you visit:</p>
<ol>
<li>Left subtree.</li>
<li>Right subtree.</li>
<li>Root node.</li>
</ol>
<p><strong>Example:</strong></p>
<p>For a binary tree:</p>
<div class="code-block" data-lang=""><pre class="chroma"><code>A
     / \
    B   C
   / \
  D   E
</code></pre><button class="code-copy" type="button" aria-label="Copy code">Copy</button></div><p><strong>Steps:</strong></p>
<ol>
<li>Visit the left subtree (B → D → E).</li>
<li>Visit the right subtree (C).</li>
<li>Visit the root (A).</li>
</ol>
<p><strong>Post-Order Traversal Output:</strong></p>
<div class="code-block" data-lang=""><pre class="chroma"><code>D → E → B → C → A
</code></pre><button class="code-copy" type="button" aria-label="Copy code">Copy</button></div><p><strong>Key Rule:</strong> Process children first, then the parent.</p>
<h3 id="example">Example:</h3>
<p>Consider the expression represented by the following binary tree:</p>
<div class="code-block" data-lang=""><pre class="chroma"><code>=
             /   \
            a     +
                 / \
                b   *
                   / \
                  c   d
</code></pre><button class="code-copy" type="button" aria-label="Copy code">Copy</button></div><p>Where:</p>
<ul>
<li><code>b = 1</code></li>
<li><code>c = 2</code></li>
<li><code>d = 3</code></li>
</ul>
<p><strong>Post-Order Traversal Approach:</strong></p>
<ol>
<li>
<p><strong>Start at the root:</strong> The root is the <code>=</code> sign, representing an assignment. To perform this assignment, we need to first evaluate both the left-hand side (LHS) and the right-hand side (RHS) of the equation. This requires us to traverse both sides of the tree using post-order traversal.</p>
</li>
<li>
<p><strong>Left Subtree (LHS):</strong> The left side is simply <code>a</code>, a terminal identifier. No further traversal is needed here, so we just take <code>a</code> as is.</p>
</li>
<li>
<p><strong>Right Subtree (RHS):</strong> The right-hand side is the <code>+</code> operator, which is a non-terminal. So, we need to perform post-order traversal on the right subtree, which consists of:</p>
<ul>
<li>The left child: <code>b</code> (terminal with value 1).</li>
<li>The right child: <code>*</code> (another non-terminal).</li>
</ul>
</li>
<li>
<p><strong>Subtree with <code>*</code> (Right of <code>+</code>):</strong> The multiplication operator (<code>*</code>) requires post-order traversal as well. It has two children:</p>
<ul>
<li><code>c</code> (terminal with value 2).</li>
<li><code>d</code> (terminal with value 3).</li>
</ul>
<p>Since both <code>c</code> and <code>d</code> are terminals, we evaluate them first: <code>c = 2</code> and <code>d = 3</code>. The multiplication (<code>c * d</code>) gives us <code>2 * 3 = 6</code>. Now the <code>*</code> node becomes:</p>
<div class="code-block" data-lang=""><pre class="chroma"><code> *
/ \
2  3
</code></pre><button class="code-copy" type="button" aria-label="Copy code">Copy</button></div><p>We replace the <code>*</code> node with <code>6</code>:</p>
<div class="code-block" data-lang=""><pre class="chroma"><code> +
/ \
b  6
</code></pre><button class="code-copy" type="button" aria-label="Copy code">Copy</button></div></li>
<li>
<p><strong>Final Step:</strong> Now that we have resolved both children of the <code>+</code> node (<code>b = 1</code> and the result of <code>*</code> = 6), we can evaluate the addition: <code>1 + 6 = 7</code>. So, the <code>+</code> node is replaced with <code>7</code>:</p>
<div class="code-block" data-lang=""><pre class="chroma"><code> =
/ \
a  7
</code></pre><button class="code-copy" type="button" aria-label="Copy code">Copy</button></div></li>
<li>
<p><strong>Solve the Assignment:</strong> Finally, we can assign the value of <code>7</code> to <code>a</code>: This is the final result of the post-order traversal and evaluation process for this simple expression.</p>
</li>
</ol>
<p><strong>Key Points:</strong></p>
<ul>
<li><strong>Post-order Traversal:</strong> This process visits the left subtree first, then the right subtree, and finally the root, ensuring that we evaluate operands before operators.</li>
<li><strong>Recursive Traversal:</strong> Non-terminals (like <code>+</code> and <code>*</code>) require recursive traversal to break down the expression into simpler components, ultimately reducing the expression to terminal values that can be computed.</li>
<li><strong>Evaluation:</strong> Once the tree has been fully traversed and reduced to terminal values, the final result can be computed step by step.</li>
</ul>
<p><strong>Extending This Concept:</strong></p>
<p>This approach can be extended to handle more complex operations such as strings, loops, conditionals (if-else), and even multi-level expressions involving arrays or objects. It is a foundational concept for building parsers and evaluators for your own programming language.</p>
<h3 id="project-suggestion">Project Suggestion:</h3>
<p>A great beginner project would be to build a calculator that can handle multiple arithmetic operations:</p>
<ul>
<li>
<p>For example, you could write an expression like:</p>
<div class="code-block" data-lang=""><pre class="chroma"><code>a = 2 + 4
b = a / 2 + 20
</code></pre><button class="code-copy" type="button" aria-label="Copy code">Copy</button></div><p>And print the results of the expressions. Once you&rsquo;ve implemented that, you can explore scope management (keeping track of variable values) and control flow (like if statements, loops), ultimately creating a simple interpreter or mini-language.</p>
</li>
</ul>
<hr>
<h2 id="limitations">Limitations</h2>
<p>Tree walk interpreters are simple and easy to implement but suffer from poor performance due to direct evaluation of the Abstract Syntax Tree (AST) at runtime, without optimizations like operator precedence or memory management. They are slower than compiled languages because they lack optimizations and perform redundant work during interpretation. In contrast, machine code compilation converts code directly to machine language, offering excellent performance but no flexibility. Bytecode compilation translates code into a platform-independent format, offering portability and some optimizations, while Just-In-Time (JIT) compilation dynamically compiles code at runtime, providing performance close to machine code with the advantage of dynamic optimizations, though it introduces initial overhead. I insist you check these other compilation methods out and try stepping up your model later on.</p>
<p>You can check out my interpreter, Solunox.</p>
]]></content:encoded>
    </item>
    
  </channel>
</rss>