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