<?xml version="1.0"?>
<rss version="2.0">
   <channel>
      <title>AlephNullPlex RSS Feed</title>
      <link>http://alephnullplex.appspot.com/</link>
      <description>AlephNullPlex RSS Feed</description>
      <language>en-us</language>
      <pubDate>Tue, 7 Jul 2015 12:12:02 +0000</pubDate>
      <lastBuildDate>Tue, 7 Jul 2015 12:12:02 +0000</lastBuildDate>
      <generator>AlephNullBlog 0.1</generator>
      <managingEditor>g_ford@hotmail.com</managingEditor>
      <webMaster>g_ford@hotmail.com</webMaster>
	  
      <item>
         <title>Slipping Rails3 into the enterprise</title>
         <link>http://alephnullplex.appspot.com/blog/view/2011/01/31/slipping-rails3-into-the-enterprise</link>
         <description>
			<![CDATA[
			<p>Today I realised that one of our new quality monitoring applications, <a href="http://www.sonarsource.org/">Sonar</a>, which we deploy to a Tomcat server, is actually a Rails application.  This intrigued me a lot. We have a very heavy Java culture at work, whilst I have a backgound in, shall we say, simpler, less enterprisey technologies.  This lead me to figure out how easy it was to get Rails up and running on JRuby.</p>

<h2>JRuby</h2>

<p>We'll install Ruby along side of JRuby, but we will stick to Ubunutu's currently supported 1.8 as this is compatiple with JRuby.  This way we can develop an application that is deployable on JRuby and Ruby giving a bit of flexibility.</p>

<pre><code>sudo apt-get install jruby ruby-full rubygems
</code></pre>

<p>Then we will install Rails 3. To do this we will first need to update RubyGems.</p>

<pre><code>sudo jruby -S gem update --system
sudo jruby -S gem install rails
</code></pre>

<h2>JRuby and Rails</h2>

<p>The hardest part about setting up a Rails app for use with JRuby is the database gems are different.  Thankfully the JRuby guys have made this real easy by providing a template.</p>

<pre><code>jruby -S rails new myapp -m http://jruby.org/rails3.rb -d mysql
</code></pre>

<p>Inspecting <code>myapp/Gemfile</code> shows that there are two <code>platforms</code> blocks with different gems for ruby and jruby. I recommend changing the jruby block to:</p>

<pre><code>gem 'activerecord-jdbc-adapter'
gem 'activerecord-jdbcmysql-adapter'
gem 'jdbc-mysql'
gem 'jruby-openssl'
gem 'jruby-rack'
</code></pre>

<p>So now we can go ahead and install everything needed by running from the root of <code>myapp</code>:</p>

<pre><code>sudo jruby -S bundle install
</code></pre>

<p>Now, with all the imagination that it entails, we'll create the standard Post example and set up the databases. </p>

<p>First update <code>conf/database.yml</code> to reflect your settings. You will also need to update all instances of <code>adatapter: mysql</code> to:</p>

<pre><code>adapter: &lt;%= defined?(JRUBY_VERSION) ? 'jdbcmysql' : 'mysql' %&gt;
</code></pre>

<p>This puts a conditional in so that if your app is deployed on JRuby it will use the jdbc drivers.  I had some major issues using <code>jruby -S rake</code> to do migrations, so this allowed me to use the regular <code>rake</code> to do my migrations.</p>

<p>Then we will create a basic Post scaffold and set up the databases for our Posts.</p>

<pre><code>jruby -S rails generate scaffold Post name:string title:string content:text
jruby -S rake db:create:all
rake db:migrate
rake db:migrate RAILS_ENV="production"
</code></pre>

<p>We can then test the development environment by running </p>

<pre><code>jruby -S rails server
</code></pre>

<p>At <a href="http://localhost:3000">http://localhost:3000</a> you should have something similar to:</p>

<p><img src="http://lh3.ggpht.com/_o7UGh0w8Xcc/TUZC_o5GAGI/AAAAAAAAAHI/0pxRaObX1ms/s640/Rails-on-Jruby.png" style="text-align:center" /></p>

<p>Note that the Ruby version <code>1.8.7 (java)</code> which indicates that it is running on JRuby, and that the Database Adapter is <code>jdbcmysql</code>. You can make sure that the database is working by playing around at <a href="http://localhost:3000/posts">http://localhost:3000/posts</a></p>

<h2>Deploying</h2>

<p>With JRuby we can package up the Rails app as a war file so that it can be deployed to all the regular containers in the same manner as a 'real' Java application.  <a href="http://caldersphere.rubyforge.org/warbler/">Warbler</a> is a simple gem that will do all the magic and hard work. From the root of of your Ruby application</p>

<pre><code>sudo jruby -S warble
</code></pre>

<p>This will create a file myapp.war in the root of myapp. Note that warbler will set you config to production automatically, which is why we did the produciton migration earlier.  Assuming you want to deploy to a standard Tomcat 6 on Ubuntu you can run:</p>

<pre><code>sudo cp myapp.war /var/lib/tomcat6/webapps/
sudo chmod 777 myapp.war
sudo /etc/init.d/tomcat6 restart
</code></pre>

<p>It seems that the default home page used for the developement server is not reproduced in the production configuration, so you may get a routing error at <a href="http://localhost:8080/myapp">http://localhost:8080/myapp</a> but you should now have a working scaffold at <a href="http://localhost:8080/myapp/posts">http://localhost:8080/myapp/posts</a>.  You can verify that warbler automatically used your production settings by manually checking the <code>myapp_production</code> database after entering a few Posts in your applicaiton.</p>

<h2>Resources</h2>

<p>Most of this was adapted from <a href="http://gregmoreno.ca/deploy-a-rails-3-sqlite3-application-in-tomcat-using-jruby/">Deploy a Rails 3, Sqlite3 application in Tomcat using JRuby 
</a> by Greg Morneo.</p>

			]]>
		</description>
         <pubDate>Mon, 31 Jan 2011 05:46:56 +0000</pubDate>
         <guid>http://alephnullplex.appspot.com/blog/view/2011/01/31/slipping-rails3-into-the-enterprise</guid>
      </item>
	  
      <item>
         <title>Let's build a compiler (in Haskell): Part 12 - Loops</title>
         <link>http://alephnullplex.appspot.com/blog/view/2010/10/28/lbach-loops</link>
         <description>
			<![CDATA[
			<p>There are a few kinds of loops in your average imperitive langauage.  There are pre and post-condition loops, loops which you can break out of the middle and then there a loops that iterate over a collection.</p>

<p>We'll progress through these in increasing difficulty. Starting with an infinite loop, through to your standard <code>for</code> loop.</p>

<h2>The Grammar</h2>

<p>First of all we will define the grammar for all out types of loops.</p>

<pre><code>//Infinite loop
LOOP        { L = getLbl;
              emitLbl L }
&lt;block&gt;
END     { Emit(jmp L }

//Post coditional
DO          { L = getLbl
              emitLbl L }
&lt;block&gt;
UNTIL
&lt;condition&gt; { Emit(JNE L) }

//For Loop
FOR &lt;ident&gt; = &lt;expr1&gt; TO &lt;expr2&gt; &lt;block&gt; END
</code></pre>

<p>These translate into the follow data type</p>

<pre class="prettyprint lang-hs">
    data Statement = Statement String 
                  | Branch Condition Block
                  | Branch2 Condition Block Block
                  | While Condition Block
                  | Loop Block
                  | DoUntil Block Condition
                  | For Statement Expression Block
                  deriving (Show)
</pre>

<h2>Infinite Loops</h2>

<p>An infinite loop by itself is pretty useless, but combined with a <code>break</code> statement it can be pretty handy for when you don't really know how long you need to be going through your loop. A typical example of an infinite loop is a game loop or an event loop, that essentially loops while true until a particular state, event or message terminates the program.</p>

<p>The paser is very simple. We just drop the keywords and pass the block onto the <code>Loop</code> data constructor.</p>

<pre class="prettyprint lang-hs">
    -- |Parses loop..end statments
    loop :: Parser Statement
    loop = accept "loop" <-+> block <+-> accept "end" >>> Loop
</pre>

<p>The assembly to create an infinite loop is just an unconditional jump back to the start of the loop.  This means we will require a label at the start of the block and a simple <code>jmp</code> after our block.</p>

<pre class="prettyprint lang-hs">
    emitStatement (Loop b) = do
        startLbl <- getLbl
        block <- emitBlock' b
        let jmp = emitLn ("jmp " ++ startLbl)
        return ((emitLbl startLbl) ++ block ++ jmp)
</pre>

<h2>Post Conditonal Loop</h2>

<p>We already have a preconditional loop with <code>while</code>, so now we will add it's cousin the <code>do...until</code>. We use the keyword <code>until</code> to avoid some issues with the <code>while</code> keyword. This loop is useful where you would like something to happen at least once.</p>

<p>On the face of it, this is just <code>while</code> with the <code>condition</code> and <code>block</code> reversed. That's exactly how we will treat it. The recogniser is the same as <code>while</code> with minor order adjustments, as is the emitter.</p>

<pre class="prettyprint lang-hs">
    -- |Parses do..until statments
    dountil :: Parser Statement
    dountil = accept "do" <-+> block <+-> accept "until" <+> condition +>> DoUntil

    emitStatement (DoUntil b cond) = do
        startLbl <- getLbl
        c <- emitCondition cond
        block <- emitBlock' b
        let jmp = emitLn ("je " ++ startLbl)
        return ((emitLbl startLbl) ++ block ++ c ++ jmp)
</pre> 

<h2>For loop</h2>

<p>The for loop construct we are going to build here is not the c-style one with a condition and increment function. We are going to use a simpler Basic style construct that is typically used like:</p>

<pre><code>FOR x=1 TO 10
    &lt;block&gt;
</code></pre>

<p>There are a few assumptions with this construct.  It is assumed that the 'counter' is an integer that incements by one on each pass through the loop.</p>

<p>You may have noticed in the first section that I (intentionally) did not add any psuedo-syntax to the for loop syntax.  If we were to try to directly translate a for loop into assembly it would be a bit tiresome and quite ugly.  Instead, we will translate the source into an alternative construct.</p>

<pre><code>// alternative for loop construct
&lt;ident&gt; = &lt;expr1&gt;
TEMP = &lt;expr2&gt;
WHILE &lt;ident&gt; &lt;= TEMP
&lt;block&gt;
&lt;ident&gt; = &lt;ident&gt; + 1
END
</code></pre>

<p>So we will parse the construct, but rather than emit the assembly directly, we will actually just 're-write' the AST to this new construct, which we can then just emit with our existing code.  </p>

<div style="float:right; width:50%; margin-left:1em;border:1px solid #333;background:#FCF4B8;padding:0.5em">Aside: The 're-writeing' of the AST is quite common in programming languages and is often called 'syntactical sugar'.  In a 'real' compiler, there are often several optimisation steps that re-write the AST that sits between the parser and emitter.  Our 'toy' compiler omits these optimisation passes.</div>

<p>To do this we will need to remediate our expression parser and emitter so that they work in the larger context of our program parser.</p>

<p>We'll bring the <code>Assign</code> type into be a data constructor for <code>Statement</code>, add the assignment option to <code>statement</code> add a new pattern to <code>emitStatment</code>, and (for now) ignore the sections and just emit the text section.</p>

<pre class="prettyprint lang-hs">
    -- Lbach.Grammar.Basics
    data Statement = Statement String 
                  | Branch Condition Block
                  | Branch2 Condition Block Block
                  | While Condition Block
                  | Loop Block
                  | DoUntil Block Condition
                  | Assign Assignment
                  deriving (Show)

    data Assignment = Assignment String Expression 
                    deriving (Show)

    -- Lbach.Parser.Control
    statement = loop 
                <|> dountil
                <|> while 
                <|> ifelse 
                <|> ifthen 
                <|> assign
                <|> other

    -- Lbach.Parser.Expressions
    assign = token letters <+-> token (literal '=') <+> expr +>> Assign

    --Lbach.Emitter.Control
    emitStatement (Assign s expr) = do
        return $ emitText expr
</pre>

<p>You'll also need to remove <code>emit2</code> from <code>Lbach.Emitter</code> and update some patterns in <code>Lbach.Emitter.Expressions</code> to get it compile.</p>

<p>Now that's out of the way, we can get down to business on the for loop parser.  Let's revisit the grammar.</p>

<p>FOR <ident> = <expr1> TO <expr2> <block> END
or
FOR <assign> TO <expr> <block> END</p>

<p>This leads to a very natual data type and parser.</p>

<pre class="prettyprint lang-hs">
    -- |Parse a for loop
    forloop :: Parser Statement     
    forloop = accept "for" <-+> assign <+-> accept "to" <+> expr <+> block <+-> accept "end" >>> br
        where br ((a, e), b) = For a e b
</pre>

<p>As you can see I chose not to transform the AST at the parser level. Therefore we have to do it at the emitter level.  This is surprisingly quite straight forward.</p>

<pre class="prettyprint lang-hs">
    emitStatement (For (Assign (Assignment s e1)) e2 b) = do
        let var1 = s
        let var2 = "temp"
        let increment = Assign (Assignment var1 (Add (Var var1) (Num 1)))
        line1 <- emitStatement $ Assign (Assignment s e1)
        line2 <- emitStatement $ Assign (Assignment var2 e2)
        rest <- emitStatement (While (Condition (var1 ++ "<=" ++ var2)) (b ++ [increment]))
        return $ line1 ++ line2 ++ rest
</pre>

<h2>Testing some samples</h2>

<pre><code>*Main&gt; p "loop block end end"
L0:
        &lt;block&gt; block
        jmp L0
        ret

*Main&gt; p "do block until condition end end"
L0:
        &lt;block&gt; block
        &lt;condition&gt; condition
        je L0
        ret

*Main&gt; p "for a=1 to 2 block end end"
        MOV eax, 1
        MOV [a], eax
        MOV eax, 2
        MOV [temp], eax
L0:
        &lt;condition&gt; a&lt;=temp
        je L1
        &lt;block&gt; block
        jmp L0
L1:
        ret
*Main&gt; p "for a=1 to 1000 if a b end d = 3+2*c end end"
        MOV eax, 1
        MOV [a], eax
        MOV eax, 1000
        MOV [temp], eax
L0:
        &lt;condition&gt; a&lt;=temp
        je L1
        &lt;condition&gt; a
        jne L2
        &lt;block&gt; b
L2:
        MOV eax, 3
        PUSH eax
        MOV eax, 2
        PUSH eax
        MOV eax, [c]
        POP ebx
        MUL ebx
        POP ebx
        ADD eax, ebx
        MOV [d], eax
        MOV eax, [a]
        PUSH eax
        MOV eax, 1
        POP ebx
        ADD eax, ebx
        MOV [a], eax
        jmp L0
L1:
        ret

*Main&gt;
</code></pre>

			]]>
		</description>
         <pubDate>Thu, 28 Oct 2010 06:09:49 +0000</pubDate>
         <guid>http://alephnullplex.appspot.com/blog/view/2010/10/28/lbach-loops</guid>
      </item>
	  
      <item>
         <title>Let's build a compiler (in Haskell): Part 11 - Introducing the State Monad</title>
         <link>http://alephnullplex.appspot.com/blog/view/2010/10/19/lbach-introducing-the-state-monad</link>
         <description>
			<![CDATA[
			<p>In the <a href="http://alephnullplex.appspot.com/blog/view/2010/04/07/lbach-10-basic-control-structures">last installment</a> you may have noticed that there was a lot of state threading in the emitter functions. This involved a lot of careful ordering of <code>s1</code>, <code>s2</code> etc.  which is quickly becoming a problem. Especially so when you aren't consistent with parameter ordering - <code>getLabel</code> took the counter last whilst <code>emitStatment</code> was taking the counter as the first parameter.</p>

<p>It is a misnomer that functional programming cannot have state, rather it cannot have side effects, which is a very different ideal.  If you need to maintain state in your application, and a compiler inherently does, then you need to continually pass this state from one function to the next.  Conversely, all your functions that modify the state must all return the entire state.</p>

<p>The State Monad was created for instances exactly like this. It defines an explicit interface for passing state from one function to the next, and provides several functions for executing the functions using this state.  I'm not going to provide yet another State Monad breakdown - for that I can recommend the following: <a href="http://www.haskell.org/haskellwiki/State_Monad">the official wiki</a>, <a href="http://coder.bsimmons.name/blog/2009/10/the-state-monad-a-tutorial-for-the-confused/">a great explaination of the mechanics</a> and most recently <a href="http://learnyouahaskell.com/for-a-few-monads-more#state">Learn you a Haskell</a>.</p>

<h2>Some things I learned the hard way</h2>

<h3>The State Monad and Record Syntax</h3>

<p>I really struggled with using the State Monad in a situation where multiple peices of state are used.  As the compiler is going to need many peices of state such as the label counter, break label, symbol table etc., I started looking for info on record syntax and State Monads.  The best I could find was a few paragraphs in <a href="http://book.realworldhaskell.org/read/monads.html#x_Wh">Real World Haskell</a> which was pretty clear if brief.</p>

<h3>Types for Functions that use the State Monad</h3>

<p>Almost all the sample code and tutorials on using the state monad involved no parameters for the functions.  All the types where of <code>State s a</code> and almost no examples showed how to pass in extra parameters.  Thankfully Learn you a Haskell had some examples that used <code>b -&gt; State s a</code> which lead me to figure out that functions using the State monad can have any type but final type of a function must be <code>State s a</code> and that the type of the function used with <code>runState</code> et.al. must be <code>State s a</code> only.  Took me a while to figure this one out.</p>

<h3>Random number examples</h3>

<p>Annoyingly, 9 times out of 10, any example on the State Monad uses the random number example.  This example is next to useless as it neatly ties up the original state in <code>StdGen</code> which hides the actual usage of <code>State</code>. Please try to come up with something original and worthwhile that explains the whole thing.  Thanks to Learn you a Haskell, which uses a simple stack example, I was able to figure how and when the <code>State</code> is called.</p>

<h2>Simple Example</h2>

<p>Rather than try to retro fit the State Monad throughout our emitter in this article, which will be complex and tedious, I will use a simplified example.</p>

<p>First thing we do is create a data type to collect all out stateful information, and a new type using <code>State</code> and our new data type.</p>

<pre class="prettyprint lang-hs">
-- This will hold all of the data in our state
data EmitStuff = EmitStuff {
    lblCounter :: Int,
    lastLabel :: String 
    } deriving (Show)

-- It is common practice to make your own state type
type MyStateMonad = State EmitStuff 
</pre>

<p><code>lblCounter</code> will hold the current count for creating numbered labels, whilst <code>lastLabel</code> will be the last generated label.  </p>

<p>Next we will create a function that generates a new label.  This will solely use the state to calculate the new label, and then update the state. Do notation makes this much clearer to read.</p>

<pre class="prettyprint lang-hs">
-- Generates a new label based on the current label counter
-- Stores the generated label, and updates the label counter
newLabel :: MyStateMonad String
newLabel = do 
    st <- get
    let l = "L" ++ show(lblCounter st)
    put st { lblCounter = lblCounter st + 1, lastLabel = l}
    return l
</pre>        

<p>Next we'll create an example that takes an extra parameter.  A function that generates a label with a comment.</p>

<pre class="prettyprint lang-hs">
-- Emits a label followed by a comment 
emitLabelAndComment :: String -> MyStateMonad String
emitLabelAndComment x = do 
    l <- newLabel
    return (l ++ ":  #" ++ x)
</pre>

<p>Let's take a moment to understand what this one is doing.  You'll recall that the State Monad is a wrapper for the type <code>s -&gt; (a, s)</code> which means that the above type signature expands into <code>String -&gt; s -&gt; (String, s)</code>.  This means that this function will also take the state as input, which is then passed onto <code>newLabel</code> through the State Monads internals. This is a key concept in turning your manual state management code into something that can be used with the state monad. <a href="http://mvanier.livejournal.com/1901.html">Mike Vanier explains</a> how we can turn the 5 different type of functions using state into one standard format: <code>s -&gt; (String, s)</code>. </p>

<p>The next example is calling multiple functions that use state from one function. </p>

<pre class="prettyprint lang-hs">
-- Simple example showing how we no longer need to manually thread the state when creating labels 
fakeIfStatement :: MyStateMonad String   
fakeIfStatement = do 
    falseBranch <- newLabel
    endLabel <- newLabel
    return ("if not true then \njump " ++ falseBranch ++ "\nDo some true stuff\njump " ++ endLabel ++ "\n" ++ falseBranch ++ ": #some stuff to do if false\n" ++ endLabel) 
</pre>      

<h2>Executing the State Monad</h2>

<p>Finally we need to tie it all together.  The state monad comes with three utility functions for executing the code.</p>

<ol>
<li><code>runState</code> returns the result and the state as a tuple</li>
<li><code>evalState</code> returns the result and discards the state i.e. <code>(result, _) = runState</code></li>
<li><code>execState</code> returns the state only and discards the result i.e. <code>(_, state) = runState</code></li>
</ol>

<p>Each of these functions take a fucntion of type <code>State s a</code> and an intial state of type <code>s</code>.  So first we will create our initial state.</p>

<pre class="prettyprint lang-hs">
initialState = EmitStuff { lblCounter = 0, lastLabel = "" }
</pre>

<p>We can then use any of the utility functions to execute our code against this state.</p>

<pre class="prettyprint lang-hs">
runState fakeIfStatement initialState 
-- or
evalState newLabel initialState
</pre>

<p>But this is not very useful as the state is reset everytime we apply it to a new function.  We have already seen the answer in <code>fakeIfStatement</code>.  We simply create one function that executes all the other functions for the duration of the state.</p>

<pre class="prettyprint lang-hs">
-- Tying it all together 
emitAll = evalState emit EmitStuff { lblCounter = 0, lastLabel = "" } 
    where emit = do
              a <- emitLabelAndComment "This is the first label"
              b <- fakeIfStatement 
              c <- emitLabelAndComment "This is the last label"
              return (a ++ "\n" ++  b ++ "\n" ++ c)
</pre>                  

<p>Now if you were to execute <code>putStrLn &amp; emitAll</code> in <code>ghci</code> you will see labels nicely placed and incremented as expected.</p>

<p><a href="http://github.com/alephnullplex/cradle/blob/master/part11/state.hs">You can download and play with all of the above from Github.</a></p>

<h2>Implementing in LBaCH</h2>

<p>Implementation into the existing <code>Emitter.Control</code> required a rather large rewrite (94% according to git), but was not terribly difficult.  It now reads much clearer and looks a lot more like the BNF notation. </p>

<p>For now I have made the state entry point at the <code>emitBlock</code> level, but in future it may be moved up to encompass the entire emit process.  </p>

<pre class="prettyprint lang-hs">
emitBlock :: Block -> String
emitBlock b = evalState e EmitterData { lblCounter = 0, lastLabel = "" }
    where e = do
              a <- emitBlock' b
              return a 
</pre>

<p><a href="http://github.com/alephnullplex/cradle/blob/master/part11/lbach-11.zip">You can find all the gory details here.</a></p>

			]]>
		</description>
         <pubDate>Tue, 19 Oct 2010 05:57:37 +0000</pubDate>
         <guid>http://alephnullplex.appspot.com/blog/view/2010/10/19/lbach-introducing-the-state-monad</guid>
      </item>
	  
      <item>
         <title>Google AI Challenge 2010</title>
         <link>http://alephnullplex.appspot.com/blog/view/2010/09/16/google-ai-challenge-2010</link>
         <description>
			<![CDATA[
			<p>The <a href="http://ai-contest.com/">Google AI Challenge</a> has started for 2010.  This year the challenge is based on a simplified version of Galcon.</p>

<p>I've been playing around with the Python starter package to get a feel for it.  AI, whilst a field I am interested in, I have absolutely no experience with.  I am fumbling and googleing my way through the first few attempts.  </p>

<p>I intend on switching to Haskell once I get my feet under me, as there is a 1 second time limit for each turn, and as my strategies get more complex, the Python version is going to reach that limit pretty quick.  <a href="http://jaspervdj.be/">Jasper Van der Jeugt</a> has kindly put together a <a href="http://github.com/jaspervdj/planet-wars-haskell">Haskell Starter Kit</a>, so the ground work is laid down.</p>

<p>Whilst I won't reveal any of my strategies just yet (for fear of embarrassment), I will share my testing script.  </p>

<p>The script runs your bot against all the example bots, and any other bots you put in the examples directory, on all maps and gives you a score.  The score is simply the percentage of wins.  Test runs are recorded in a history file, along with the git version so you can assess whether you are going forwards or backwards.</p>

<p>You can also specify how many maps to use if you want a shorter feedback loop.</p>

<pre class="brush: py">
import os, subprocess, sys

total_wins = 0
opponents = 0
maps = 100
mybot = "python MyBot.py"

history = "history.txt"
this_run = []

if len(sys.argv) > 1:
    maps = int(sys.argv[1])

import subprocess as sub
p = sub.Popen('git rev-parse HEAD',stdout=sub.PIPE,stderr=sub.PIPE)
output, errors = p.communicate()
print output
this_run.append("Bot version: " + output.strip())

for file in os.listdir("example_bots"):
    opponent_cmd = ""
    if file.endswith(".jar"):
        opponent_cmd = 'java -jar example_bots/' + file
    if file.endswith(".py"):
        opponent_cmd = 'python example_bots/' + file
    if opponent_cmd:
        opponents = opponents + 1
        player_1_counter=0
        player_2_counter=0
        for i in range(1, maps):
            cmd = ['java', '-jar', 'tools/PlayGame.jar', 'maps/map' + str(i) + '.txt', '1000', '1000', 'log.txt', '"' + opponent_cmd + '"', '"' + mybot + '"', '>tmp 2>&1']
            cmd2 = " ".join(cmd)
            os.system(cmd2)
            r = open('tmp').read()
            if "Player 1 Wins!" in r:
                player_1_counter = player_1_counter + 1
            if "Player 2 Wins!" in r:
                player_2_counter = player_2_counter + 1
                total_wins = total_wins + 1
        print file + " :: " + str(player_1_counter) + "/" + str(player_2_counter)
        this_run.append(file + " :: " + str(player_1_counter) + "/" + str(player_2_counter))
print "Done. Won " + str(total_wins) + " of " + str(opponents * maps)
print "Score of " + str((float(total_wins) / (opponents * maps)))
this_run.append("Done. Won " + str(total_wins) + " of " + str(opponents * maps))
this_run.append("Score of " + str((float(total_wins) / (opponents * maps))))

open(history, 'a').write("\n".join(this_run) + "\n\n")
</pre>

<p>Good luck.</p>

			]]>
		</description>
         <pubDate>Thu, 16 Sep 2010 00:35:36 +0000</pubDate>
         <guid>http://alephnullplex.appspot.com/blog/view/2010/09/16/google-ai-challenge-2010</guid>
      </item>
	  
      <item>
         <title>TechEd Highlights</title>
         <link>http://alephnullplex.appspot.com/blog/view/2010/09/02/teched-highlights</link>
         <description>
			<![CDATA[
			<p>I recently attended the <a href="http://australia.msteched.com/">TechEd</a> conference on the Gold Coast, and it was a well organised and hectic three days.  With around 3000 delegates, 15 tracks and 241<sup><a href="#footnote-1">1</a></sup> talks and presentations it was definitely big.</p>

<p>The facilities were exemplary.  The exhibitors were seperated from the presentation halls so that you could avoid the vendors between talks.  The catering was plentiful.  And I spent a fair amount of time with the Lego in the chill out area.  Check out the <a href="http://www.flickr.com/groups/auteched09/">Flickr Stream</a> to see what it was all about.</p>

<p>But the purpose of the event was to learn something. Which I did. I learn't a lot actually.  Like ASP.NET MVC2 has some killer features, I heard about <a href="http://code.google.com/p/autofac/">autofac</a> for the first time, and got very interested in <a href="http://en.wikipedia.org/wiki/Concurrency_and_Coordination_Runtime">CCR</a>. </p>

<p>I'm not going to review each of the talks I attended, because that would be boring and ardious.  Instead I will just share my highlight - <a href="http://callvirt.net/blog/">Joel Pobar</a>. </p>

<p>Joel's talk (or rant) on <a href="http://www.msteched.com/2010/Australia/ARC301">Philosophy of Software Quality</a> with <a href="http://www.msteched.com/Speakers/David-Connors">David Connors</a> was quite critical about current standards and processes, yet I found it to be incrediable insightful.   Their third pillar, Craftsmanship, is something that I have instinctually known to be critical for a good developer to become great, yet I was unable to label.  It now makes perfect sense.</p>

<p>I also attended Joel's other talk, <a href="http://www.msteched.com/2010/Australia/DEV424">High performance, highly scalable applications on the .NET Framework</a>. This was a little over my head, but Joel's enthusiasm and delivery style kept me interested and definately sparked an 'I should know more about this' light bulb.</p>

<p>If you get the chance to attend any of Joel's presentations, grab it with both hands. Even if you have no idea what the subject matter is, you will not be dissappointed.</p>

<p><a name="footnote-1"></a>1. Number found by running <code>document.getElementsByClassName('topic').length</code> against http://australia.msteched.com/topic/list</p>

			]]>
		</description>
         <pubDate>Thu, 2 Sep 2010 01:44:00 +0000</pubDate>
         <guid>http://alephnullplex.appspot.com/blog/view/2010/09/02/teched-highlights</guid>
      </item>
	  
      <item>
         <title>Announcing SPProfileDump</title>
         <link>http://alephnullplex.appspot.com/blog/view/2010/08/02/announcing-spprofiledump</link>
         <description>
			<![CDATA[
			<p><a href="http://spprofiledump.codeplex.com">SharePoint Profile Data Export Import</a> is a simple command line utility to export the data associated with profiles in SharePoint.</p>

<h2>Why?</h2>

<p>During a farm upgrade I needed a way to bring across all the profiles from the old SSP to the new SSP.  Some of the data in the profiles was original content and was not in any of the profile source systems e.g. Skills etc. As I didn't want the users to have to re-enter all their information, this tool was born.</p>

<h2>But why write something?</h2>

<p>During my research I could not find anything that got the job done.  I found ways to <a href="http://blah.winsmarts.com/2007-1-SharePoint_2007_Utility_-1_-_ProfilePropertyMgr_-_Utility_to_Import-Export_profile_properties.aspx">import/export the properties</a> and a project to <a href="http://blah.winsmarts.com/2007-1-SharePoint_2007_Utility_-2_-_PI_-_Utility_to_Import-Export_actual_user_profiles.aspx">import profile data</a> based on an XML file mapping, but didn't seem to fulfill the export option it promised.  There was nothing that would let me do a simple export then import. So now there is.</p>

<h2>Usage</h2>

<p>To export all the profiles use {{spprofiledump.exe --url http://example.sharepoint.com --file dump.xml --export}}. This will create an XML file with all the profiles contained in the SSP.
To import data into an SSP use {{spprofiledump.exe --url http://example.sharepoint.com --file dump.xml --import}}.</p>

<h2>The XML File</h2>

<p>The file is reasonably straight forward.  A sample entry is probably the simplest way to explain it:</p>

<pre><code>&lt;ProfileDump&gt;
  &lt;User AccountName="DOMAIN\USER"&gt;
    &lt;Property Name="Title" Type="string"&gt;Mr&lt;/Property&gt;
    &lt;Property Name="FirstName" Type="string"&gt;Geoff&lt;/Property&gt;
    &lt;Property Name="LastName" Type="string"&gt;Ford&lt;/Property&gt;
    &lt;Property Name="SPS-HireDate" Type="date"&gt;10/06/2003 12:00:00 AM&lt;/Property&gt;
    &lt;Property Name="SPS-Skills" Type="List"&gt;
        &lt;Entry&gt;SharePoint Development&lt;/Entry&gt;
    &lt;Property&gt;
    ...
  &lt;/User&gt;
&lt;ProfileDump&gt;
</code></pre>

<p>As you can see, dates and multi-valued properties are handled correctly.</p>

<h2>Get It</h2>

<p>You can get the source, and a pre-compiled binary at the <a href="http://spprofiledump.codeplex.com">SPProfileDump homepage</a>.  Please put all feedback, questions, issues etc. over there.</p>

			]]>
		</description>
         <pubDate>Mon, 2 Aug 2010 03:12:24 +0000</pubDate>
         <guid>http://alephnullplex.appspot.com/blog/view/2010/08/02/announcing-spprofiledump</guid>
      </item>
	  
      <item>
         <title>SharePoint Solution upgrade woes</title>
         <link>http://alephnullplex.appspot.com/blog/view/2010/06/17/sharepoint-solution-upgrade-woes</link>
         <description>
			<![CDATA[
			<p>Recently I was upgrading a bunch of master pages, layouts and CSS files in a SharePoint 2007 via a Solution when I ran into a problem with deployment. No matter what I tried, I could not get my new look to take.</p>

<p>I tried all the usual <code>stsadm</code> commands. First I tried just an <code>upgradesolution</code>, then I tried forcing a redolyment as well. I even went as far as to delete the solution and re-add, but all to no avail. Everything I tried was met with a furiating 'meh' from the servers.</p>

<h2>SharePoint Storage Model</h2>

<p>SharePoint has an interesting concept of how, where and when to store certain files.  Coming from a regular web developer background, I assumed that all the files on disk is what SharePoint would use for rendering the pages. Turns out I was wrong.</p>

<p>After a lot of hunting, I stumbled on <a href="http://mikeknowles.com/blog/2009/02/20/SharePointPublishingAndBrowserCacheContentUpdates.aspx">this article from Mike Knowles</a> which explains it quite clearly</p>

<blockquote>
  <p>...once Master Pages and Page Layouts have been customized then SharePoint does not allow solutions to overwrite them. Depending who you talk to or what article you read, or how late you end up working when vexed by this problem, you might consider this a feature or a bug.</p>
</blockquote>

<p>In the SharePoint development world, you can't depend on updating files on the file system to affect any changes at all, because the 'files' might actually be database records.</p>

<h2>My Solution</h2>

<p>As all good SharePoint developers should, I was using a Feature to deploy my layouts.  The plan was to use a FeatureReceiver to simulate the check-out, modification and check-in of the files in question.  It works suprising well.</p>

<p>The code is quite straight forward. The only gotcha was to ensure that the file was able to be checked out and not customised.  Because the files that you need to update are dependant on the Feature, I have not included my implementation of <code>GetLayouts()</code>. I used the <code>Features.xml</code> via <code>properties.Definition.GetXmlDefinition()</code> to get a list of all the <code>ElementFile</code> nodes, but you might prefer to traverse the file system. </p>

<pre class="brush: csharp">
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
    var files = GetLayouts();

    SPFile targetFile = null;
    FileStream fileStream;
    string targetFileName;
    try
    {
        using (SPWeb web = Extensions.GetWeb(properties))
        {
            foreach (string file in files)
            {
                targetFileName = file.Replace("\\", "/");
                targetFile = web.GetFile(targetFileName);
                if (targetFile.Exists == true)
                {
                    if (targetFile.CheckOutStatus != SPFile.SPCheckOutStatus.None)
                    {
                        targetFile.UndoCheckOut();
                    }
                    if (targetFile.CustomizedPageStatus == SPCustomizedPageStatus.Customized)
                    {
                        targetFile.RevertContentStream();
                    }

                    targetFile.CheckOut();
                    using (fileStream = File.OpenRead(properties.Definition.RootDirectory + "\\" + file))
                    {
                        targetFile = web.Files.Add(targetFileName, fileStream, true);
                        fileStream.Close();
                        targetFile.CheckIn("Feature Activation", SPCheckinType.MajorCheckIn);
                        Trace.WriteLine(targetFileName + " successfully updated");
                    }
                } else {
                    Trace.WriteLine(targetFileName + " does not exist");
                }
            }
        }
    }
    catch (Exception exception)
    {
        Trace.WriteLine(exception.Message);
    }
}
</pre>

<p>This could be written as an extension on <code>SPFeatureReceiverProperties</code> and you caould add some diffing so you don't create unneccessary versions of the files, but this simple implementation works sufficently.</p>

<p>Now when you update the layout files, repackage and redeploy the solution, you will need to do a <code>activatefeature -force</code> to ensure that your layouts are updated.</p>

			]]>
		</description>
         <pubDate>Thu, 17 Jun 2010 00:18:56 +0000</pubDate>
         <guid>http://alephnullplex.appspot.com/blog/view/2010/06/17/sharepoint-solution-upgrade-woes</guid>
      </item>
	  
      <item>
         <title>Thoughts on Drupal</title>
         <link>http://alephnullplex.appspot.com/blog/view/2010/06/01/thoughts-on-drupal</link>
         <description>
			<![CDATA[
			<p>With the release of a large website redesign using Drupal successfully launched, I thought it was time for me to evaluate what I thought of Drupal.</p>

<p>This review is of using Drupal 6 in a commercial environment for a medium to large website with over 600 pages, and a traffic profile of approx. 10,000 hits per hour with almost 90% bounce rate off the home page.</p>

<p>I will cover each of the stages of development:  implementing the template, installing and configuring modules, importing the content, integrating other services and deployment.  </p>

<h2>Templating</h2>

<p>The template system in Drupal is a powerful and flexible system that is an odd combination of template files and template functions.  Some modules prefer functions over files and others vice versa, whilst some things are easier to do using functions but files are more easily maintained.  </p>

<p>This duality can lead to a bit of confusion. It can be a bit of a hassle to figure which is best, what can be done where etc. The <a href="http://drupal.org/project/devel">Theme Developer module</a> was indispensable during this phase. We mostly used files with very rare exceptions, leaving <code>template.php</code> to almost exclusive house helper functions.</p>

<p>I personally liked the seperation of the template files to allow you to override only certain things, such as targetting the way a particular field is displayed. That is, until I couldn’t do what I wanted.  </p>

<p>For example, I was trying to override an individual block template, whilst retaining the default block template.  Apparently, to override a single block template you must override the default template.  This took me a little while to figure out.  I can understand why this is so, but I don’t think it was a good design decision.</p>

<p>The other thing I will recommend is to use a design partner that understands the complexity and separate components of Drupal.  If your designer provides a design that you can’t quite mould into Drupal’s way of doing things, you will have to resort to horrible things like calling <code>theme_blocks()</code> within <code>node.tpl.php</code>. </p>

<h2>Modules</h2>

<p>As with any popular CMS, Drupal has an extensible architecture which they term modules.  There are literally <a href="http://drupal.org/project/Modules">thousands of modules available</a> on Drupal.org. However, as with any popular CMS, these are of varying degrees of completeness and robustness. </p>

<p>There is a bewildering array of modules available, some that seem to do almost nothing, to others that are so common that they have actually been flagged for inclusion in the core of Drupal 7 suc as <a href="http://drupal.org/project/cck">CCK</a>.  Finding the module that does what you want can be a little bit of a game of find and seek.  A good research environment, one that can be set up and torn down fast, is mandatory when trialing new modules.</p>

<p>Developing modules in Drupal is a pretty pleasant experience.  While the core code is using an old ‘hooks’ paradigm, it works very well.  Combined with the extensive code comments, <a href="http://api.drupal.org/">excellent API site</a> and <a href="http://drupal.org/contributors-guide">one of the best developer handbooks</a> I have seen in a CMS, you can quickly and easily find and understand the function you need.</p>

<h2>Migrating the Old site</h2>

<p>The site we re-implemented in Drupal has been around for several years and was a large, sprawling collection of HTML mixed with assets and code.</p>

<p>So the first order of the day was to rationalize and understand the existing content.  This was probably the hardest part of the entire project, and was completely under estimated.  Be warned, moving a site in a large, complex organization has a far reaching impact.  We found out after our first release that a number of other teams, and even external sites, were depending on assets served on the site.  </p>

<p>There are a couple of modules available for importing content into Drupal, but the <a href="http://www.lullabot.com/articles/drupal-data-imports-migrate-and-table-wizard">method we used</a> was <a href="http://drupal.org/project/migrate">Migrate</a> and <a href="http://drupal.org/project/tw">Table Wizard</a>.  We had to write a crawler that would dissect each page in the existing site, stripping styles, downloading assets and attempting to fix links, and dumped all of this into a database of content to import.  </p>

<p>The crawler saved us a huge amount of time, but every page still required manual review to ensure that no inline styles slipped through and that it actually looked and functioned correctly. </p>

<h2>Integrating with other things</h2>

<p>The hardest part of the entire build was working with external data. As this site has been around for several years, a number of dynamic pages had been constructed using data from various sources using various techniques.</p>

<p>Drupal likes to share its information out. You can provide RSS and ATOM feeds and even provide web services for others to consume.  But when it comes to Drupal using external data, you are limited.  </p>

<p>There are a couple of modules that make integrating with specific services easy such as Flickr and Amazon.  There are even a few modules that attempt to make it easy to use generic data such as <a href="http://drupal.org/project/feeds">Feeds</a> and <a href="http://drupal.org/project/data">Data</a>, but I found these a bit cumbersome and limited.  I am keen to see them progress in the future.</p>

<p>So when it came to connecting to the web services that we had written to expose all the legacy applications to the new Drupal site we got a bit stuck.  We ended up writing a <a href="http://github.com/alephnullplex/drupal-soapy">very thin module</a> that simply called a web service and passed the data onto a template for rendering.   With Drupal’s ability to override template files, we were on our way.</p>

<h2>Deployment</h2>

<p>We went with established best practice for enterprise Drupal and separated out authoring environment from the production environment.  We then used deployment scripts to automatically and painlessly deploy from one environment to the other, with only a change to settings.php.</p>

<p>This worked well with the glaring exception of the <a href="http://drupal.org/project/swftools">SWF Tools</a> module.  For some reason, whenever we deployed a page using SWF Tools filter, the flash was still referencing the previous environment.  With a little digging, we were able to find a workaround, but the <a href="http://drupal.org/node/813656">original issue</a> remains. </p>

<h2>Caching and Performance</h2>

<p>Drupal is a complex machine and requires a fair bit of horsepower to keep it going.  There will be untold misery if you neglect to enable at least the default page caching in production. Believe me – we've been there.</p>

<p>Caching in general is difficult to get right. It is a balance between fresh data and fast page serves.  Unfortunately, Drupal’s built in page cache is based on a minimum lifetime.  This means that the pages are stored in the cache forever until a page edit causes the cache to invalidate.  </p>

<p>This might be fine for mostly static pages, but we had a few pages that we wanted to use (almost) live data on without the need for someone to edit the page.  This fell afoul of the standard cache, because the page was pulled from the cache without updating the dynamic parts.</p>

<p>I don’t know how, or if it’s even possible, to specify that a portion of the page is not to be cached.  I think we could have used blocks, but because this data was to be placed anywhere in the content with the use a filter, blocks were out of the question.  For now we have simply excluded the important pages from being cached, but we can’t do this for too many pages or we start seeing 100% CPU utilization. And that’s not fun.
We are investigating the use of Boost, which is based on a maximum cache time and looks to be a huge performance increase as well. </p>

<h2>Conclusion</h2>

<p>Drupal is not just a CMS, but as a CMS it functions exceptionally well.  There are enough modules out there to do almost everything you need, yet if you do need to develop your own module you won’t be short on tutorials, samples and documentation.  </p>

<p>The user interface can be a bit awkward, but by limiting the options that editors could use and providing a bit of training, they are more than comfortable doing their own edits.  </p>

<p>My only real issue with Drupal is that the performance needs some serious work and caching could be a little more flexible and easier to work with dynamic pages.</p>

<p>Overall, it was a pleasant experience, especially when juxtaposed with other CMS implementations I have had the (unfortunate) pleasure of being involved in. I still think there is a lot for me to learn, especially around the capability of other modules such as <a href="http://drupal.org/project/panels">Panels</a> and <a href="http://drupal.org/project/rules">Rules</a> etc, as well as just understanding the 'Drupal way'.  </p>

<p>With Drupal 7 very active and nearing release (they are up to <a href="http://drupal.org/drupal-7.0-alpha5">Alpha 5</a> at the time of writing), things are looking very good for the Drupal eco-system.</p>

			]]>
		</description>
         <pubDate>Tue, 1 Jun 2010 00:45:13 +0000</pubDate>
         <guid>http://alephnullplex.appspot.com/blog/view/2010/06/01/thoughts-on-drupal</guid>
      </item>
	  
      <item>
         <title>Let's build a compiler (in Haskell): Part 10 - Basic Control Structures</title>
         <link>http://alephnullplex.appspot.com/blog/view/2010/04/07/lbach-10-basic-control-structures</link>
         <description>
			<![CDATA[
			<p>It's time to move on from basic mathmatical expressions and start looking at control structures.  </p>

<h2>The Program</h2>

<p>First of all we will create some 'holding' functions. Let's define these first.</p>

<pre><code>&lt;program&gt;::=&lt;block&gt; END
&lt;block&gt;::=[&lt;statement&gt;]*
</code></pre>

<p>What this says is that a <code>program</code> is a <code>block</code> followed by the <code>end</code> keyword, and that a <code>block</code> is any number of <code>statemtents</code>.</p>

<p>As usual this requires a type, a parser and an emitter.  </p>

<h3>Parsing a Program</h3>

<p>The types are very simple.</p>

<pre class="prettyprint lang-hs">
    data Program = Program Block deriving (Show)
    type Block = [Statement]
    data Statement = Statement String deriving (Show)
</pre>

<p>Because multi-character keywords are pretty simple using our techniques, we will skip the single character keyword versions. I will be using a function called <code>accept</code> which is a simple parser that reads the <code>letters</code> and then compares it to the given keyword.  I've also created a <code>letters'</code> that fails on an empty string. I'll leave the definition of these as an exercise.</p>

<pre class="prettyprint lang-hs">
    program :: Parser Program
    program = block <+-> accept "end" >>> Program 

    block :: Parser Block
    block = iter statement

    statement :: Parser Statement
    statement =  other

    -- | Accepts any string except 'end'
    other :: Parser Block
    other = (token letters') <=> (/="end") >>> Statement
</pre>

<p>With these parsers you can write really cool programs like <code>something end</code> or <code>two statements end</code>.  Don't worry, it gets more exciting.  You might also want to update your <code>parse</code> function to use <code>program</code> instead of <code>assign</code>.</p>

<h3>Emitting a Program</h3>

<p>Our emitter must now take a <code>Program</code>, and iterate over the <code>Statements</code> in it's <code>Block</code>. For now we will be outputting a place holder <code>&lt;block&gt;</code> for our other statements.</p>

<pre class="prettyprint lang-hs">
    type State = Int

    emit :: Program -> String
    emit (Program b) = emitBlock b ++ emitLn "ret"

    emitBlock :: Block -> String
    emitBlock b = result
        where (s, result) = emitBlock' 0 b

    emitBlock' :: State -> [Statement] -> (State, String)
    emitBlock' s [] = (s, "")
    emitBlock' s (b:bs) = (s', first ++ rest)
        where (s1, first) = emitStatement s b
              (s', rest) = emitBlock' s1 bs

    emitStatement s (Statement b) = (s, emitLn ("<block> " ++ b))
</pre>

<p>In case you are wondering why all <code>s</code> and <code>State</code>, this is how we will track the label counter, and other stateful items like the symbol table in the future. I originally had <code>emitBlock</code> using <code>fold'</code> and <code>map</code> in one line, but it caused complications when it came time to thread the label counter through the emit functions.  </p>

<p>So now we can parse and emit multi-statement programs.  Those statements might not do anything yet, but we'll get there. </p>

<h2>If-Then Statements</h2>

<p>The first control structure we will look at is the basic if statement.  This takes a condition, and if the condition is true, it will execute the body of the if statment.</p>

<p>The hardest part of this section is deciding what our syntax will be.  To keep things simple, we will stick to Crenshaws recommended syntax of </p>

<pre><code>IF &lt;condition&gt; &lt;block&gt; ENDIF
</code></pre>

<p>By having an explicit block terminator (ENDIF) we avoid the ambiguity of 'is this still part of the if body'.  </p>

<h3>Parsing If-Then</h3>

<p>We create a new type constructor, which I called <code>Branch</code>, which will hold the condition and the body of the if statement, which is really just another block. The parser is very similar to the syntax definition:</p>

<pre class="prettyprint lang-hs">
    data Statement = Statement String 
                   | Branch Condition Block

    ifthen :: Parser Statement      
    ifthen = accept "if" <-+> condition <+> block <+-> accept "end" >>> buildBranch
        where buildBranch (c, b) = Branch c b
</pre>

<p>Because we use <code>block</code> as part of the function, we can parse multi-statement bodies, and even nested if statments such as:</p>

<pre><code>*Lbach.Parser&gt; ifthen "if cond partA partB end"
Just (Branch (Condition "cond") [Statement "partA",Statement "partB"],"")
*Lbach.Parser&gt; ifthen "if condA if condB bodyB end bodyA end"
Just (Branch (Condition "condA") [Branch (Condition "condB") [Statement "bodyB"],Statement "bodyA"],"")
</code></pre>

<p>Gotta love the power of recursion.</p>

<p>Now to be able to use our new <code>ifthen</code> as part of a <code>program</code> we need to update <code>statement</code> to include it, using our good friend the alternate combinator <code>&lt;|&gt;</code>:</p>

<pre class="prettyprint lang-hs">
    statement :: Parser Statement
    statement =  ifthen <|> other
</pre>

<h3>Emitting If-Then</h3>

<p>An if statement needs to be translated into the following assembly:</p>

<pre><code>&lt;condition&gt; ;calculate the condition
jne end     ;goto 'end' if the condition is NOT equal
&lt;block&gt;     
end:
</code></pre>

<p>We need to use a <code>jne</code>, which means jump if <strong>not</strong> equal, because we want to skip the body if the condition fails. We will continue to output the placeholder <code>&lt;block&gt;</code>.  We will also use a placeholder for <code>&lt;condition&gt;</code> as we haven't covered relational statements yet.  </p>

<p>When generating asm we can't call all our labels <code>end</code> so we have to create a function to generate a new label and we'll also create one to emit the label.  For labels we will use <code>L1</code>, <code>L2</code> etc, and to keep things nice we need to return the next label count.</p>

<pre class="prettyprint lang-hs">
    getLbl :: Int -> (String, Int)
    getLbl count = ("L" ++ (show count), count + 1)

    emitLbl :: String -> String
    emitLbl lbl = lbl ++ ":\n"
</pre>   

<p>Unfortunately, the need to thread the label counter through the emitters complicates them a little, but they are reasonably simple.  We have to be careful to pass the <code>State</code> around in the right order so that our labels come out correct.</p>

<pre class="prettyprint lang-hs">
    emitStatement :: State -> Statement -> (State, String)
    emitStatement s (Branch cond b1) = (s', c ++ jmp ++ block1 ++ end)
        where (s1, c)       = emitCondition s cond 
              jmp           = emitLn ("jne " ++ lbl)
              (s', block1)  = emitBlock' s2 b1
              end           = emitLbl lbl
              (lbl, s2)     = getLbl s1
    emitStatement s (Statement b) = (s, emitLn ("<block> " ++ b))

    emitCondition s (Condition c) = (s, emitLn ("<condition> " ++ c))
</pre>

<p>The only tricky part is following the label counter through.  We first send the label counter through the condition in case it needs to use labels.  The counter is then used to get a new label for use in the jump and outputting the label to jump to. It then gets passed onto the body <code>block</code> which may use labels and therefore increment the counter.  This final number is then returned to the caller.  To see why we pass it in this order try parsing and emitting a nested if.</p>

<pre><code>*Main&gt; let k = emit . parse
*Main&gt; putStr $ k "if condA if condB bodyB end bodyA end end"
        &lt;condition&gt; condA
        jne L0
        &lt;condition&gt; condB
        jne L1
        &lt;block&gt; bodyB
L1:
        &lt;block&gt; bodyA
L0:
        ret
*Main&gt;
</code></pre>

<h2>If-Else</h2>

<p>Now that we have the basic concepts of creating branches, extending it to the if-else statement not so hard. Extending the definition of if to include the else statment looks like:</p>

<pre><code>IF &lt;condition&gt; &lt;block&gt; [ ELSE &lt;block&gt;] ENDIF
</code></pre>

<p>Before we start, we need to modify <code>other</code> to ignore the <code>else</code> keyword.  I chose to use a keyword list to ignore rather than test for individual keywords. </p>

<pre class="prettyprint lang-hs">    
    keywords = ["if", "else", "end"]

    other :: Parser Statement
    other = (token letters') <=> (\x -> not $ any (==x) keywords) >>> Statement
</pre>

<h3>Parsing If-Else</h3>

<p>You could treat <code>else</code> as an optional part of <code>ifthen</code> but I chose to seperate them into seperate type constructors and functions. </p>

<pre class="prettyprint lang-hs">
    data Statement = Statement String 
                  | Branch Condition Block
                  | Branch2 Condition Block Block
                  deriving (Show)

    statement :: Parser Statement
    statement =  ifelse <|> ifthen <|> other

    ifelse :: Parser Statement      
    ifelse = accept "if" <-+> condition <+> block <+-> accept "else" <+> block <+-> accept "end" >>> br
        where br ((c, b1), b2) = Branch2 c b1 b2
</pre>

<p>As you can see, it is much the same as the basic if statement. The only difference is that we add a second <code>Block</code> to the type constructor to allow for the else body.  Again, recusrion allows for nested if statements in nested if-else statements all the way down to turtles.</p>

<h3>Emitting If-Else</h3>

<p>The asm for and if-else is not much more complicated than the if version, but it does entail another jump.</p>

<pre><code>&lt;condition&gt; ;calculate the condition
jne else    ;goto 'else' if the condition is NOT equal
&lt;block&gt;     ;the block to execute if the condition is true
jmp end     ;an unconditional jump to skip the else block
else:
&lt;block&gt;     ;the block to execute if the condition is false (the else block)
end:
</code></pre>

<p>This is where we really need to keep track of our label counter.  Because we need two labels for an if-else, one for the jump to the else portion and another for the jump to the end, the threading gets kind of hairy.  I'll just show it to you and let you figure out where it winds it's way through.</p>

<pre class="prettyprint lang-hs">
    emitStatement s (Branch2 cond b1 b2) = (s', c ++ jmpElse ++ block1 ++ jmpEnd ++ el ++ block2 ++ end)
        where (s1, c)       = emitCondition s cond 
              jmpElse       = emitLn ("jne " ++ lblElse)
              (s4, block1)  = emitBlock' s3 b1
              jmpEnd        = emitLn ("jmp " ++ lblEnd)
              el            = emitLbl lblElse
              (s', block2)  = emitBlock' s4 b2
              end           = emitLbl lblEnd
              (lblElse, s2) = getLbl s1
              (lblEnd, s3)  = getLbl s2
</pre>

<p>As I said, with 4 intermediate counters, the threading does get a bit hairy.  I took a quick look at the <a href="http://www.haskell.org/all_about_monads/html/statemonad.html">State Monad</a> which looks like a nice way to simplify this issue, but it was a bit too much to introduce just yet.  I might retro-fit the State Monad as a seperate article outside this series.</p>

<h2>While</h2>

<p>Third time round we should be able to fly through this. The definition of while is </p>

<pre><code>WHILE  &lt;condition&gt; &lt;block&gt; END
</code></pre>

<p>Which is very similar to the if definition.  The difference is in the generated asm.</p>

<h3>Parsing While</h3>

<p>By now we don't really need an explaination for this.</p>

<pre class="prettyprint lang-hs">
    data Statement = Statement String 
                  | Branch Condition Block
                  | Branch2 Condition Block Block
                  | While Condition Block
                  deriving (Show)

    statement :: Parser Statement
    statement =  while <|> ifelse <|> ifthen <|> other

    while :: Parser Statement
    while = accept "while" <-+> condition <+> block <+-> accept "end" >>> buildWhile
            where buildWhile (c, b) = While c b
</pre>

<p>No surprises there.</p>

<h3>Emitting While</h3>

<p>The asm for a while statement is different from an if in that we need a start label to come back to at the end of the loop.  We jump to the end label if the condition is <strong>true</strong> where as in an if we were jump if false.</p>

<p>The desired asm looks like:</p>

<pre><code>L1: 
&lt;condition&gt;
je L2
&lt;block&gt;
jmp L1
L2:
</code></pre>

<p>Once again, the lable counter threading is tedious, but other than that the function is the same as we've seen before and is dictated by the asm structure.</p>

<pre class="prettyprint lang-hs">
    emitStatement s (While c b) = (s', start ++ cond ++ jmp ++ block ++ loop ++ end)
        where start = emitLbl startLbl
              (s1, cond) = emitCondition s c
              jmp = emitLn ("je " ++ endLbl)
              (s', block) = emitBlock' s3 b
              loop = emitLn ("jmp " ++ startLbl)
              end = emitLbl endLbl
              (endLbl, s2) = getLbl s1
              (startLbl, s3) = getLbl s2
</pre>

<h2>Conclusions</h2>

<p>For those that haven't been following along, you can <a href="http://github.com/alephnullplex/cradle/blob/master/part10/Lbach.zip">get all the code from github</a>. Let's try some complicated samples.</p>

<pre><code>C:\cradle\code\src&gt;runhaskell Lbach.hs "while a if b c else d end e end f end"
L1:
        &lt;condition&gt; a
        je L0
        &lt;condition&gt; b
        jne L2
        &lt;block&gt; c
        jmp L3
L2:
        &lt;block&gt; d
L3:
        &lt;block&gt; e
        jmp L1
L0:
        &lt;block&gt; f
        ret
C:\cradle\code\src&gt;runhaskell Lbach.hs "if a while b c d e end f g else h i if j k end end end"
        &lt;condition&gt; a
        jne L0
L3:
        &lt;condition&gt; b
        je L2
        &lt;block&gt; c
        &lt;block&gt; d
        &lt;block&gt; e
        jmp L3
L2:
        &lt;block&gt; f
        &lt;block&gt; g
        jmp L1
L0:
        &lt;block&gt; h
        &lt;block&gt; i
        &lt;condition&gt; j
        jne L4
        &lt;block&gt; k
L4:
L1:
        ret
</code></pre>

<p>Apparently, with only and if and a while statement, what we have is capable of producing almost any program.  I wouldn't like to test that theory though. In the next article we will be creating a few more control structures such as for loops and a break statement.</p>

			]]>
		</description>
         <pubDate>Wed, 7 Apr 2010 01:32:49 +0000</pubDate>
         <guid>http://alephnullplex.appspot.com/blog/view/2010/04/07/lbach-10-basic-control-structures</guid>
      </item>
	  
      <item>
         <title># Let's build a compiler (in Haskell): Part 9 - Packaging</title>
         <link>http://alephnullplex.appspot.com/blog/view/2010/04/01/lbach-9-packaging</link>
         <description>
			<![CDATA[
			<p>The preferred method for creating distributable Haskell packages, whether they are libraries or programs, is with <a href="http://www.haskell.org/cabal/">the Cabal</a>. The Cabal is a small wrapper around the build tools, and allows some standardised dependancy management, license distribution etc.</p>

<h2>Setting up our compiler to use Cabal</h2>

<p>Unfortunately the <a href="http://hackage.haskell.org/package/mkcabal">mkcabal</a> package, which automates the creation of a basic cabal enabled Haskell package, won't install under OS X Snow Leopard yet, so we are going to have to do this by hand.  Don't worry - it's not that hard.</p>

<p>Create the following as <code>lbach.cabal</code>.</p>

<pre><code>Name:                lbach
Version:             0.1
Description:         Toy compiler
License:             MIT
License-file:        LICENSE
Author:              Geoff Ford
Maintainer:          g_ford@hotmail.com
Build-Type:          Simple
Cabal-Version:       &gt;=1.2
Executable lbach
  Main-is:           Lbach.hs
  Build-Depends:     base &gt;= 3,haskell98
  hs-source-dirs:    src
</code></pre>

<p>The parameters in this file should be pretty self explanatory, with the main ones to keep an eye being the dependencies and the entry file. One thing to note is the <code>hs-source-dirs</code> parameter. This says that all the code can be found under the <code>src</code> directory, and the <code>Main-is</code> parameter will therefore look for <code>src/Lbach.hs</code>.</p>

<p>You'll also need to create a file called <code>LICENSE</code> and create <code>setup.hs</code> as: </p>

<pre class="brush: hs">
    import Distribution.Simple
    main = defaultMain
</pre>

<p>Once this is done, move <code>lbach.hs</code> to <code>src\Lbach.hs</code> and then we need to modify it so that it will run from the command line. For now, we'll just make it so it tries to parse the string passed in as the command line argument.  Add the following at the top of your file in place of <code>import Char</code>:</p>

<pre class="brush: hs">
    module Main
    where

    import Char
    import System.Environment

    main :: IO ()
    main = getArgs >>= print . parse . head
</pre>

<p>This simply creates a module called <code>Main</code> and a function called <code>main</code>, which all Haskell programs must have as their entry point.  Before we test the package, we should test that the program works.</p>

<pre><code>~/Projects/compilers/cradle/code/src&gt; runhaskell Lbach.hs "test=1+2 / counter"
Assign "test" (Add (Num 1) (Div (Num 2) (Var "counter")))
</code></pre>

<p>Awesome.  Now let's test if <code>cabal</code> can package it up and install it for us.  We'll only install it for ourselves just to be on the safe side.</p>

<pre><code>~/Projects/compilers/cradle/code&gt; cabal install --prefix=$HOME --user
Resolving dependencies...
Configuring lbach-0.1...
Warning: 'license: MIT' is not a recognised license.
Preprocessing executables for lbach-0.1...
Building lbach-0.1...
Installing executable(s) in /Users/geoff/bin 
~/Projects/compilers/cradle/code&gt; ~/bin/lbach "test=1+2 / counter"
Assign "test" (Add (Num 1) (Div (Num 2) (Var "counter")))
</code></pre>

<h2>Modularisation</h2>

<p>To keep our program source files from running to unmanageable lengths we will need to break them up into separate files.  This is also a good time to think about how we are going to split the compiler up into modules.  </p>

<p>We immediately know that there are three basic modules - the Parser, the Emitter and the Grammar.  I have also separated the expression parsers from the general parsers.  I'll also prefix everything with an Lbach namespace so as not to get in the way of any existing namespaces. </p>

<p>With Haskell, modules are expected to be in files and folders that reflect their name.  For example the module <code>My.Great.Module</code> should be in the file <code>My/Great/Module.hs</code>. This gives the following file structure.</p>

<pre><code>src
  |- Lbach.hs
  |- Lbach
    |- Parser.hs
    |- Parser
      |- Expressions.hs
    |- Grammar.hs
      | Basics.hs
    | Emitter.hs
</code></pre>

<p>I've updated the emitter to handle our changes to <code>Expression</code> and the addition of <code>Assign</code>.</p>

<p>The reason we have all the code under a <code>src</code> directory is because of the common practice of also having a <code>test</code> directory at the same level.  This keeps the 'real' code and the test code nicely separated. </p>

<p>What goes where is a matter of personal taste.  I won't describe in detail how I broke the compiler up, but you can always check it out at <a href="http://github.com/alephnullplex/cradle/">github</a>. </p>

<p>Don't forget to check that <code>cabal</code> can still package it up and install it.</p>

			]]>
		</description>
         <pubDate>Thu, 1 Apr 2010 00:33:19 +0000</pubDate>
         <guid>http://alephnullplex.appspot.com/blog/view/2010/04/01/lbach-9-packaging</guid>
      </item>
	  
	</channel>
</rss>