<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/">
  <channel>
    <title>Interpreter on Abdullah Diab&#39;s Blog</title>
    <link>https://mpcabd.xyz/tags/interpreter/</link>
    <description>Recent content in Interpreter on Abdullah Diab&#39;s Blog</description>
    <generator>Hugo</generator>
    <language>en-us</language>
    <lastBuildDate>Mon, 19 Oct 2009 22:31:17 +0000</lastBuildDate>
    <atom:link href="https://mpcabd.xyz/tags/interpreter/index.xml" rel="self" type="application/rss+xml" />
    <item>
      <title>Brainfuck Python Interpreter</title>
      <link>https://mpcabd.xyz/brainfuck-python-interpreter/</link>
      <pubDate>Mon, 19 Oct 2009 22:31:17 +0000</pubDate>
      <guid>https://mpcabd.xyz/brainfuck-python-interpreter/</guid>
      <description>&lt;h1 id=&#34;what-is-brainfuck&#34;&gt;What is brainfuck?&lt;/h1&gt;
&lt;p&gt;Brainfuck is a programming language&lt;img loading=&#34;lazy&#34; src=&#34;http://www.zu14.cn/coolemotion/emotions/zz_8.gif&#34;&gt;&lt;/p&gt;
&lt;p&gt;This is the definition from &lt;a href=&#34;http://en.wikipedia.org/wiki/Brainfuck&#34; target=&#34;_blank&#34;&gt;Wikipedia&lt;/a&gt;:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;The &lt;strong&gt;brainfuck&lt;/strong&gt; programming language is an &lt;a href=&#34;http://en.wikipedia.org/wiki/Esoteric_programming_language&#34;&gt;esoteric programming language&lt;/a&gt; noted for its extreme minimalism. It is a &lt;a href=&#34;http://en.wikipedia.org/wiki/Turing_tarpit&#34;&gt;Turing tarpit&lt;/a&gt;, designed to challenge and amuse &lt;a href=&#34;http://en.wikipedia.org/wiki/Programmer&#34;&gt;programmers&lt;/a&gt;, and is not suitable for practical use. Its name has been variously &lt;a href=&#34;http://en.wikipedia.org/wiki/Expurgation&#34;&gt;bowdlerized&lt;/a&gt;. The name of the language is generally not capitalized, although it is a &lt;a href=&#34;http://en.wikipedia.org/wiki/Proper_noun&#34;&gt;proper noun&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;This programming language is very easy to learn, very hard to do work with. As the &lt;a href=&#34;http://en.wikipedia.org/wiki/Brainfuck&#34; target=&#34;_blank&#34;&gt;Wikipedia article&lt;/a&gt; describes it; the language is an esoteric language, which means it was created for fun &lt;img loading=&#34;lazy&#34; src=&#34;http://www.zu14.cn/coolemotion/emotions/zz_14.gif&#34;&gt;&lt;/p&gt;
&lt;p&gt;I discovered the language while I was reading an article about &lt;a href=&#34;http://blog.damonjablons.com/2009/10/15/the-perfect-django-settings-file/&#34; target=&#34;_blank&#34;&gt;writing the perfect settings file for Django&lt;/a&gt;. The author used &lt;a href=&#34;http://dpaste.com/&#34; target=&#34;_blank&#34;&gt;DPaste&lt;/a&gt; website to link to pieces of code. DPaste website says that it uses &lt;a href=&#34;http://pygments.org/&#34; target=&#34;_blank&#34;&gt;Pygments&lt;/a&gt; for syntax highlighting. Pygments say that their syntax highlighter even supports &lt;a href=&#34;http://www.muppetlabs.com/~breadbox/bf/&#34; target=&#34;_blank&#34;&gt;brainfuck&lt;/a&gt;. And that’s how I got to brainfuck &lt;img loading=&#34;lazy&#34; src=&#34;http://www.zu14.cn/coolemotion/emotions/zz_2.gif&#34;&gt;&lt;/p&gt;
&lt;p&gt;After I read articles about the language I wanted to test some code of it, I found some &lt;a href=&#34;http://koti.mbnet.fi/villes/php/bf.php&#34; target=&#34;_blank&#34;&gt;online interpreters&lt;/a&gt;, but I wanted to test some code on my machine. I found a &lt;a href=&#34;http://home.arcor.de/partusch/html_en/bfd.html&#34; target=&#34;_blank&#34;&gt;compiler&lt;/a&gt; for it, but I’m using Windows 7 on my machine and the compiler is not compatible with it. I got pissed off and I decided I have to write my own interpreter &lt;img loading=&#34;lazy&#34; src=&#34;http://www.zu14.cn/coolemotion/emotions/zz_3.gif&#34;&gt;&lt;/p&gt;</description>
      <content:encoded><![CDATA[<h1 id="what-is-brainfuck">What is brainfuck?</h1>
<p>Brainfuck is a programming language<img loading="lazy" src="http://www.zu14.cn/coolemotion/emotions/zz_8.gif"></p>
<p>This is the definition from <a href="http://en.wikipedia.org/wiki/Brainfuck" target="_blank">Wikipedia</a>:</p>
<blockquote>
<p>The <strong>brainfuck</strong> programming language is an <a href="http://en.wikipedia.org/wiki/Esoteric_programming_language">esoteric programming language</a> noted for its extreme minimalism. It is a <a href="http://en.wikipedia.org/wiki/Turing_tarpit">Turing tarpit</a>, designed to challenge and amuse <a href="http://en.wikipedia.org/wiki/Programmer">programmers</a>, and is not suitable for practical use. Its name has been variously <a href="http://en.wikipedia.org/wiki/Expurgation">bowdlerized</a>. The name of the language is generally not capitalized, although it is a <a href="http://en.wikipedia.org/wiki/Proper_noun">proper noun</a>.</p>
</blockquote>
<p>This programming language is very easy to learn, very hard to do work with. As the <a href="http://en.wikipedia.org/wiki/Brainfuck" target="_blank">Wikipedia article</a> describes it; the language is an esoteric language, which means it was created for fun <img loading="lazy" src="http://www.zu14.cn/coolemotion/emotions/zz_14.gif"></p>
<p>I discovered the language while I was reading an article about <a href="http://blog.damonjablons.com/2009/10/15/the-perfect-django-settings-file/" target="_blank">writing the perfect settings file for Django</a>. The author used <a href="http://dpaste.com/" target="_blank">DPaste</a> website to link to pieces of code. DPaste website says that it uses <a href="http://pygments.org/" target="_blank">Pygments</a> for syntax highlighting. Pygments say that their syntax highlighter even supports <a href="http://www.muppetlabs.com/~breadbox/bf/" target="_blank">brainfuck</a>. And that’s how I got to brainfuck <img loading="lazy" src="http://www.zu14.cn/coolemotion/emotions/zz_2.gif"></p>
<p>After I read articles about the language I wanted to test some code of it, I found some <a href="http://koti.mbnet.fi/villes/php/bf.php" target="_blank">online interpreters</a>, but I wanted to test some code on my machine. I found a <a href="http://home.arcor.de/partusch/html_en/bfd.html" target="_blank">compiler</a> for it, but I’m using Windows 7 on my machine and the compiler is not compatible with it. I got pissed off and I decided I have to write my own interpreter <img loading="lazy" src="http://www.zu14.cn/coolemotion/emotions/zz_3.gif"></p>
<h2 id="brainfuck-in-simple-description">Brainfuck in simple description</h2>
<p>The language consists of 8 symbols &lt; &gt; . , + – [ ]</p>
<p>The language deals with a 30,000 bytes array, at the start of the application all the items of that array are zeros.</p>
<p>The symbols can just deal with a pointer on that array to do specific jobs.</p>
<h1 id="ply">PLY</h1>
<p>I mentioned in a <a href="http://mpcabd.xyz/binding-netbeans-with-flex/" target="_blank">previous post</a> that I’m implementing a compiler for my 4th year in Informatics faculty. Hence I made a lot of searching around the net for information about implementing compilers. Implementing a compiler requires building a lexer which can be generated using lexer generator tools, and a parser which also can be generated using parser generator tools.</p>
<p>Since I’m a Python-Lover I searched for Python lexer and parser tools, and I came across the great PLY.</p>
<p><a href="http://www.dabeaz.com/ply/" target="_blank">PLY (Python Lex-Yacc)</a> is an implementation of lex and yacc parsing tools for Python.</p>
<p>The usage of PLY is not the target of this post.</p>
<h1 id="writing-a-lexer-for-brainfuck">Writing a lexer for brainfuck</h1>
<p>The lexer would be so simple, since the language only has 8 symbols, and capturing them requires almost nothing.</p>
<p>The lexer file is the following</p>
<pre class="lang:python decode:true">import ply.lex as lex

tokens = [
    'GoLeft',
    'GoRight',
    'Print',
    'Read',
    'Increase',
    'Decrease',
    'WhileStart',
    'WhileEnd'
]

t_GoLeft = r'\&lt;'
t_GoRight = r'\&gt;;'
t_Print = r'\.'
t_Read = r','
t_Increase = r'\+'
t_Decrease = r'\-'
t_WhileStart = r'\['
t_WhileEnd = r'\]'

def t_error(t):
    t.lexer.skip(1)

lexer = lex.lex()

if __name__ == "__main__":
    lex.runmain()
</pre>
<p>It simply captures the symbols of the language and ignores any other symbol. Simple isn’t it 🙂</p>
<h1 id="writing-a-parser-for-brainfuck">Writing a parser for brainfuck</h1>
<p>The parser will have to capture the instructions and store them in a tree so that it can do operations on the code without too much efforts.</p>
<p>The parser will ask the lexer to capture the symbols, while the parser will be responsible for making instructions from symbols.</p>
<h2 id="sparse-matrix">Sparse matrix</h2>
<p>I won’t actually allocate 30,000 bytes array for the application, and since the default value for any item is 0 then I can make use of the <a href="http://en.wikipedia.org/wiki/Sparse_matrix" target="_blank">Sparse Matrix</a>.</p>
<p>Implementing a simple sparse matrix is nothing more than a dictionary:</p>
<pre class="lang:python decode:true">class sparseMatrix:
    def __init__(self):
        self.dict = {}

    def __getitem__(self, index):
        if self.dict.has_key(index):
            return self.dict[index]
        else:
            return 0

    def __setitem__(self, index, value):
        self.dict[index] = value
</pre>
<h2 id="building-the-tree">Building the tree</h2>
<p>Six commands from the brainfuck language have no arguments or any other elements attaching to them, so they would just add elements containing the command type.</p>
<p>While two commands have a scope of code attached with them, the “[“ and “]” can be used to define while loops. So the while loop is the only command that will add an element with sub-level to the tree.</p>
<pre class="lang:python decode:true">def p_start(p):
    """
    start : code
            | empty
    """
    if p[1]:
        executeStatements(p[1])

def p_empty(p):
    'empty : '
    pass

def p_code(p):
    """
    code : code statement
            | code whilestatement
            | statement
            | whilestatement
    """
    if len(p) == 2:
        p[0] = [p[1]]
    else:
        p[0] = p[1][:]
        p[0].extend([p[2]])

def p_statement(p):
    """
    statement : GoLeft
                   | GoRight
                   | Print
                   | Read
                   | Increase
                   | Decrease
    """
    if p[1] == '&lt;':
        p[0] = ('GoLeft', None)
    elif p[1]  == '&gt;':
        p[0] = ('GoRight', None)
    elif p[1] == '.':
        p[0] = ('Print', None)
    elif p[1] == ',':
        p[0] = ('Read', None)
    elif p[1] == '+':
        p[0] = ('Increase', None)
    elif p[1] == '-':
        p[0] = ('Decrease', None)

def p_whilestatement(p):
    'whilestatement : WhileStart code WhileEnd'
    p[0] = ('While', p[2])
</pre>
<h2 id="executing-the-tree">Executing the tree</h2>
<p>Since I’m not building a real compiler I won’t have to generate machine specific code after building the tree. I decided that I can execute the code from within python since the code is too simple to be executed.</p>
<p>So I wrote a method to execute a list of tree elements and it can execute while loops using recursive calling to itself.</p>
<p>The method will be called when the parser parses a valid application and when it can recognize the start symbol of the generating rules of the language.</p>
<pre class="lang:python decode:true">def executeStatements(tuplesList):
    global matrix
    global index
    global MAX_INDEX

    for node in tuplesList:
        if node[0] == 'GoLeft':
            if index &gt; 0:
                index -= 1
            else:
                raise Exception, "Index out of array bounds!"
        elif node[0] == 'GoRight':
            if index &lt; MAX_INDEX:
                index += 1
            else:
                raise Exception, "Index out of array bounds!"
        elif node[0] == 'Print':
            print(chr(matrix[index]), sep='', end='')
        elif node[0] == 'Read':
            matrix[index] = ord(raw_input()[0])
        elif node[0] == 'Increase':
            matrix[index] += 1
        elif node[0] == 'Decrease':
            matrix[index] -= 1
        elif node[0] == 'While':
            while matrix[index] != 0:
                executeStatements(node[1])
</pre>
<h1 id="testing-the-interpreter">Testing the interpreter</h1>
<p>After running the interpreter, I tried the <a href="http://en.wikipedia.org/wiki/Brainfuck#Hello_World.21" target="_blank">Hello World example in Wikipedia</a> and I got the result:</p>
<pre class="lang:python decode:true">BrainFuck&gt; ++++++++++[&gt;+++++++&gt;++++++++++&gt;+++&gt;+&lt;&lt;&lt;&lt;-]&gt;++.&gt;+.+++++++..+++.&gt;++.&lt;&lt;+++++++++++++++.&gt;.+++.------.--------.&gt;+.&gt;.
Hello World!
BrainFuck&gt;
</pre>
<h1 id="download-source-code">Download source code</h1>
<p>You can download and test the interpreter from <a href="http://www.box.net/shared/jaranfgyz1" target="_blank">here</a>.</p>]]></content:encoded>
    </item>
  </channel>
</rss>
