<?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 Mirasma on Medium]]></title>
        <description><![CDATA[Stories by Mirasma on Medium]]></description>
        <link>https://medium.com/@mirasma?source=rss-9c7164dd6d8a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*UFLyf63sAhjAXvqS</url>
            <title>Stories by Mirasma on Medium</title>
            <link>https://medium.com/@mirasma?source=rss-9c7164dd6d8a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 11:08:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mirasma/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[Creating a Mini C Compiler using Lex and Yacc [Part 1]]]></title>
            <link>https://medium.com/@mirasma/creating-a-mini-c-compiler-using-lex-and-yacc-part-1-963b0860f5b1?source=rss-9c7164dd6d8a------2</link>
            <guid isPermaLink="false">https://medium.com/p/963b0860f5b1</guid>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[lex]]></category>
            <category><![CDATA[c]]></category>
            <category><![CDATA[yacc]]></category>
            <category><![CDATA[programming-languages]]></category>
            <dc:creator><![CDATA[Mirasma]]></dc:creator>
            <pubDate>Sat, 06 May 2023 19:29:12 GMT</pubDate>
            <atom:updated>2023-05-07T04:24:38.695Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you wondered how a compiler is written? Do you want to learn how to use lex and yacc to write a compiler? Great timing!</p><h3>About this series</h3><p>In this series of posts, we will create a small compiler that compiles a subset of C, and then we will build a “virtual machine” that executes the compiled instructions.</p><p>I will try to include all details in the posts, but if something doesn’t work or is mistakenly left out, check the <a href="https://github.com/Akshat-Oke/Mini-C">GitHub repository</a> for the full code.</p><h3>Contents</h3><p>· <a href="#9340">Mini C, our language</a><br> ∘ <a href="#a518">Pre-requisites</a><br> ∘ <a href="#53ac">Lex and Yacc</a><br>· <a href="#d744">The Flow</a><br>· <a href="#b71e">Lex</a><br>· <a href="#c61d">Tokens</a><br> ∘ <a href="#07b3">Token Types</a><br>· <a href="#f5fe">tokenizer.l</a><br> ∘ <a href="#cf9f">Keywords and Symbols</a><br> ∘ <a href="#4018">Numbers and Characters</a><br> ∘ <a href="#8143">Identifiers</a><br> ∘ <a href="#aaf9">Strings</a><br> ∘ <a href="#2e2c">Comments</a><br> ∘ <a href="#b0e6">Whitespace</a><br> ∘ <a href="#2f64">Strapping with Main</a><br>· <a href="#de7d">Conclusion</a><br>· <a href="#5aab">Final Code</a></p><h3>Mini C, our language</h3><p>Before building the compiler, let’s establish what the language is. Here is an example program that can be compiled and run:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_m-1OsFKTifSKnKatYzijg.png" /><figcaption>Mini C Example Program</figcaption></figure><p>We will go through implementing function calls, adding native functions printf() and time() , multi-dimensional arrays and floating point numbers.</p><p>Exciting? Well, whip up your favourite editor, slap on your playlist and fill your coffee mug. Setting the mood, you know.</p><h4>Pre-requisites</h4><p>Well, before we get going, let’s make sure we are all on the same page. Here are a couple of things you should be familiar of:</p><p>First, the general stages of a compiler, namely Lexical Analysis, Syntax Analysis, Semantic Analysis, Code generation, and Optimization. You can read more about these <a href="https://www.geeksforgeeks.org/introduction-of-compiler-design/">here.</a></p><p>Second, regular expressions and grammar. Read what a programming language grammar is <a href="https://pgrandinetti.github.io/compilers/page/what-is-a-programming-language-grammar/">on this page</a> and about <a href="https://en.wikipedia.org/wiki/Regular_expression">regular expressions here.</a></p><h4>Lex and Yacc</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jSNKHS3Sc6R5tb2U" /><figcaption>A Yak, by <a href="https://unsplash.com/@quaritsch?utm_source=medium&amp;utm_medium=referral">Quaritsch Photography</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>You also need Lex and Yacc installed on your OS. A short guide on using these tools can be read here: <a href="https://arcb.csc.ncsu.edu/~mueller/codeopt/codeopt00/y_man.pdf">https://arcb.csc.ncsu.edu/~mueller/codeopt/codeopt00/y_man.pdf</a>.</p><h3>The Flow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PqPnli2XIhDCrhun3I4qRQ.png" /><figcaption>The compiler flow</figcaption></figure><p>Here is the structure of the compiler. The frontend phase contains Lex and Yacc, which generates the Intermediate Representation in the form of Three Address Code and passes it over to the backend. The backend phase then takes the IR and executes it. We can put the optimisation and machine code generation phases here.</p><blockquote>Actually, Yacc calls upon the lexer generated by Lex to tokenize the input stream.</blockquote><blockquote>yylex is called repeatedly by yyparse to get the next token and determine what action to perform based on the grammar. We will delve deeper into this process in the next part of the series.</blockquote><h3>Lex</h3><p>Lex is a program that generates scanners, also known as tokenizers, that recognise text lexical patterns. Lex is commonly used with the yacc parser generator.</p><p>You can say that Lex is a glorious Regex Engine. Getting a bit fancy, Lex is a paragon of virtuosity in the world of regex engines, but its prowess extends far beyond mere pattern matching. In fact, this powerful tool boasts a plethora of additional features that make it a revered asset in the realm of lexical analysis.</p><blockquote>There are other alternatives to lex and yacc now, though, like ANTLR or other parser generators and parser combinators. <a href="https://softwareengineering.stackexchange.com/questions/338665/when-to-use-a-parser-combinator-when-to-use-a-parser-generator">This stackoverflow answer</a> describes the differences between the two.</blockquote><p>Lex takes in a specification file and produces C code that matches the regexes in the input file and performs actions according to the string matched. You can write C code in the input file that will be directly copied to the output file.</p><p>The specification file defines the rules for matching the input text. This file consists of three sections: definitions, rules, and user code. You can declare variables, macros, and regular expressions in the definitions section. The rules section is where you specify the patterns to match and the actions to perform when a match is found. In the user code section, you can write any additional C code you need for your scanner.</p><pre>definitions<br>%%<br>rules<br>%%<br>user code</pre><p>Since this is not a Lex guide, I won’t go into further details and features of Lex. Check out <a href="https://westes.github.io/flex/manual/index.html#Top">this flex manual</a>; it has excellent examples and explanations.</p><h3>Tokens</h3><p>We need tokens, but what <em>are </em>they?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*42OjRICPfDxPO7hcQCP_Vg.png" /><figcaption>Tokens for a statement</figcaption></figure><p>The figure above shows the tokens for a statement int arr[] = {1};</p><p>In short, tokens break the code into symbols, identifiers and literals (like numbers and strings) while ignoring comments and whitespace.</p><blockquote>How many tokens will the following line be split into?</blockquote><pre>char str[5] = &quot;abcd&quot;;</pre><blockquote>Answer: 8</blockquote><h4>Token Types</h4><p>Each token has a <em>token type</em>. This type represents what class the token belongs to. A class can be as broad as a keyword. The substring of the source code that the token represents is called its <strong><em>lexeme. </em></strong>Thus, the lexeme of a number type token will be, for example, the string 1.23 . The lexeme of a keyword is the keyword itself.</p><p>Although Lex is used to tokenize the source, the tokens are declared in the Yacc file. Create a file named parser.y to write the token types.</p><blockquote>No need to panic if you don’t know Yacc! Stick around for the next part where we will dive into the finer details. Or if you are bold and impatient enough, here is a handy <a href="https://www.gnu.org/software/bison/manual/html_node/index.html">starting point</a>.</blockquote><p>Every token in Yacc has a <em>value </em>associated with it. For an integer, the value is the integer value. This is stored in the yylval variable that is declared in the lex file.</p><p>Since we need to deal with a variety of Token values (integer, floating, character, strings), we define a union as the yylval datatype. This is done using the %union command in Yacc.</p><pre> /* File: parser.y */<br>%{<br>#include &lt;stdio.h&gt;<br>#include &lt;stdlib.h&gt;<br>char *currentFileName;<br>extern int lineno, col;<br>int yyerror(char *s);<br>int yylex();<br>%}<br><br>%union {<br>    int iValue;<br>    float fValue;<br>    char* sValue;<br>    IdStruct id;<br>    char cValue;<br>};<br><br>/* Keywords */<br>%token &lt;iValue&gt; K_INT K_FLOAT K_CHAR <br>%token FOR WHILE ELSE IF SWITCH CASE RETURN CONTINUE BREAK DEFAULT<br>/* Literals */<br>%token &lt;iValue&gt; INTEGER <br>%token &lt;fValue&gt; FLOAT<br>%token &lt;cValue&gt; CHARACTER<br>%token &lt;sValue&gt; STRING<br>/* Variables and functions */<br>%token &lt;id&gt; IDENTIFIER<br>/* Operators &amp;&amp; || &gt;= &lt;= == != */<br>%token AND OR GE LE EQ NE<br>/* Other operators are returned as ASCII */<br><br>/* End of file token */<br>%token EOF_TOKEN<br><br>%%<br>/* Dummy grammar */<br>program: IDENTIFIER;<br>%%<br>// Error routine<br>int yyerror(char *s){<br>  exit(1);<br>  return 1;<br>}</pre><p>As evident as it can be, the %token defines the tokens in the parser. The token type is specified in the angled brackets, referring to one of the variables from the %uniondeclaration.</p><blockquote>Yacc calls the function yyerror on encountering a parsing error. You can read more about these yy- functions <a href="https://arcb.csc.ncsu.edu/~mueller/codeopt/codeopt00/y_man.pdf">here</a>.</blockquote><p>You should have noticed the identifier variable is id with a type IdStruct . This struct is defined in the symbol.h file and looks like this:</p><pre>// File: symbol.h <br>#ifndef __SYMBOL<br>#define __SYMBOL<br><br>// Stores the coordinate in source file<br>typedef struct<br>{<br>  // Length is for an expression<br>  unsigned int line, col, length;<br>} Coordinate;<br>// Token type for an identifier<br>typedef struct<br>{<br>  Coordinate src; // used for error reporting<br>  char *name; //copied string (pointer)<br>} IdStruct;<br><br>#endif</pre><p>Yacc generates a header file named y.tab.h with the declared tokens as members of an enumeration. To generate this header file, run yacc -d parser.y .</p><h3>tokenizer.l</h3><p>Let’s get started on our tokenizer. This will chop up our source code into tokens defined earlier and pass them over to the parser. The parser then uses these tokens to generate the parse tree according to the grammar.</p><p>First, we begin with the definitions section of the specification file.</p><pre> /* tokenizer.l */<br>%{<br>#include &lt;stdio.h&gt;<br>#include &lt;string.h&gt;<br>#include &lt;math.h&gt;<br>#include &lt;stdlib.h&gt;<br>#include &quot;symbol.h&quot;<br>#include &quot;y.tab.h&quot;<br><br>#define MAX_STR_CONST 1000<br>#define yyterminate() return EOF_TOKEN<br>/* YY_USER_ACTION is called after<br>matching a pattern and before executing the action */<br>#define YY_USER_ACTION \<br>  col += yyleng;<br>extern char *currentFileName;<br>int col = 1; //track the current column<br>int lineno = 1;<br>int yyerror(char* s);<br>%}</pre><p>MAX_STR_CONST is the max length of a string literal in Mini C. yyterminate() defines the function to terminate the lexer. This returns the End Of File token.</p><p>Next, define a few helper regex patterns:</p><pre>%}<br><br>alpha [a-zA-Z]<br>alphanum [a-zA-Z0-9]<br>digit [0-9]<br>nonzero [1-9]<br>%%</pre><p>This completes the definitions part. We will return here to add a few more things to handle strings and comments, but that’s for later.</p><h4>Keywords and Symbols</h4><p>Welcome to the <strong>Rules</strong> section! Here we lay out our tokenizer building brick by brick.</p><p>Since yylval is a union defined by %union in parser.y , we have to carefully set the right field of the union.</p><p>Keywords and symbols are very simple: just return what you match. Here are the match patterns:</p><pre>%%<br>      char string_buf[MAX_STR_CONST]; /* to store strings */<br>      char *string_buf_ptr;<br><br>  /* Keywords */<br>&quot;int&quot; {return K_INT;} <br>&quot;float&quot; {return K_FLOAT;}<br>&quot;char&quot; {return K_CHAR;} <br>&quot;for&quot; {return FOR;} <br>&quot;while&quot; {return WHILE;} <br>&quot;else&quot; {return ELSE;} <br>&quot;if&quot; {return IF;} <br>&quot;switch&quot; {return SWITCH;} <br>&quot;case&quot; {return CASE;} <br>&quot;return&quot; {return RETURN;}<br>&quot;continue&quot; {return CONTINUE;}<br>&quot;break&quot; {return BREAK;}<br>&quot;default&quot; {return DEFAULT;}<br><br> /* Symbols <br>    Return the first character of the matched string<br> */<br>[-+*/%] return *yytext;<br>[;,:()] return *yytext;<br>[\{\}\[\]] return *yytext;<br>[=!&lt;&gt;] return *yytext;<br>  /* Lex always executes the longest match action */<br>&quot;==&quot; {return EQ;}<br>&quot;&gt;=&quot; {return GE;}<br>&quot;&lt;=&quot; {return LE;}<br>&quot;!=&quot; {return NE;}<br><br>&quot;&amp;&amp;&quot; {return AND;}<br>&quot;||&quot; {return OR;}</pre><p>On calling yylex() , lex will go through these patterns and execute the action for the pattern that matches the longest string.</p><h4>Numbers and Characters</h4><p>Here is the regex pattern to match integers and floating numbers:</p><pre>  /* Integers */<br>0 {yylval.iValue = 0; return INTEGER;}<br>{nonzero}({digit})*([eE][-+]?[0-9]+)? {<br>      yylval.iValue = (int)round(atof(yytext)); return INTEGER;}<br><br>  /* Floats */<br>{nonzero}({digit})*&quot;.&quot;({digit})*([eE][-+]?[0-9]+)? {<br>      yylval.fValue = atof(yytext); return FLOAT;}<br><br>  /* Characters */<br>&quot;\&#39;&quot;({alpha}|{digit})&quot;\&#39;&quot; {yylval.cValue = yytext[1]; return CHARACTER;}</pre><p>The action part sets the iValue or fValue field accordingly and returns the type of token ( INTEGER or FLOAT )</p><blockquote>yytext <em>points to the current matched substring of the source string. It has to be parsed into an integer or floating point number using the standard library functions </em><em>atoi (argument to int) and </em><em>atof</em></blockquote><h4>Identifiers</h4><p>An identifier token will capture the identifier string and pass it to the parser. This captured string will stick around throughout the lifetime of the compiler.</p><pre>  /* Identifiers */<br>(_|{alpha})((_|{alphanum}))* {<br>  yylval.id.name = malloc(strlen(yytext)+1);<br>  yylval.id.src.line = lineno;<br>  yylval.id.src.col = col - yyleng;<br>  // yylval.name = malloc(strlen(yytext)+1);<br>  strcpy(yylval.id.name, yytext);<br>  // strcpy(yylval.name, yytext);<br>  return IDENTIFIER;  <br>}</pre><h4>Strings</h4><p>For strings, we use start conditions in lex. To define a start condition, place the definition in the definitions section.</p><pre>%x str<br>%x comment single_line_comment /* for comments */</pre><p>These are exclusive start conditions, meaning that other rules won’t be matched when these conditions are active. To parse strings, we BEGIN the str condition on seeing the first &quot; and keep adding characters to the buffer till the closing &quot; is not seen.</p><pre>/* Strings*/<br>\&quot; { string_buf_ptr = string_buf; BEGIN(str);}<br>&lt;str&gt;\&quot; {<br>  BEGIN(INITIAL);<br>  *string_buf_ptr = &#39;\0&#39;;<br>  yylval.sValue = (char*)malloc(strlen(string_buf)+1);<br>  strcpy(yylval.sValue, string_buf);<br>  return STRING;<br>}<br>&lt;str&gt;\n {yyerror(&quot;Unterminated string.\n&quot;); return ERROR;}<br>&lt;str&gt;\\n {*string_buf_ptr++ = &#39;\n&#39;;}<br>&lt;str&gt;[^\n] {<br>  *string_buf_ptr++ = *yytext;<br>}</pre><blockquote>There is no support for escape characters except \n , but if you are feeling adventurous enough, have a go at adding other escape sequences like \&quot;</blockquote><h4>Comments</h4><p>Comments are treated as whitespace and ignored by the tokenizer. Again, we use start conditions to ignore characters inside the comment.</p><pre>  /* Comments*/<br>&quot;//&quot; BEGIN(single_line_comment);<br>&lt;single_line_comment&gt;&quot;\n&quot; {col = 1; lineno++; BEGIN(INITIAL);}<br>&lt;single_line_comment&gt;&lt;&lt;EOF&gt;&gt; {BEGIN(INITIAL); return EOF_TOKEN;}<br>&lt;single_line_comment&gt;[^\n]+ ;<br><br>&quot;/*&quot; BEGIN(comment);<br>&lt;comment&gt;&quot;\n&quot; {col = 1; lineno++;}<br>&lt;comment&gt;&quot;*/&quot; {BEGIN(INITIAL);}<br>&lt;comment&gt;&lt;&lt;EOF&gt;&gt; {yyerror(&quot;Unclosed comment found\n&quot;);}<br>&lt;comment&gt;. ;</pre><h4>Whitespace</h4><p>It’s sad, but we have to do it. Ignore whitespace. And raise an error on any other character.</p><pre>  /* Whitespace */<br>[ \t\r] ;<br>\n {col = 1; lineno++;}<br><br>. {yyerror(&quot;Error: Invalid character&quot;); return ERROR;}</pre><h4>Strapping with Main</h4><p>Almost done! Wrap up the tokenizer by closing the rules section like so:</p><pre><br>%%<br>int yywrap(){<br>  yyterminate();<br>  return EOF_TOKEN;<br>}</pre><p>And create a file main.c that will read tokens from a file:</p><pre>//File main.c<br>#include &lt;stdio.h&gt;<br>#include &lt;stdlib.h&gt;<br>#include &quot;symbol.h&quot;<br>#include &quot;y.tab.h&quot;<br>// The current line number.<br>// This is from tokenizer.l.<br>extern int lineno;<br>extern FILE *yyin;<br>// Current token&#39;s lexeme<br>extern char *yytext;<br>// The source file name<br>extern char *currentFileName;<br>// From lex.yy.c, returns the next token.<br>// Ends with EOF<br>int yylex();<br><br>int main()<br>{<br>  yyin = fopen(&quot;input.txt&quot;, &quot;r&quot;);<br>  int token;<br>  while ((token = yylex()) != EOF_TOKEN)<br>  {<br>    printf(&quot;Token: %d: &#39;%s&#39;\n&quot;, token, yytext);<br>  }<br>  return 0;<br>}</pre><p>Create a file input.txt and enter your sample program.</p><pre>// input.txt<br>int a = 3;<br>while(a){<br>   printf(&quot;%d&quot;, a);<br>}</pre><p>Compile by running:</p><pre>&gt; yacc -d parser.y<br>&gt; lex tokenizer.l<br>&gt; gcc y.tab.c lex.yy.c main.c -ll -lm<br>&gt; ./a.out</pre><p>And there’s your output!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9F2W4T6phEFnW2QKBX2lqQ.png" /><figcaption>Tokens for input.txt</figcaption></figure><h3>Conclusion</h3><p>Awesome job, you now have your own tokenizer!</p><p>Although I have used very little of what Lex offers, it is worth going through one of the links above (find them!😄) and maybe adding or modifying a few tokens yourself.</p><p>In the next part, we shall write the grammar and be able to determine if the given program has valid syntax or not. Till then, happy coding!</p><h3>Final Code</h3><p>I have added a few more functions to report errors in the source program. When an invalid character is detected, yyerror calls the point_at_in_line function with the current column and line numbers. This reads the source file and prints the given line and column number in a pleasing manner.</p><blockquote>The complete source code of the compiler is available on GitHub.</blockquote><p><a href="https://github.com/Akshat-Oke/Mini-C">GitHub - Akshat-Oke/Mini-C: A compiler for a subset of C, made using lex and yacc</a></p><p><em>If you found this useful, please give it a 👏 to show your support and help others discover it too! Don’t be shy to leave a comment; your feedback is valuable to me and helps me improve. Thank you for reading!</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4c113b22fd4e41a133ae2d602c5ddb9/href">https://medium.com/media/a4c113b22fd4e41a133ae2d602c5ddb9/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=963b0860f5b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>