Implemented a programming language

This is the place to post any code that you want to share with the community. Only completed scripts should be posted here.

Implemented a programming language

Postby stranac » Mon Jan 27, 2014 2:47 pm

I had some free time today, so I decided I'd implement a programming language...
I chose a pretty simple one: HQ9+

Here's the implementation:
Code: Select all

A simple implementation of the HQ9+ programming language.

Ignores everything except the four valid commands(case insensitive):
    H   Prints "Hello, world!"
    Q   Prints the entire text of the source code file.
    9   Prints the complete canonical lyrics to "99 Bottles of Beer on the Wall"
    +   Increments the accumulator.

import sys
import re

import bottles

class HQ9PlusProgram(object):
    def __init__(self, src):
        self.src = src
        self.acc = 0
        self.commands = {
        'H': self.hello,
        'Q': self.quine,
        '9': self.nine,

    def hello(self):
        print 'Hello, world!'

    def quine(self):
        print self.src

    def nine(self):
        print '\n'.join(bottles.verses())

    def plus(self):
        self.acc += 1

    def run(self):
        for letter in re.findall(r'[HQ+9]', self.src.upper(), re.MULTILINE):

def main():
        filename = sys.argv[1]
    except IndexError:
        in_file = sys.stdin
        in_file = open(filename)

    with in_file:
        program = HQ9PlusProgram(


Code: Select all

'''{0} bottle{1} of beer on the wall,
{0} bottle{1} of beer.
{3} bottle{4} of beer on the wall.

TAKE = 'Take one down and pass it around,'
BUY = 'Go to the store and buy some more,'

def verses():
    Yield verses of "99 Bottles of Beer" one at a time.
    for n in xrange(99, 2, -1):
        yield VERSE.format(n, _ending(n), TAKE, n-1, _ending(n-1))
    yield VERSE.format(1, '', TAKE, 'No more', 's')
    yield VERSE.format('No more', 's', BUY, 99, 's')

def _ending(n):
    return '' if n == 1 else 's'

And of course, I can't show you a program and not show you how to write a "Hello, world!" program:
-- source code:
Code: Select all

-- output:
Code: Select all
Hello, world!

Just run your programs using python <sourcefile>(you can, of course, make it executable if you wish)
If there is no source file given, it will read from stdin...

Friendship is magic!

R.I.P. Tracy M. You will be missed.
User avatar
Posts: 1137
Joined: Thu Feb 07, 2013 3:42 pm

Re: Implemented a programming language

Postby ochichinyezaboombwa » Tue Jan 28, 2014 10:57 pm

Wrong forum!
This should be in Tutorials: "How to implement a programming language".
Posts: 200
Joined: Tue Jun 04, 2013 7:53 pm

Return to Completed Scripts

Who is online

Users browsing this forum: No registered users and 1 guest