Skip to content

Commit

Permalink
Added support for byte literals to compiler, interpreter, and trimmer.
Browse files Browse the repository at this point in the history
  • Loading branch information
Kragen Javier Sitaker committed Oct 18, 2008
1 parent 952f4bd commit 3f71e92
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 4 deletions.
5 changes: 5 additions & 0 deletions tinyboot.py
Expand Up @@ -127,6 +127,7 @@ def end_loop():
'[': start_conditional, ']': end_conditional,
'{': start_loop, '}': end_loop,
' ': nop, '\n': nop,
"'": eat_byte, # ignore the literal character
}

def tbfcompile():
Expand Down Expand Up @@ -222,6 +223,9 @@ def loop():
if not stack.pop(): return
jump()

def literal_byte():
# you put 'A into your program to get 65, or 'B to get 66, etc.
stack.append(ord(eat_byte()))

run_time_dispatch = {
'(': jump,
Expand All @@ -238,6 +242,7 @@ def loop():
'[': conditional, ']': nop,
'{': nop, '}': loop,
' ': nop, '\n': nop,
"'": literal_byte,
}

for digit in '0123456789': run_time_dispatch[digit] = push_literal
Expand Down
11 changes: 7 additions & 4 deletions tinyboot1.tbf1
@@ -1,7 +1,9 @@
( Second step toward a tiny bootstrap Forth compiler written in itself.
( A tiny bootstrap Forth compiler written in itself.

Generates an ELF executable for x86 Linux that exits with return code
42, following Brian Raiter’s lead. Uses functions.
Generates an ELF executable for x86 Linux.

Bytes preceded by ' and numbers are compiled into instructions to push
their values on the stack.

Compile-time primitives:
( — defines a comment that extends to the next right-paren
Expand Down Expand Up @@ -277,7 +279,7 @@ v B # 0 ( buffer for w )

( routine to dispatch a byte being compiled )
: D
d 40 = [ p { G 41 - } ; ] ( drop comments until right paren )
d '( = [ p { G 41 - } ; ] ( drop comments until right paren )
d 32 = [ p ; ] ( drop spaces )
d 10 = [ p ; ] ( drop newlines )
d 35 = [ p w 48 - n E ; ] ( # writes the next number as data literally )
Expand All @@ -292,6 +294,7 @@ v B # 0 ( buffer for w )
d 93 = [ p P ; ] ( ] backpatches the address on the compile stack )
d 123 = [ p % H @ ; ] ( { merely pushes an address to jump back to )
d 125 = [ p j ; ] ( } compiles a conditional jump to that address )
d '' = [ p G L ; ] ( ' pushes a character literal )
d 118 = [ p w V ; ] ( v registers the next non-blank as a
variable label )
d 45 = [ p 41 . 4 . 36 . 88 . ; ] ( - is `sub %eax, [%esp]; pop %eax` )
Expand Down
1 change: 1 addition & 0 deletions trim.py
Expand Up @@ -22,5 +22,6 @@
if not firstline: sys.stdout.write('\n')
elif wsp: sys.stdout.write(' ')
sys.stdout.write(byte)
if byte == "'": sys.stdout.write(sys.stdin.read(1))
wsp = newline = firstline = False
sys.stdout.write('\n')

0 comments on commit 3f71e92

Please sign in to comment.