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:
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
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:
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
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
READ_WORD.length db ?
READ_WORD.char_buffer db ?
-
;; Return stack
rq $2000
return_stack_top: