Implement 0BRANCH
[rrq/jonasforth.git] / main.asm
index d206134c08b968bee7d52fb94564de5c4bff8c6f..af84a66631a0d17d5abb5922a220130f9135f8b4 100644 (file)
--- a/main.asm
+++ b/main.asm
@@ -50,6 +50,33 @@ EXIT:
   popr rsi
   next
 
+;; LIT is a special word that reads the next "word pointer" and causes it to be
+;; placed on the stack rather than executed.
+LIT:
+  dq .start
+.start:
+  lodsq
+  push rax
+  next
+
+;; 0BRANCH is the fundamental mechanism for branching. If the top of the stack
+;; is zero, we jump by the given offset. 0BRANCH is given the offset as an
+;; integer after the word.
+ZBRANCH:
+  dq .start
+.start:
+  ;; Compare top of stack to see if we should branch
+  pop rax
+  cmp rax, 0
+  jnz .dont_branch
+.do_branch:
+  add rsi, [rsi] ; [RSI], which is the next word, contains the offset; we add this to the instruction pointer.
+  next           ; Then, we can just continue execution as normal
+.dont_branch:
+  add rsi, 8     ; We need to skip over the next word, which contains the offset.
+  next
+
+;; Expects a character on the stack and prints it to standard output.
 EMIT:
   dq .start
 .start:
@@ -65,15 +92,10 @@ EMIT:
   popr rsi
   next
 
-PUSH_NEWLINE_CHAR:
-  dq .start
-.start:
-  push $A
-  next
-
+;; Prints a newline to standard output.
 NEWLINE:
   dq docol
-  dq PUSH_NEWLINE_CHAR
+  dq LIT, $A
   dq EMIT
   dq EXIT
 
@@ -131,6 +153,8 @@ READ_WORD:  ; 400170
 
   next
 
+;; Takes a string (in the form of a pointer and a length on the stack) and
+;; prints it to standard output.
 TYPE:
   dq .start
 .start:
@@ -147,16 +171,23 @@ TYPE:
   mov rsi, rbx
   next
 
-PUSH_HELLO_CHARS:
+;; Exit the program cleanly.
+TERMINATE:
   dq .start
 .start:
-  push $A
-  push 'o'
-  push 'l'
-  push 'l'
-  push 'e'
-  push 'H'
-  next
+  mov rax, $3C
+  mov rdi, 0
+  syscall
+
+PUSH_HELLO_CHARS:
+  dq docol
+  dq LIT, $A
+  dq LIT, 'o'
+  dq LIT, 'l'
+  dq LIT, 'l'
+  dq LIT, 'e'
+  dq LIT, 'H'
+  dq EXIT
 
 PUSH_YOU_TYPED:
   dq .start
@@ -167,27 +198,21 @@ PUSH_YOU_TYPED:
 
 HELLO:
   dq docol
-  dq PUSH_HELLO_CHARS
-  dq EMIT
-  dq EMIT
-  dq EMIT
-  dq EMIT
-  dq EMIT
-  dq EMIT
+  dq LIT, 'H', EMIT
+  dq LIT, 'e', EMIT
+  dq LIT, 'l', EMIT
+  dq LIT, 'l', EMIT
+  dq LIT, 'o', EMIT
+  dq LIT, '!', EMIT
+  dq NEWLINE
   dq EXIT
 
-TERMINATE:
-  dq .start
-  .start:
-  mov rax, $3C
-  mov rdi, 0
-  syscall
-
 MAIN:
   dq docol
   dq HELLO
   dq READ_WORD
-  dq PUSH_YOU_TYPED
+  dq LIT, you_typed_string
+  dq LIT, you_typed_string.length
   dq TYPE
   dq TYPE
   dq NEWLINE
@@ -206,7 +231,6 @@ READ_WORD.buffer rb READ_WORD.max_size
 READ_WORD.length db ?
 READ_WORD.char_buffer db ?
 
-
 ;; Return stack
 rq $2000
 return_stack_top: