Task

Implement a    HQ9+    interpreter or compiler.




import Nanoquery.IO
 
// a function to handle fatal errors
def fatal_error(errtext)
	println "%" + errtext
	println "usage: " + args[1] + " [filename.cp]"
	exit(1)
end
 
// a function to perform '99 bottles of beer'
def bottles(n)
	for bottles in range(n, 1, -1)
		bottlestr = ""
 
		if bottles = 1
			bottlestr = "bottle"
		else
			bottlestr = "bottles"
		end if
 
		println (bottles + " " + bottlestr + " of beer on the wall")
		println (bottles + " " + bottlestr + " of beer")
		println "Take one down, pass it around."
 
		if !(bottles = 2)
			println (bottles - 1 + " bottles of beer on the wall.\n")
		else
			println "1 bottle of beer on the wall.\n"
		end if
	end for
end
 
// get a filename from the command line and read the file in
fname = null
source = null
try
	fname = args[2]
	source = new(Nanoquery.IO.File, fname).readAll()
catch
	fatal_error("error while trying to read from specified file")
end
 
// define an int to be the accumulator
accum = 0
 
// interpreter the hq9+
for char in source
	if char = "h"
		println "hello world!"
	else if char = "q"
		println source
	else if char = "9"
		bottles(99)
	else if char = "+"
		accum += 1
	end
end