<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Saad Haider on Medium]]></title>
        <description><![CDATA[Stories by Saad Haider on Medium]]></description>
        <link>https://medium.com/@msaadh?source=rss-45b06c8d03f0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*YIXJaEues-0qTwV3</url>
            <title>Stories by Saad Haider on Medium</title>
            <link>https://medium.com/@msaadh?source=rss-45b06c8d03f0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 15:29:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@msaadh/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Making of an Interpreter]]></title>
            <link>https://medium.com/@msaadh/the-making-of-an-interpreter-1177ef124e44?source=rss-45b06c8d03f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/1177ef124e44</guid>
            <category><![CDATA[abstract-syntax-tree]]></category>
            <category><![CDATA[tree-walk-interpreter]]></category>
            <category><![CDATA[interpreters]]></category>
            <category><![CDATA[compilers]]></category>
            <dc:creator><![CDATA[Saad Haider]]></dc:creator>
            <pubDate>Fri, 31 Jul 2026 13:43:40 GMT</pubDate>
            <atom:updated>2026-07-31T13:43:40.771Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TGIU1ka69BffJmSwZTQyTg.png" /><figcaption>The Core of Interpreter</figcaption></figure><p>We’ve written code for years, but how often do we think about why the text we type into an editor eventually produces an output?</p><p>How do words like if, while, or return make sense to a machine that ultimately deals with binary?</p><p>In this article, I’ll take you through that journey and the thinking behind how an interpreter works.</p><h3>How Did We Get Here?</h3><p>Before we get into how an interpreter works, I think it’s worth asking why we needed one in the first place.</p><p>In the early days of computing, before assemblers and higher-level languages existed, programmers had to work much closer to the machine. Instructions were written in machine code, and on some early computers, even entered using physical switches.</p><p>Then came Assembly.</p><p>Instead of dealing with raw machine instructions, programmers could write things like MOV, ADD, and JMP, and an <strong>assembler</strong> would translate them into machine code.</p><p>But that raises an interesting question:</p><p><strong>How do you build an assembler when you don’t have an assembler yet?</strong></p><p>The first ones had to be created using lower-level mechanisms, including machine code. Once an assembler existed, though, it could be used to build better tools, which could then help build even better ones.</p><p>Eventually, this same idea leads to a question that confused me when I first thought about it:</p><p><strong>If the Java compiler is itself written in Java, how was the first Java compiler compiled?</strong></p><p>It wasn’t compiled by Java.</p><p>An initial compiler can be implemented using an already existing language. Once the new language becomes capable enough, a compiler for it can be written in the language itself and compiled using the existing compiler. From then on, each working compiler can help build the next one.</p><p>This is called <strong>bootstrapping</strong>.</p><p>And I think it captures something important about how we got here. We didn’t jump straight from machine code to the languages we use today. We kept building abstractions on top of what already worked, moving further away from the machine.</p><p>All because of a simple problem:</p><p><strong>Humans don’t want to speak the computer’s language. So we built programs that translate ours.</strong></p><h3>What Is an Interpreter?</h3><p>Enough of the story. Let’s get back to our topic.</p><p>Before going deeper, I want to differentiate between two terms: <strong>compiler</strong> and <strong>interpreter</strong>.</p><p>Both take source code and somehow make it executable, but they approach the problem differently.</p><p>In a simplified mental model, a compiler translates source code into another representation before execution. That representation could be machine code, bytecode, assembly, or even another language.</p><p>An interpreter, on the other hand, executes the program through the language implementation itself.</p><p>The distinction isn’t always clean. Modern language implementations often combine compilation and interpretation. But for what we’re building, this mental model is enough.</p><p>Our interpreter will roughly do this:</p><figure><img alt="Timeline of an interpreter" src="https://cdn-images-1.medium.com/max/309/1*H_XEPfNFjzuhP0ThXiTwQw.png" /></figure><p>Now let’s figure out why we need each of these stages.</p><h3>How Does a Computer Understand Our Source Code?</h3><p>Let’s return to our original question; how does a sequence of English characters actually make sense to a computer?</p><p>One thing is clear, the computer can’t directly understand the source code we write. We need to transform it into a structure our program can reason about.</p><p>There are thousands of programming languages, and they can express the same idea using completely different syntax.</p><p>That means the exact characters aren’t what ultimately matter. We need some internal representation of what those characters <strong>mean</strong>.</p><p>One common representation is the <strong>Abstract Syntax Tree (AST)</strong>.</p><p>But before we can build an AST, we need to turn our raw source code into something easier to work with.</p><p>We need <strong>tokens</strong>.</p><h3>Tokens</h3><p>Right now, our source code is just a sequence of characters.</p><p>Take this simple line:</p><pre>var age = 20 + 1;</pre><p>Is var three unrelated characters or one keyword?</p><p>Are 2 and 0 two numbers, or are they together the number 20?</p><p>Before trying to understand the structure of the program, let’s categorize what was written.</p><pre>var     -&gt;     VAR<br>age     -&gt;     IDENTIFIER<br>=       -&gt;     EQUAL<br>20      -&gt;     NUMBER<br>+       -&gt;     PLUS<br>1       -&gt;     NUMBER<br>;       -&gt;     SEMICOLON</pre><p>These categorized pieces are called <strong>tokens</strong>.</p><p>Humans are also going to make mistakes. We can’t assume that the code users write will always be valid.</p><p>So when we encounter an error, saying:</p><blockquote><em>“Oh! you have an error in the code. Good luck finding where it is”</em></blockquote><p>isn’t particularly useful.</p><p>We need to tell the user where the error occurred. That’s why tokens usually carry information such as their line number, lexeme, and literal value.</p><p>Let’s define the types of tokens our interpreter supports:</p><pre>public enum TokenType {<br>    // Single-character tokens.<br>    LEFT_PAREN, RIGHT_PAREN,<br>    LEFT_BRACE, RIGHT_BRACE,<br>    LEFT_BRACKET, RIGHT_BRACKET,<br>    DOT, MINUS, PLUS, COMMA,<br>    COLON, SEMICOLON, SLASH, STAR,<br><br>    // One or two-character tokens.<br>    BANG, BANG_EQUAL,<br>    EQUAL, EQUAL_EQUAL,<br>    GREATER, GREATER_EQUAL,<br>    LESS, LESS_EQUAL,<br>    AND, OR,<br><br>    // Literals.<br>    IDENTIFIER, STRING, NUMBER,<br><br>    // Keywords.<br>    FOR, WHILE, IF, ELSE, NIL,<br>    PRINT, VAR, TRUE, FALSE,<br>    EOF<br>}</pre><p>To keep track of additional information, we’ll wrap the token type inside a Token class:</p><pre>public class Token {<br>    private final TokenType type;<br>    private final String lexeme;<br>    private final Object literal;<br>    private final int line;<br>}</pre><p>There are two terms here that might look similar: <strong>lexeme</strong> and <strong>literal</strong>.</p><p>We’ll see the distinction more clearly when we build the scanner.</p><h3>Scanner</h3><p>The scanner’s job is to convert our source code, which is just a string of characters, into meaningful tokens.</p><p>For the most part, this involves walking through the source code, recognizing patterns, and categorizing them.</p><p>This is where <strong>lexemes</strong> and <strong>literals</strong> become useful.</p><p>A <strong>lexeme</strong> is the exact sequence of characters encountered in the source code.</p><p>A <strong>literal</strong> is the value represented by those characters.</p><p>For example, suppose the scanner encounters:</p><pre>true</pre><p>The lexeme is:</p><pre>&quot;true&quot;</pre><p>But the literal value is:</p><pre>true</pre><p>The first is a sequence of characters. The second is a boolean value.</p><p>Similarly, for:</p><pre>20</pre><p>the lexeme may be &quot;20&quot;, while the literal is the numeric value 20.</p><p>After scanning the entire source file, we have a list of tokens.</p><p>But tokens alone don’t tell us what the program means.</p><p>We need structure.</p><h3>Statements and Expressions</h3><p>A program is a sequence of instructions, and a single instruction usually requires multiple tokens to become meaningful.</p><p>Take:</p><pre>print &quot;Saad&quot;;</pre><p>Knowing that print is a PRINT token tells us that the user wants to print something.</p><p>But what do they want to print?</p><p>We need the STRING token too.</p><p>So instead of reasoning about isolated tokens, we’ll combine them into larger structures: <strong>statements</strong> and <strong>expressions</strong>.</p><p>An expression produces a value:</p><pre>20 + 1</pre><p>A statement performs some action:</p><pre>print 20 + 1;</pre><p>These statements and expressions will eventually become the nodes of our AST.</p><p>But how does the parser know which tokens belong together?</p><p>That’s where grammar comes in.</p><h3>Parser</h3><p>Every programming language has a grammar.</p><p>The grammar defines which sequences of tokens form valid programs and how those tokens relate to each other.</p><p>Consider:</p><pre>1 + 2 * 3</pre><p>The parser needs to understand that multiplication has higher precedence than addition.</p><p>It should interpret this as:</p><pre>1 + (2 * 3)</pre><p>not:</p><pre>(1 + 2) * 3</pre><p>Simply grouping tokens until we encounter a semicolon isn’t enough.</p><p>We need rules.</p><p>A small grammar might look like this:</p><pre>program     -&gt; statement* EOF ;<br>statement   -&gt; exprStmt<br>            | varDeclStmt<br>            | printStmt ;<br>exprStmt    -&gt; expression &quot;;&quot; ;<br>varDeclStmt -&gt; &quot;var&quot; IDENTIFIER ( &quot;=&quot; expression )? &quot;;&quot; ;<br>printStmt   -&gt; &quot;print&quot; expression &quot;;&quot; ;<br>expression  -&gt; equality ;<br>equality    -&gt; comparison ( (&quot;==&quot; | &quot;!=&quot;) comparison )* ;<br>comparison  -&gt; term ( (&quot;&gt;&quot; | &quot;&gt;=&quot; | &quot;&lt;&quot; | &quot;&lt;=&quot;) term )* ;<br>term        -&gt; factor ( (&quot;+&quot; | &quot;-&quot;) factor )* ;<br>factor      -&gt; unary ( (&quot;*&quot; | &quot;/&quot;) unary )* ;<br>unary       -&gt; (&quot;!&quot; | &quot;-&quot;) unary<br>            | primary ;<br>primary     -&gt; NUMBER | STRING<br>            | &quot;true&quot; | &quot;false&quot; | &quot;nil&quot;<br>            | &quot;(&quot; expression &quot;)&quot; ;</pre><p>This grammar tells us how valid expressions and statements are constructed.</p><p>Now we need to translate these rules into code.</p><h3>Recursive Descent Parsing</h3><p>One of the simplest ways to build a parser is <strong>recursive descent parsing</strong>.</p><p>It’s a <strong>top-down parser</strong> because it starts from the outermost grammar rule and works its way down into nested expressions.</p><p>The nice thing about recursive descent is that the implementation is almost a direct translation of the grammar.</p><p>For example:</p><pre>Expr expression() {<br>    return equality();<br>}<br><br>Expr equality() {<br>    Expr expr = comparison();<br>    while (match(EQUAL_EQUAL, BANG_EQUAL)) {<br>        Token operator = previous();<br>        Expr right = comparison();<br>        expr = new Binary(expr, operator, right);<br>    }<br>    return expr;<br>}<br><br>Expr comparison() {<br>    Expr expr = term();<br>    while (match(GREATER, GREATER_EQUAL, LESS, LESS_EQUAL)) {<br>        Token operator = previous();<br>        Expr right = term();<br>        expr = new Binary(expr, operator, right);<br>    }<br>    return expr;<br>}<br><br>Expr term() {<br>    Expr expr = factor();<br>    while (match(PLUS, MINUS)) {<br>        Token operator = previous();<br>        Expr right = factor();<br>        expr = new Binary(expr, operator, right);<br>    }<br>    return expr;<br>}<br><br>Expr factor() {<br>    Expr expr = unary();<br>    while (match(STAR, SLASH)) {<br>        Token operator = previous();<br>        Expr right = unary();<br>        expr = new Binary(expr, operator, right);<br>    }<br>    return expr;<br>}</pre><p>Each grammar rule becomes a method.</p><p>expression() begins with equality(), which works its way down through the precedence levels.</p><p>For example, term() handles addition and subtraction, while factor() handles multiplication and division.</p><p>Because term() calls factor() before handling its own operators, multiplication and division naturally get higher precedence than addition and subtraction.</p><p>That’s recursive descent parsing.</p><h3>Error Handling</h3><p>The parser is also a good place to detect <strong>syntax errors</strong>.</p><p>Suppose the user writes:</p><pre>var age = ;</pre><p>The scanner can tokenize this perfectly well.</p><p>But according to our grammar, something should appear after =.</p><p>That’s a syntax error.</p><p>Our first instinct might be to report the error immediately and stop parsing.</p><p>But what if the source code contains five syntax errors?</p><p>Reporting one error at a time would force the user into an annoying cycle:</p><pre>run -&gt; fix -&gt; run -&gt; fix -&gt; run -&gt; fix</pre><p>It would be much better to report as many useful errors as possible in a single run.</p><p>But that introduces another problem.</p><p>After encountering an error, where should the parser continue?</p><p>Starting from the next token could leave us in the middle of an expression, producing a cascade of meaningless errors.</p><p>Instead, we <strong>synchronize</strong>.</p><p>We advance until we reach a likely statement boundary, such as a semicolon or the beginning of another statement. Then the parser can continue from a location where it has a reasonable chance of understanding the program again.</p><p>Now that we can parse our tokens, we can finally build the structure we’ve been talking about.</p><h3>Abstract Syntax Tree</h3><p>An <strong>Abstract Syntax Tree</strong>, or AST, represents the structure of our program.</p><p>Take:</p><pre>1 + 2 * 3</pre><p>The AST might conceptually look like:</p><pre>  +<br> / \<br>1   *<br>   / \<br>  2   3</pre><p>The multiplication sits deeper in the tree, representing the fact that it should be evaluated before addition.</p><p>The nodes of our AST represent meaningful constructs such as:</p><pre>BinaryExpression<br>UnaryExpression<br>VariableExpression<br>PrintStatement<br>VariableDeclaration<br>WhileStatement</pre><p>Now our source code has gone from:</p><pre> Characters<br>      ↓<br>   Tokens<br>      ↓<br>Structured AST</pre><p>The parser has done its job.</p><p>But now we have another problem.</p><p>How do we actually do things with this tree?</p><h3>The Problem With Traversing the AST</h3><p>We could manually traverse the tree.</p><p>For each node, we check its type and perform the appropriate operation.</p><p>But an interpreter eventually needs many operations over the same AST.</p><p>For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*LXMFWMPLt6Uto9vxGGgzvg.png" /></figure><p>Think of AST node types as rows and operations as columns.</p><p>One approach would be to put methods such as:</p><pre>interpret()<br>resolve()<br>analyze()</pre><p>inside every AST node.</p><p>Adding a new node type would be easy, create the class and implement those methods.</p><p>But adding a new operation would be painful because we’d need to modify every existing AST class.</p><p>We could flip the design and centralize operations instead.</p><p>That makes adding operations easier, but now every operation needs to know how to handle every AST node type.</p><p>This is the problem the <strong>Visitor Pattern</strong> helps us organize.</p><h3>The Visitor Pattern</h3><p>The Visitor Pattern lets us define operations over a family of types without putting those operations directly inside each type.</p><p>Think of the AST as a hospital.</p><p>The nodes are patients.</p><p>The visitors are specialists.</p><p>A patient only needs to identify what kind of patient they are. The specialist decides what to do with that kind of patient.</p><p>A node is essentially saying:</p><blockquote><em>“You’re visiting me? I’m a </em><em>BinaryExpr. Use your </em><em>visitBinaryExpr() procedure.&quot;</em></blockquote><p>Let’s use a simpler example.</p><pre>interface Animal {<br>    void accept(AnimalVisitor visitor);<br>}<br><br>interface AnimalVisitor {<br>    void visitMonkey(Monkey monkey);<br>    void visitLion(Lion lion);<br>    void visitDolphin(Dolphin dolphin);<br>}<br><br>class Monkey implements Animal {<br>    @Override<br>    public void accept(AnimalVisitor visitor) {<br>        visitor.visitMonkey(this);<br>    }<br>}<br><br>class Lion implements Animal {<br>    @Override<br>    public void accept(AnimalVisitor visitor) {<br>        visitor.visitLion(this);<br>    }<br>}<br><br>class Dolphin implements Animal {<br>    @Override<br>    public void accept(AnimalVisitor visitor) {<br>        visitor.visitDolphin(this);<br>    }<br>}</pre><p>Every animal knows how to accept a visitor.</p><p>Now we can define an operation:</p><pre>class Speak implements AnimalVisitor {<br>    @Override<br>    public void visitMonkey(Monkey monkey) {<br>        System.out.println(&quot;Monkey shout: Ooh oo aa aa!&quot;);<br>    }<br><br>    @Override<br>    public void visitLion(Lion lion) {<br>        System.out.println(&quot;Lion roar: Roaaar!&quot;);<br>    }<br><br>    @Override<br>    public void visitDolphin(Dolphin dolphin) {<br>        System.out.println(&quot;Dolphin speak: Tuut tutt tuutt!&quot;);<br>    }<br>}</pre><p>Speak contains the implementation of that operation for every animal.</p><p>Using it looks like this:</p><pre>void main() {<br>    Monkey monkey = new Monkey();<br>    Lion lion = new Lion();<br>    Dolphin dolphin = new Dolphin();<br><br>    AnimalVisitor speak = new Speak();<br><br>    monkey.accept(speak);<br>    lion.accept(speak);<br>    dolphin.accept(speak);<br>}</pre><p>What’s interesting here is <strong>double dispatch</strong>.</p><p>When we call:</p><pre>monkey.accept(speak);</pre><p>the first dispatch selects Monkey.accept().</p><p>Inside that method:</p><pre>visitor.visitMonkey(this);</pre><p>the second dispatch selects the visitor’s implementation for Monkey.</p><p>The same idea works with our AST.</p><p>Instead of putting interpreter logic inside every AST node, the interpreter can be a visitor.</p><p>The resolver can be another visitor.</p><p>Later, if we want another operation over the AST, we can create another visitor.</p><p>Now we finally have a structured program that we can execute.</p><p>But execution introduces another problem.</p><p>Memory.</p><h3>Memory</h3><p>While executing a program, we create variables:</p><pre>var name = &quot;Saad&quot;;</pre><p>and use them later:</p><pre>print name;</pre><p>So we need somewhere to store them.</p><p>We need two things:</p><pre>name -&gt; value</pre><p>A natural choice is:</p><pre>Map&lt;String, Object&gt;</pre><p>A hash map gives us average O(1) insertion and lookup, which makes it a good fit for variable storage.</p><p>Great.</p><p>But now we encounter <strong>scoping</strong>.</p><p>Consider:</p><pre>var name = &quot;global&quot;;<br>var num = 1;<br><br>{<br>    var name = &quot;local&quot;;<br>    print name;<br>    print num;<br>}<br>print name;</pre><p>Inside the block, name should refer to &quot;local&quot;.</p><p>But num should still be accessible from the outer scope.</p><p>After leaving the block, name should once again refer to &quot;global&quot;.</p><p>We could create a new map for every scope.</p><p>Conceptually:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*OgP7zviVnHfNHpcY1PiMaw.png" /></figure><p>But how does the local map access variables from the global map?</p><p>We could copy every global variable into every local scope.</p><p>That would work, but it would waste memory and create synchronization problems. With deeply nested scopes, the same variable could be duplicated many times.</p><p>Instead, why not link scopes together?</p><p>Each scope stores its own variables and a reference to its parent.</p><pre>class Environment {<br>    Map&lt;String, Object&gt; memory;<br>    Environment parent;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*bWZuQ6V6xDfO0-Zl5D9Kkg.png" /></figure><p>Now variable lookup works like this:</p><pre>Current scope<br>    ↓<br>Parent scope<br>    ↓<br>Parent&#39;s parent<br>    ↓<br>...</pre><p>If a variable isn’t found in the current environment, we walk up the chain until we find it.</p><p>Now we have a basic environment model with lexical scopes.</p><p>Things get more interesting when we introduce functions.</p><h3>Functions</h3><p>We now have a place to store variables, and scopes are represented by environments linked to their parents.</p><p>That’s enough for executing blocks of code.</p><p>But consider a function:</p><pre>var name = &quot;Saad&quot;;<br><br>func greet() {<br>    print name;<br>}<br>greet();</pre><p>When we call greet(), where should it look for name?</p><p>The simplest answer might be:</p><blockquote><em>Look in whatever environment is active when the function is called.</em></blockquote><p>But that creates strange behavior:</p><pre>var name = &quot;Saad&quot;;<br><br>func greet() {<br>    print name;<br>}<br><br>{<br>    var name = &quot;John&quot;;<br>    greet();<br>}</pre><p>Should greet() suddenly print &quot;John&quot; just because we called it from inside this block?</p><p>That would mean the meaning of the function depends on where we call it from.</p><p>That’s not how <strong>lexical scoping</strong> works.</p><p>We should be able to look at the source code and determine what a variable refers to.</p><p>greet() was declared where name referred to the global variable. Calling it from another scope shouldn&#39;t change that.</p><p>So a function needs to remember the environment in which it was declared.</p><pre>class Function {<br>    FunctionDeclaration declaration;<br>    Environment closure;<br>}</pre><p>When we encounter a function declaration, we store the current environment with it.</p><p>Later, when the function is called, we create a new child environment for that particular call.</p><p>This new environment stores parameters and local variables, while its parent gives the function access to variables that were visible where it was declared.</p><p>That captured environment is what makes closures possible.</p><h3>Closures</h3><p>Consider:</p><pre>func makeCounter() {<br>    var count = 0;<br><br>    func increment() {<br>        count = count + 1;<br>        print count;<br>    }<br>    return increment;<br>}<br><br>var counter = makeCounter();<br><br>counter(); // 1<br>counter(); // 2<br>counter(); // 3</pre><p>Normally, we might expect everything created while executing makeCounter() to disappear once the function returns.</p><p>But increment() still needs count.</p><p>When increment was created, it captured the current environment: the environment belonging to makeCounter().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*3CuJ8fPfZaj3S8M2DCieGA.png" /></figure><p>Even after makeCounter() returns, increment still holds a reference to that environment.</p><p>So the environment can’t disappear yet.</p><p>Every time we call increment(), it reaches back into that captured environment and updates the same count.</p><p>That’s a <strong>closure</strong>.</p><p>A closure is essentially a function bundled with the environment in which it was created.</p><p>This is why a function can keep using variables from an outer function even after that outer function has finished executing.</p><p>At this point, our environment model looks pretty solid.</p><p>Unfortunately, there’s a hole in it.</p><h3>When Runtime Scoping Breaks</h3><p>Consider this:</p><pre>var a = &quot;global&quot;;<br>{<br>    func showA() {<br>        print a;<br>    }<br><br>    showA();<br><br>    var a = &quot;block&quot;;<br><br>    showA();<br>}</pre><p>What should this print?</p><pre>global<br>global</pre><p>Why?</p><p>Look at where showA() is written.</p><p>The a inside it refers to the global a. At the point where that expression appears in the source code, the block&#39;s local a hasn&#39;t been declared yet, so it isn&#39;t in scope.</p><p>But let’s run this using the environment model we just built.</p><p>When showA is declared, it captures the current block environment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*nA54aVXLMDYhbb24NpdYNA.png" /></figure><p>During the first call, we look for a in the block environment.</p><p>It isn’t there, so we move to its parent and find:</p><pre>a = &quot;global&quot;</pre><p>Perfect.</p><p>Then this executes:</p><pre>var a = &quot;block&quot;;</pre><p>But remember: showA holds a reference to the <strong>same block environment</strong>.</p><p>That environment now looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*z0351QFXq6h-yYZwz7IGyw.png" /></figure><p>Call showA() again and our interpreter searches the environment chain.</p><p>This time, it immediately finds:</p><pre>a = &quot;block&quot;</pre><p>So our interpreter prints:</p><pre>global<br>block</pre><p>We have a problem.</p><p>The exact same expression:</p><pre>print a;</pre><p>referred to one variable during the first call and another variable during the second.</p><p>Its meaning changed at runtime.</p><p>But lexical scope is determined by the structure of the source code, not by the state of our environment when a line happens to execute.</p><p>Our environments are good at answering:</p><blockquote><em>Where is the value of this variable stored?</em></blockquote><p>But we’re missing another question:</p><blockquote><em>Which variable does this </em><em>a actually refer to?</em></blockquote><p>And that’s something we can figure out <strong>before executing the program</strong>.</p><h3>Semantic Analysis</h3><p>So we introduce another pass between parsing and execution: a <strong>resolver</strong>.</p><p>The parser gave structure to our program, but that structure alone doesn’t tell us which declaration a variable refers to.</p><p>The <strong>resolver</strong> walks the AST before execution and resolves these references. For each variable expression, it determines which declaration that variable refers to.</p><p>Suppose we have:</p><pre>var a = &quot;global&quot;;<br>{<br>    var b = 10;<br>    {<br>        var c = a + b;<br>    }<br>}</pre><p>When the resolver encounters b, it can determine that b belongs to the environment one scope outside the current one.</p><p>Conceptually, we can record:</p><pre>b -&gt; 1 scope away</pre><p>For a, no local declaration exists, so it resolves to the global variable.</p><p>Now when the interpreter later evaluates b, it doesn&#39;t need to ask:</p><blockquote><em>Starting from my current environment, where can I find something called </em><em>b?</em></blockquote><p>We’ve already answered that question.</p><p>It knows exactly which scope to access.</p><p>This separation turns out to be useful beyond fixing closures.</p><p>There are errors that are perfectly valid syntax but don’t make sense semantically.</p><p>For example:</p><pre>{<br>    var a = a;<br>}</pre><p>The parser has no problem with this.</p><pre>var IDENTIFIER = expression;</pre><p>is valid syntax.</p><p>But while resolving it, we know that we’re currently declaring a, and its initializer is trying to read that same variable before its initialization has completed.</p><p>Similarly:</p><pre>return 10;</pre><p>is syntactically a perfectly valid return statement.</p><p>But if we’re not inside a function, what are we returning from?</p><p>Again, the parser shouldn’t care.</p><p>Its job is to determine whether the tokens form valid syntax. But the resolver understands enough context to reject it.</p><p>This gave me a useful way to separate their responsibilities:</p><pre>Parser:<br>&quot;What structure does this code have?&quot;</pre><pre>Resolver:<br>&quot;What do the names and constructs in that structure refer to?&quot;</pre><pre>Interpreter:<br>&quot;What happens when I execute it?&quot;</pre><p>The resolver isn’t there because every interpreter is supposed to have something called “semantic analysis.”</p><p>It exists because eventually there are questions that can’t be answered correctly by syntax or runtime environment lookup alone.</p><h3>Control Flow</h3><p>Now that variables, scopes, and functions work, we can start making the language actually useful.</p><p>An if statement is straightforward. Evaluate the condition and decide which branch to execute.</p><p>A while loop isn&#39;t much different:</p><pre>while (condition) {<br>    body;<br>}</pre><p>The interpreter evaluates condition. If it&#39;s true, it executes body and repeats.</p><p>So far, control flow is still local. We either execute a statement, skip a branch, or repeat a block.</p><p>But some statements need to jump out of the normal execution flow entirely.</p><h3>Return</h3><p>Consider a return statement:</p><pre>func find() {<br>    while (true) {<br>        if (found) {<br>            return 10;<br>        }<br>    }<br>}</pre><p>When the interpreter reaches return, it can&#39;t simply stop executing the current block. It has to escape the if, then the while, then the function body, and finally return 10 to whoever called find().</p><p>We could make every layer check whether a return occurred and manually propagate it upward, but that would spread return-handling logic throughout the interpreter.</p><p>There’s a simpler option: use the host language’s own stack unwinding.</p><p>When the interpreter encounters a return, we throw a special exception carrying the returned value:</p><pre>class Return extends RuntimeException {<br>    final Object value;<br><br>    Return(Object value) {<br>        this.value = value;<br>    }<br>}</pre><p>Then, at the function boundary, we catch it:</p><pre>try {<br>    interpreter.executeBlock(body, environment);<br>} catch (Return returnValue) {<br>    return returnValue.value;<br>}</pre><p>Now it doesn’t matter how deeply nested the return is. The exception unwinds through all those intermediate blocks until it reaches the function call that knows how to handle it.</p><p>Nothing actually went wrong here. We’re simply using the exception mechanism because it already provides exactly what we need: <strong>jumping through multiple levels of execution to a known boundary</strong>.</p><p>Here’s another interesting control-flow construct: the for loop.</p><pre>for (var i = 0; i &lt; 10; i = i + 1) {<br>    print i;<br>}</pre><p>Our first instinct might be to create a new ForStmt AST node, teach the parser how to construct it, add a visitor method for it, and teach the interpreter how to execute it.</p><p>We could.</p><p>But look at what a for loop actually does.</p><p>First:</p><pre>var i = 0;</pre><p>Then repeatedly:</p><pre>while (i &lt; 10) {<br>    print i;<br>    i = i + 1;<br>}</pre><p>We already know how to execute every one of those things.</p><p>So why teach the rest of the interpreter about another construct?</p><h3>Desugaring</h3><p>Instead of implementing for all the way through the interpreter, the parser can translate it into simpler constructs that already exist.</p><p>This:</p><pre>for (var i = 0; i &lt; 10; i = i + 1) {<br>    print i;<br>}</pre><p>can become something conceptually equivalent to:</p><pre>{<br>    var i = 0;<br>    while (i &lt; 10) {<br>        print i;<br>        i = i + 1;<br>    }<br>}</pre><p>Now the interpreter doesn’t even need to know that for loops exist.</p><p>As far as it’s concerned, it received a block containing a variable declaration and a while loop.</p><p>This is called <strong>desugaring</strong>.</p><p>Some syntax exists because it makes the programmer’s life easier, not because the interpreter needs a fundamentally new operation to support it.</p><p>We can provide convenient syntax at the surface and translate it into a smaller set of constructs internally.</p><h3>What I Took Away From Building an Interpreter</h3><p>When I started building this interpreter, I thought the hard part would be executing code.</p><p>It wasn’t.</p><p>Most of the interesting problems appeared before execution: turning characters into structure, deciding what names refer to, representing scopes, handling closures, and designing the AST so that adding new operations didn’t turn the codebase into a mess.</p><p>What started as: “How does a computer understand my code?”</p><p>eventually became a fully working interpreter.</p><p>And each stage exists because the previous one leaves a problem that still needs to be solved.</p><p>The scanner turns characters into meaningful pieces.</p><p>The parser turns those pieces into structure.</p><p>The resolver determines what names and constructs mean in context.</p><p>The interpreter finally executes that meaning.</p><p>The <a href="https://github.com/M-SaaD-H/orin">interpreter I built</a> is nowhere near a production programming language, and that was never the goal.</p><p>The goal was to stop treating compilers and interpreters as black boxes.</p><p>Now when I declare a variable, define a function, create a closure, or write a for loop, I have a much better picture of what has to happen underneath before that code can run.</p><p>And for me, that was the whole point of building one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1177ef124e44" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>