cmks script v1
[dotfiles.git] / Scripts / cormackscript
1 #!/bin/sh
2
3 # CORMACKSCRIPT 
4 # written by daniel
5 #
6 # Usage: cormackscript [cmks file] [output file]
7 #
8 # IMPORTANT!
9 # Place the comments:
10 # ; CMKS START
11 # ; CMKS END
12 # into your racket program, the 'compiled' code will be injected here.
13 #
14 # For extra niceness, if you have the racket program installed it will auto execute it.
15 #
16 # A CormackScript file contains 3 columns separated by whitespace in the format [opcode|target|source]  
17 # Here's some sample code
18 #
19 # mov 20 30
20 # inc 1
21 # read 21
22 # print 21
23 # quit
24 #
25 # Note, for commands that only need one param you don't need to add empty columns
26 # oh yeah, you can also comment with ;
27
28 # You can redefine these to whatever you want
29
30 inst0="inc"   # [tt] = [tt] + 1
31 inst1="add"   # [tt] = [tt] + [ss]
32 inst2="sub"   # [tt] = max([tt] - [ss], 0)
33 inst3="mov"   # [tt] = [ss]
34 inst4="addeq" # [tt] = [tt] + 1, if [ss] = 0
35 inst5="fetch" # [tt] = [[ss]]
36 inst6="store" # [[tt]] = [ss]
37 inst7="print" # display [ss]
38 inst8="read"  # read [tt]
39 inst9="quit"  # halt
40
41 # Config ends here =-=-=-=-=-=-=-=-=
42
43 [ "$#" -ne 2 ] && { echo "Usage: cormackscript [cmks file] [output file]" && exit 1; }
44 scriptfile="$1"; targetfile="$2"
45 [ -f "$scriptfile" ] && [ -f "$targetfile" ] || { echo "Either $scriptfile or $targetfile do not exist" && exit 1; }
46
47 tmp="$(mktemp 'tempXXX')"
48 cat "$scriptfile" |\
49     sed -r "s/\s*;.*//g; /^\s*$/ d; s/\s+/ /g; s/^\s+//; s/ [0-9]{1} / 0&/; s/ [0-9]{1}\$/ 0&/; s/$inst0/0/; s/$inst1/1/; s/$inst2/2/; s/$inst3/3/; s/$inst4/4/; s/$inst5/5/; s/$inst6/6/; s/$inst7/700/; s/$inst8/8/; s/$inst9/9/; s/ //g" |\
50     sed -e :a -e 's/^.\{1,4\}$/&0/;ta' |\
51     sed 's/![0-9]//g' >> "$tmp"
52 sed -i "/\; CMKS START/,/\; CMKS END/{/\; CMKS START/!{/\; CMKS END/!d}}; /\; CMKS START/r $tmp" "$targetfile"
53 rm "$tmp"
54
55 # If racket is installed run it directly
56 [ ! -z "$(command -v racket)" ] && racket "$targetfile" && echo ""