<?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 Krupa Dave on Medium]]></title>
        <description><![CDATA[Stories by Krupa Dave on Medium]]></description>
        <link>https://medium.com/@heyitskrupa?source=rss-21e45d916897------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*txusLbJ4m6GbOKF7ByMhFg.jpeg</url>
            <title>Stories by Krupa Dave on Medium</title>
            <link>https://medium.com/@heyitskrupa?source=rss-21e45d916897------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 03:03:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@heyitskrupa/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[Building a Teeny Tiny Compiler: My Journey]]></title>
            <link>https://medium.com/@heyitskrupa/building-a-teeny-tiny-compiler-my-journey-dd08b1cf42c4?source=rss-21e45d916897------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd08b1cf42c4</guid>
            <category><![CDATA[compiler-design]]></category>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[low-level-design]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[computers]]></category>
            <dc:creator><![CDATA[Krupa Dave]]></dc:creator>
            <pubDate>Thu, 06 Feb 2025 15:20:02 GMT</pubDate>
            <atom:updated>2025-02-06T15:20:02.573Z</atom:updated>
            <content:encoded><![CDATA[<p>Compilers always seemed like an intimidating topic to me — something that was reserved more for hardcore software engineers. But after coming across Austin Henley’s <em>Teeny Tiny Compiler</em>, I realized that building a compiler is not only possible, but an incredibly rewarding learning experience as well. This is my journey through the process, the challenges I faced, and what I learned along the way.</p><h3>Why Build a Compiler?</h3><p>Before delving into all the technical details, the most obvious question is, why did I decide to write a compiler? And for those of you who don’t come from a technical background…what is a compiler, and why is it mentioned so extensively in the programming world.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kim6Kqubcz99CatY.jpg" /></figure><p>Imagine you have a friend who only speaks French, and another who only speaks English. Assuming that they each know nothing about the other’s language, they need a translator who understands both languages and can seamlessly convert one into the other.</p><p>A <strong>compiler </strong>is like that <strong>translator</strong> but for computers. Programmers write instructions in a language that they understand (eg. C, C++, Java), and the compiler will translate these instructions into a language that the computer understands (eg. binary code consisting of 1s and 0s). Thanks to the compiler, the computer now understands which set of instructions to execute!</p><p>Personally, I wanted to understand more about this “translation process”, and gain an insight into how programming languages work under the hood. Building a compiler would force me to understand parsing, code generation, and how a CPU actually executes instructions.</p><h3><strong>Understanding the Basics</strong></h3><p>The first step was actually grasping the basics of a compiler, and what it actually does. On a higher level, it takes high-level programming code, and transforms it into machine-executable instructions.</p><p>Note: The <em>Teeny Tiny</em> Compiler doesn’t include all <strong>6</strong> processes of a full-fledged compiler because it’s designed to be a simplified example, focusing on the core mechanics of compilation <em>(refer to endnotes)</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*MHYbl5gYKHRxWxaM.png" /></figure><p>The Teeny Tiny Compiler is broken down into 3 main components:</p><ol><li><strong>Lexer (Lexical Analysis): </strong>The source code is broken down into <em>tokens </em>such as keywords (ie. if, while), identifiers (ie. variable names), operators (+, -, *, /) and punctuation (, or ;)</li><li><strong>Parser (Syntax Analysis): </strong>Checks the code for syntax errors &amp; ensures it follows the rules of the programming language. The compiler will generate an Abstract Syntax Tree (AST) that represents the structure of the code</li><li><strong>Emitter (Code Generation): </strong>Takes the parsed structure (AST) and coverts it into an executable Output — in this case, a simple stack-based set of instructions in C</li></ol><p>Armed with this knowledge, I was now ready to move on to the code.</p><h3><strong>Building the Lexer</strong></h3><p>With an understanding of the compiler’s overall structure, the next step was to build the lexer (tokenizer/scanner). This part of the compiler transforms raw source code into a list of tokens — discrete units that can be passed into the parser.</p><p><strong>What the Lexer Does:</strong></p><ol><li><strong>Read Characters: </strong>The lexer scans the input character by character</li><li><strong>Categorize: </strong>It groups characters into recognizable tokens (e.g. keywords like if, while, identifiers (i.e. variable names or symbols +, -, *, /)</li><li><strong>Ignoring Irrelevant Data:</strong> Whitespace and comments are skipped</li></ol><p>The lexer would have to iterate the source code (written in Teeny Tiny), character by character, &amp; identify what type of token it is — where it begins and where it ends. The figure below demonstrates how a raw source string in <em>Teeny Tiny </em>looks like broken up into tokens along with the type (ie. identifier).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CrKx-b4UDiVS3nMNYvL7wQ.png" /></figure><p><em>Note: The following code snippets use Python. Familiarity with Python syntax &amp; related programming concepts may be helpful to follow along.</em></p><p>First, I had to initialize the constructor of the Lexer class, which kept track of the current position, and the character at that position.</p><pre>    #Lexer keeps track of the current position in the input string &amp; the character at that position. These are initialized in the following constructor:<br>    def __init__ (self, source): <br>        self.source = source + &#39;\n&#39; #this adds the source code to the lexer as a string, and a newline character is appended in order to simpify lexing/parsing the last token/statement<br>        self.curChar = &quot;&quot; #current character in the string <br>        self.curPos = -1 #current position in the string <br>        self.nextChar() </pre><p>Next, I had a function that would increment the lexer’s current position, and updates the current character until it reaches the end of the source code (until it reaches the end-of-file marker).</p><pre>    #Processing the next character<br>    def nextChar (self):<br>        self.curPos += 1 #increments the lexer&#39;s current position<br>        if self.curPos &gt;= len (self.source):<br>            self.curChar = &#39;\0&#39; #EOF (reach end of the file)<br>        else:<br>            self.curChar = self.source [self.curPos]</pre><p>Next, I added a peek function that would allow me to look ahead at the character after curChar (current character) without having to modify curPos (the current position).</p><p>This was also where I added a function that would display an error message if an invalid token was found &amp; exit. I had to add <em>import sys </em>at the top of the lexer’s Python file (<em>refer to Endnotes</em>).</p><pre>#Return the lookahead character <br>    def peek (self):<br>        if self.curPos + 1 &gt;= len (self.source): <br>            return &#39;\0&#39;<br>        return self.source [self.curPos + 1]<br>            <br>    #If an invalid token is found, then print an error message and exit <br>    def abort (self, message):<br>        sys.exit (&quot;Lexing error. &quot;+message) #Note to self: As a part of the sys module, you can terminate a program using sys.exit([status])</pre><p>Next, I added functions to skip whitespace &amp; comments in the source code (ie. skipping a space or text after “#”) , so it registers only tokens.</p><pre>    #Skip whitespaces except newlines, which will be used to indicate the end of a sentence <br>    def skipWhitespace (self):<br>        while self.curChar == &#39; &#39; or self.curChar == &#39;\t&#39; or self.curChar == &#39;\r&#39;:<br>            self.nextChar()<br>    <br>    #Skip comments in the code <br>    #Whenever a lexer sees a comment, it should ignore all the text after it until a newline (will be discarded)<br>    #it&#39;s important that the newline at the end of the comment isn&#39;t thrown away since it its own token and may still be needed <br>    def skipComment (self):<br>        if self.curChar == &#39;#&#39;:<br>            while self.curChar != &#39;\n&#39;:<br>                self.nextChar()</pre><p>It was important to identify how many characters constituted a “token” and what each token was classified as. The following figure identifies all the tokens in <em>Teeny Tiny </em>and the main lexer rules.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UvUiAg62IgeZRw5avN0zqQ.png" /></figure><p>Henceforth, I then created a Token class which would keep track of what type of token it is, and the “text” from the code.</p><pre>class Token:<br>    &quot;&quot;&quot;This is a token class that keeps track of what type of token it is &amp; the exact text from the code&quot;&quot;&quot;<br>    <br>    def __init__(self, tokenText, tokenKind):<br>        self.text = tokenText #the token&#39;s actual text. Used for identifiers, strings &amp; numbers <br>        self.kind = tokenKind #the &quot;type&quot; of token that this will be identified as<br>        <br>    @staticmethod <br>    def checkIfKeyword(tokenText):<br>        for kind in TokenType:<br>            #relies on all enumvalues being 1xx<br>            if kind.name == tokenText and kind.value &gt;= 100 and kind.value &lt; 200:<br>                return kind<br>        return None</pre><p>To manage these tokens in my compiler, I used Python’s <em>enum</em> module. Enums (enumerations) assign names along with constant values, which is used in the logic above (in the checkIfKeyword function) to identify if it fell within the number range — and if it did, to return the kind of token.</p><pre>class TokenType(enum.Enum):<br>        EOF = -1<br>        NEWLINE = 0<br>        NUMBER = 1<br>        IDENT = 2<br>        STRING = 3 <br>        #Keywords<br>        LABEL = 101<br>        GOTO = 102<br>        PRINT = 103<br>        INPUT = 104<br>        LET = 105<br>        IF = 106<br>        THEN = 107<br>        ENDIF = 108<br>        WHILE = 109<br>        REPEAT = 110<br>        ENDWHILE = 111<br>        #Operators <br>        EQ = 201<br>        PLUS = 202<br>        MINUS = 203<br>        ASTERISK = 204<br>        SLASH = 205<br>        EQEQ = 206<br>        NOTEQ = 207<br>        LT = 208<br>        LTEQ = 209<br>        GT = 210<br>        GTEQ = 211</pre><p>And finally, the remaining logic was put within the getToken function — which is the heart of the lexer. This function was responsible for reading the source code character by character and deciding what type of token to produce next. The <em>getToken</em> function handled all the preprocessing, token detection, multi-character operations, handling string literals, recognizing numbers, handling identifiers &amp; keywords, and special cases like unknown tokens.</p><pre># Return the next token<br>    def getToken(self):<br>        <br>        #skip everytime you encounter a whitespace<br>        self.skipWhitespace()<br>        <br>        #skip everytime you encounter a comment <br>        self.skipComment()<br>        <br>        token = None #Note to self: none is used to define a null value in Python<br>        <br>        #checking the first character of the token to see if we can decide what it is <br>        #if it is a multiple character operator (eg. !=), number, identifier or keyword then we will process the rest<br>        if self.curChar == &#39;+&#39;: #plus token<br>            token = Token (self.curChar, TokenType.PLUS)<br>        elif self.curChar == &#39;-&#39;: #minus token<br>            token = Token (self.curChar, TokenType.MINUS)<br>        elif self.curChar == &#39;*&#39;: #asterisk token<br>            token = Token (self.curChar, TokenType.ASTERISK)<br>        elif self.curChar == &#39;/&#39;: #slash token<br>            token = Token (self.curChar, TokenType.SLASH)<br>        <br>        #lexing operators made up of 2 characters (== &amp; &gt;= &amp; &lt;= &amp; !=)<br>        elif self.curChar == &#39;=&#39;:<br>            #check whether the token is = or == <br>            if self.peek() == &#39;=&#39;:<br>                lastChar = self.curChar<br>                self.nextChar()<br>                token = Token (lastChar + self.curChar, TokenType.EQEQ)<br>            else:<br>                token = Token (self.curChar, TokenType.EQ)<br>        elif self.curChar == &#39;&gt;&#39;:<br>            #check whether this token is &gt; or &gt;= <br>            if self.peek() == &#39;=&#39;:<br>                lastChar = self.curChar <br>                self.nextChar()<br>                token = Token (lastChar + self.curChar, TokenType.GTEQ)<br>            else:<br>                token = Token (self.curChar, TokenType.GT)<br>        elif self.curChar == &#39;&lt;&#39;:<br>            #check whether this token is &lt; or &lt;= <br>            if self.peek() == &#39;=&#39;:<br>                lastChar = self.curChar <br>                self.nextChar()<br>                token = Token (lastChar + self.curChar, TokenType.LTEQ)<br>            else:<br>                token = Token (self.curChar, TokenType.LT)<br>        elif self.curChar == &#39;!&#39;:<br>            #check whether this oken is ! or !=<br>            if self.peek() == &#39;=&#39;:<br>                lastChar = self.curChar<br>                self.nextChar()<br>                token = Token (lastChar + self.curChar, TokenType.NOTEQ)<br>            else:<br>                self.abort(&quot;Expected !=, got !&quot; + self.peek())<br>        <br>        #supports printing a string - which starts with a double quotation mark up until the 2nd double quotation mark<br>        elif self.curChar == &#39;\&quot;&#39;:<br>            <br>            #get all the characters between the quotation marks<br>            self.nextChar()<br>            startPos = self.curPos<br>            <br>            while self.curChar != &#39;\&quot;&#39;:<br>                #No special characters are allowed in the string, including no escape characters, newlines, tabs or %<br>                #we&#39;re using C&#39;s printf on this sting<br>                if self.curChar == &#39;\r&#39; or self.curChar == &#39;\n&#39; or self.curChar == &#39;\t&#39; or self.curChar == &#39;\\&#39; or self.curChar == &#39;%&#39;:<br>                    self.abort (&quot;Illegal character in the string&quot;)<br>                self.nextChar()<br>            tokText = self.source [startPos:self.curPos] #this slices the source string from the beginning of the &quot; to the end of &quot; (start and end of string)&quot;<br>            token = Token (tokText, TokenType.STRING)<br>        <br>        #In the Teeny Tiny Language, it supports a number as one or more digits (from 0-9) that is followed by an optional decimal point that must be followed by atleast 1 digit<br>        #peek function will help look ahead one character <br>        <br>        elif self.curChar.isdigit(): #Note to self: isdigit() is a string method used to check whether all characters in a string are digits (0-9). Returns True if they&#39;re numeric digits, and False otherwise<br>            startPos = self.curPos<br>            while self.peek().isdigit():<br>                self.nextChar()<br>            if self.peek() == &#39;.&#39;:<br>                self.nextChar() <br>    <br>                #ensure that you have atleast one digit after the decimal to be valid<br>                if not self.peek().isdigit():<br>                    #you get an error if it&#39;s not a digit <br>                    self.abort(&quot;Illegal character in number.&quot;)<br>                while self.peek().isdigit():<br>                    self.nextChar()<br>            tokText = self.source [startPos:self.curPos + 1] #Note to self: remember string slicing goes up to the value before itself<br>            token = Token (tokText, TokenType.NUMBER)   <br>        <br>        #Handling keywords &amp; identifiers. An identifier is anything that begins with an alphabetical character followed by zero or more alphanumeric characters<br>        elif self.curChar.isalpha(): #Note to self: isalpha() is a method used in Python that checks whether the characters in a string are alphabetic (ie. letters a to z). Returns True if so, otherwise False<br>            startPos = self.curPos<br>            while self.peek().isalnum(): #Note to self: isalnum() is a method used in Python that checks whether the characters in a string are alphanumeric<br>                self.nextChar()    <br>            <br>            #check to see whether the token is in the list of keywords<br>            tokText = self.source [startPos : self.curPos + 1] #getting the substring of text<br>            keyword = Token.checkIfKeyword(tokText)<br>            if keyword == None: #This means it&#39;s an identifier<br>                token = Token (tokText, TokenType.IDENT)  <br>            else:<br>                token = Token (tokText, keyword)<br>                                                            <br>        elif self.curChar == &#39;\n&#39;: #newline token<br>            token = Token (self.curChar, TokenType.NEWLINE)<br>        elif self.curChar == &#39;\0&#39;:<br>            token = Token (&quot;&quot;, TokenType.EOF)<br>        else:<br>            #unknown token!<br>            self.abort (&quot;Unknown token: &quot; + self.curChar)<br>        self.nextChar()<br>        return token</pre><p>And with that, the lexer was completed. The next step was the parser.</p><h3>Building the Parser</h3><p>With the lexer in place, the next step was to build the parser. While the lexer breaks the source code into discrete tokens, the parser’s job is to analyze how these tokens fit together according to the syntax (grammar) of <em>Teeny Tiny</em>. This grammar is constructed into a visual known as the Abstract Syntax Tree (AST).</p><p><strong>What the Parser Does:<br></strong>1. <strong>Validate Syntax:</strong> The parser checks whether the tokens follow grammar we’ve defined (eg. allowing LET variable = expression, but not LET = variable)</p><p>2. <strong>Organize the Program</strong>: The parser converts linear tokens into a hierarchal structure, ensuring we know which tokens belong to which statements or expression.</p><p>3. <strong>Bridge to Code Generation</strong>: Once we identify a valid construct (eg. PRINT statement or WHILE loop), we can generate the corresponding output code on the fly</p><p><strong>The Grammar Rules</strong></p><p>Here are the grammar rules for the Teeny Tiny Language. If you’re not familiar with the Backus-Naur Form (which don’t worry, I wasn’t either before), it is the format in which the grammar rules are written below. Once the parser is implemented, each grammar rule is mapped to a function in Python code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5qq25NBoQNOUWraEViULHg.png" /></figure><p>The Abstract Syntax Tree (AST) of the grammar rules, look something similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6kqVL_WfFwega7_ZjIggqg.png" /></figure><p>While building the AST, I asked myself the question — why is it structured this way, and why is it split up into 5 grammar rules? The answer is precedence. It’s necessary to include operators with higher precedence lower in the AST, whereas operators with lower precedence must be placed higher. That’s how BEDMAS will be adhered to as well.</p><p>First, I started off by initializing the constructor of the parser class.</p><pre>def __init__(self, lexer, emitter):<br>        self.lexer = lexer<br>        self.emitter = emitter <br>        <br>        #Note to self: the set() function in Python is used to create a set (an unordered collection of unique, hashable elements)<br>        self.symbols = set() #This is all the variables that have been declared so far<br>        self.labelsDeclared = set() #This is all the labels declared so far<br>        self.labelsGotoed = set() #This is all labels goto&#39;ed so far<br>        <br>        self.curToken = None<br>        self.peekToken = None<br>        self.nextToken()<br>        self.nextToken() #nextToken() is called twice so that it initializes current &amp; peak</pre><p>Next, I implemented a <em>checkToken </em>and <em>checkPeek </em>function that will let the parser decide which grammar rules to implement. The <em>match</em> function checks if the token matches with the current token, the <em>nextToken</em> function advancing the current token, and an <em>abort</em> function that prints a message if not parsed correctly.</p><pre>    #Returns true if the current token matches <br>    def checkToken (self, kind):<br>        return kind == self.curToken.kind #Note to self: this operation is an equality comparision which evaluates to a boolean (True if 2 values are equal, False if not)<br>    <br>    #Returns true if the next token matches <br>    def checkPeek (self, kind):<br>        return kind == self.peekToken.kind<br><br> #Trying to match current token. If not, error. Advances to the next token<br>    def match (self, kind):<br>        if not self.checkToken(kind):<br>            self.abort (&quot;Expected &quot; + kind.name + &quot;, got &quot; + self.curToken.kind.name)<br>        self.nextToken()<br>    <br>    #Advances the current token<br>    def nextToken (self):<br>        self.curToken = self.peekToken<br>        self.peekToken = self.lexer.getToken() #you don&#39;t need to parse through the EOF because the lexer handles that already<br>    <br>    def abort (self, message):<br>        sys.exit (&quot;Error! &quot; + message)</pre><p>Next, I had to implement the function that kicks off the parser and is the parent rule in the grammar.</p><pre>#Parsing Statements (Going through the grammar &amp; implementing a function for each rule) - this line checks whether the program is made up of 0 or more statements<br>    # program ::= {statement}<br>    def program (self):<br>        self.emitter.headerLine(&quot;#include &lt;stdio.h&gt;&quot;)<br>        self.emitter.headerLine(&quot;int main(void){&quot;)<br>        <br>        #Some newlines are required in the grammar, hence we need to skip over the excess <br>        while self.checkToken(TokenType.NEWLINE):<br>            self.nextToken()<br>        <br>        #Parse through all the statements in the program<br>        while not self.checkToken(TokenType.EOF):<br>            self.statement()<br>        <br>        #at the end of the C code<br>        self.emitter.emitLine (&quot;return 0;&quot;)<br>        self.emitter.emitLine (&quot;}&quot;)<br>        <br>        #Check that each label referenced in a GOTO is declared<br>        for label in self.labelsGotoed:<br>            if label not in self.labelsDeclared:<br>                self.abort (&quot;Attempting to GOTO to undeclared variable: &quot; + label)</pre><p>And then, I had to go back and implement a function for each grammar rule, 1 by 1. If a rule references another rule, it’ll call that function.</p><pre>#Next rule in grammar is &quot;statement&quot; which allows for 7 different types of rules. <br>    def statement(self):<br>        #Check the first token to see what kind of token it is<br>        <br>        #&#39;PRINT&#39; (expression | string)<br>        if self.checkToken(TokenType.PRINT):<br>            self.nextToken()<br>            <br>            if self.checkToken(TokenType.STRING):<br>                #simple string, so just print it<br>                self.emitter.emitLine (&quot;printf (\&quot;&quot; + self.curToken.text + &quot;\\n\&quot;);&quot;)<br>                self.nextToken()<br>                <br>            else:<br>                #expect an expression, therefore print the result as a float<br>                self.emitter.emit (&quot;printf (\&quot;%&quot; + &quot;.2f\\n\&quot;, (float)(&quot;)<br>                self.expression()<br>                self.emitter.emitLine (&quot;));&quot;)<br>        <br>        # &quot;IF&quot; comparision &quot;THEN&quot; {statement} <br>        elif self.checkToken (TokenType.IF):<br>            self.nextToken()<br>            self.emitter.emit (&quot;if(&quot;)<br>            self.comparision() #another grammar rule - comparision <br>            <br>            self.match(TokenType.THEN)<br>            self.nl()<br>            self.emitter.emitLine (&quot;){&quot;)<br>            <br>            #Zero or more statements in the body <br>            while not self.checkToken(TokenType.ENDIF):<br>                self.statement()<br>                <br>            self.match(TokenType.ENDIF)<br>            self.emitter.emitLine (&quot;}&quot;)<br>        <br>        #&quot;WHILE&quot; comparision &quot;REPEAT&quot; {statement} &quot;ENDWHILE&quot;<br>        elif self.checkToken (TokenType.WHILE):<br>            self.nextToken()<br>            self.emitter.emit(&quot;while(&quot;)<br>            self.comparision()<br>            <br>            self.match(TokenType.REPEAT)<br>            self.nl()<br>            self.emitter.emitLine (&quot;){&quot;)<br>            <br>            #Zero or more statements in the loop body<br>            while not self.checkToken(TokenType.ENDWHILE):<br>                self.statement()<br>            <br>            self.match(TokenType.ENDWHILE)<br>            self.emitter.emitLine (&quot;}&quot;)<br>        <br>        # &quot;LABEL&quot; ident <br>        elif self.checkToken(TokenType.LABEL):<br>            self.nextToken()<br>            <br>            #Ensure that the label doesn&#39;t already exist<br>            if self.curToken.text in self.labelsDeclared:<br>                self.abort (&quot;Label aready exists: &quot; + self.curToken.text)<br>            self.labelsDeclared.add(self.curToken.text)<br><br>            self.emitter.emitLine (self.curToken.text + &quot;:&quot;)<br>            self.match(TokenType.IDENT)<br>        <br>        # &quot;GOTO&quot; ident<br>        elif self.checkToken(TokenType.GOTO):<br>            self.nextToken()<br>            self.labelsGotoed.add(self.curToken.text) #Note to self: the .add() method is used in Python to add a single element to a set &amp; if the element already exists, will ignore duplicates<br>            self.emitter.emitLine (&quot;goto &quot; + self.curToken.text + &quot;;&quot;)<br>            self.match(TokenType.IDENT)<br>        <br>        # &quot;LET&quot; ident &quot;=&quot; expression <br>        elif self.checkToken (TokenType.LET):<br>            self.nextToken()<br>            <br>            #Check if the symbols exist in the symbol table, and if not - then make sure to declare it<br>            if self.curToken.text not in self.symbols:<br>                self.symbols.add(self.curToken.text)<br>                self.emitter.headerLine (&quot;float &quot; + self.curToken.text + &quot;;&quot;)<br>            <br>            self.emitter.emit(self.curToken.text + &quot; = &quot;)<br>            self.match(TokenType.IDENT)<br>            self.match(TokenType.EQ)<br>            <br>            self.expression()<br>            self.emitter.emitLine(&quot;;&quot;)<br>        <br>        <br>        #Note: There&#39;s a limitation to the &quot;Teeny Tiny&quot; language. You can&#39;t tell if the user input was the value 0 or an invalid input<br>        # &quot;INPUT&quot; ident =<br>        elif self.checkToken (TokenType.INPUT):<br>            self.nextToken()<br>            <br>            #if the variable doesn&#39;t already exist, declare it <br>            if self.curToken.text not in self.symbols:<br>                self.symbols.add (self.curToken.text) <br>                self.emitter.headerLine (&quot;float &quot; + self.curToken.text + &quot;;&quot;)<br>                <br>            #Emit scanf but also validate the input. If it&#39;s invalid, then set the variable to 0 and clear the input<br>            self.emitter.emitLine (&quot;if(0 == scanf(\&quot;%&quot; + &quot;f\&quot;, &amp;&quot; + self.curToken.text + &quot;)) {&quot;)<br>            self.emitter.emitLine (self.curToken.text + &quot; = 0;&quot;)<br>            self.emitter.emit (&quot;scanf(\&quot;%&quot;)<br>            self.emitter.emitLine (&quot;*s\&quot;);&quot;)<br>            self.emitter.emitLine (&quot;}&quot;)<br>            self.match(TokenType.IDENT)<br>                        <br>        #otherwise, it&#39;s not a valid statement so you want to print an error<br>        else:<br>            self.abort(&quot;Invalid statement at &quot; + self.curToken.text + &quot; (&quot;+ self.curToken.kind.name + &quot;)&quot;)<br>        #newline<br>        self.nl()<br>    <br>    #comparision ::= expression ((&quot;==&quot; | &quot;!=&quot; | &quot;&gt;&quot; | &quot;&gt;=&quot; | &quot;&lt;&quot; | &quot;&lt;=&quot;) expression)+<br>    def comparision (self):<br>        self.expression()<br>        <br>        #You must have atleast 1 comparision operator and another expression<br>        if self.isComparisionOperator():<br>            self.emitter.emit(self.curToken.text)<br>            self.nextToken()<br>            self.expression()<br>        <br>        #else:<br>        #    self.abort (&quot;Expected comparision operator at: &quot; + self.curToken.text)<br>            <br>        #You can have 0 or more comparision operator &amp; expressions<br>        while self.isComparisionOperator():<br>            self.emitter.emit (self.curToken.text)<br>            self.nextToken()<br>            self.expression()<br>        <br>    #Checks whether its a comparision operator or not (returns True if it is &amp; the type of comparision operator) <br>    def isComparisionOperator(self):<br>        return self.checkToken (TokenType.GT) or self.checkToken (TokenType.GTEQ) or self.checkToken (TokenType.LT) or self.checkToken (TokenType.LTEQ) or self.checkToken (TokenType.EQEQ) or self.checkToken (TokenType.NOTEQ)<br>    <br>    # expression ::= term {( &quot;-&quot; | &quot;+&quot; ) term}<br>    def expression (self):<br>        self.term()<br>        #You can have 0 or more (+/-) expressions<br>        while self.checkToken (TokenType.PLUS) or self.checkToken (TokenType.MINUS):<br>            self.emitter.emit(self.curToken.text)<br>            self.nextToken()<br>            self.term()<br>    <br>    # term ::= unary {( &quot;/&quot; | &quot;*&quot; ) unary}<br>    def term (self):<br>        self.unary()<br>        #can have 0 or more *// and expressions<br>        while self.checkToken (TokenType.ASTERISK) or self.checkToken (TokenType.SLASH):<br>            self.emitter.emit(self.curToken.text)<br>            self.nextToken()<br>            self.unary()   <br>    <br>    #unary ::= [&quot;+&quot; | &quot;-&quot;] primary<br>    def unary (self):        <br>        #optional unary +/-<br>        if self.checkToken (TokenType.PLUS) or self.checkToken (TokenType.MINUS):<br>            self.emitter.emit(self.curToken.text)<br>            self.nextToken()<br>        self.primary()<br>    <br>    #primary ::= number | ident<br>    def primary (self):<br>        <br>        if self.checkToken (TokenType.NUMBER):<br>            self.emitter.emit(self.curToken.text)<br>            self.nextToken()<br>        elif self.checkToken (TokenType.IDENT):<br>        <br>            #Ensure the variable already exists<br>            if self.curToken.text not in self.symbols:<br>                self.abort(&quot;Referencing variable before assignment: &quot; + self.curToken.text)<br>            <br>            self.emitter.emit(self.curToken.text)<br>            self.nextToken()<br>        else:<br>            #error<br>            self.abort (&quot;Unexpected token at &quot; + self.curToken.text)<br>        <br>    #Implementing the nl function that can handle newlines (called at the end of the statement function) - it expects 1 newline character but allows for more <br>    # nl ::= &#39;\n&#39;+<br>    def nl (self):<br>        #requiring atleast 1 type of newline<br>        self.match(TokenType.NEWLINE)<br>        #allows for extra newlines too <br>        while self.checkToken(TokenType.NEWLINE):<br>            self.nextToken()</pre><h3><strong>Implementing the Emitter</strong></h3><p>Compared to the parser, the emitter is relatively straightforward. Rather than having to understand the <em>Teeny Tiny </em>grammar, the emitter just needs to receive snippets of C code from the parser &amp; piece them together.</p><p><strong>How the Emitter Works</strong></p><ol><li><strong>Header vs. Main File</strong>: We keep 2 buffers — one for lines that must appear at the top of the final C file (eg. #include &lt;stdio.h&gt;, variable declarations) and another for the main code body</li><li><strong>Write to File</strong>: At the end, the header and the body are stitched together into a single .c file</li></ol><pre>#Enitter object will keep track of the generated code &amp; outputs it<br><br>#&#39;code&#39; is the string containing the C code that is emitted <br>#&#39;header&#39; contains things that will be prepended to the code<br>#&#39;fullPath&#39; is the path to write the file containing the C code<br><br><br>class Emitter:<br>    def __init__(self, fullPath):<br>        self.fullPath = fullPath<br>        self.header = &quot;&quot;<br>        self.code = &quot;&quot;<br>    <br>    #adds a fragment of C code <br>    def emit (self, code):<br>        self.code += code<br>    <br>    #adds a fragment that ends a line<br>    def emitLine (self, code):<br>        self.code += code + &#39;\n&#39;<br>    <br>    #adds a line of C code to the top of the C code file (ie. library header, main function, variable declarations)<br>    def headerLine (self, code):<br>        self.header += code + &#39;\n&#39;<br>    <br>    #writes the C code to a file<br>    def writeFile (self):<br>        with open (self.fullPath, &#39;w&#39;) as outputFile:<br>            outputFile.write(self.header + self.code)</pre><p>And that ends the journey of building the <em>Teeny Tiny Compiler! </em>If you’d like to see the entire code, here’s the link to my GitHub:</p><p><a href="https://github.com/krupadav3/tiny-compiler">GitHub - krupadav3/tiny-compiler</a></p><p>And here’s the original link to Austin Henley’s <em>Teeny Tiny Compiler</em>, if you’d like to follow along with my journey:</p><p><a href="https://austinhenley.com/blog/teenytinycompiler1.html">Let&#39;s make a Teeny Tiny compiler, part 1</a></p><h3>Endnotes</h3><ol><li>There are typically 6 stages of compiler design: Lexical Analysis, Syntax Analysis [Parsing], Semantic Analysis, Intermediate Code Generation, Code Optimization and Target Code Generation</li><li><strong>sys module </strong>in Python: provides various functions &amp; variables that are used to manipulate different parts of the Python runtime environment.</li></ol><p>Feel free to follow/reach out to me on other platforms:</p><p><em>LinkedIn</em>: <a href="https://www.linkedin.com/in/krupa-d/">https://www.linkedin.com/in/krupa-d/</a></p><p><em>X</em>: <a href="https://x.com/Krupa_Dave321">https://x.com/Krupa_Dave321</a></p><p><em>E-mail</em>: heyitskrupa@gmail.com</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd08b1cf42c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>