+entry main
+
+include "impl.asm"
+
+main:
+ cld ; Clear direction flag so LODSQ does the right thing.
+ mov rbp, return_stack_top ; Initialize return stack
+
+ mov rax, MAIN
+ jmp qword [rax]
+
+program: dq MAIN
+
+;; The codeword is the code that will be executed at the beginning of a forth
+;; word. It needs to save the old RSI and update it to point to the next word to
+;; execute.
+docol:
+ pushr rsi ; Save old value of RSI on return stack; we will continue execution there after we are done executing this word
+ lea rsi, [rax + 8] ; RAX currently points to the address of the codeword, so we want to continue at RAX+8
+ next ; Execute word pointed to by RSI
+
+;; This word is called at the end of a Forth definition. It just needs to
+;; restore the old value of RSI (saved by 'docol') and resume execution.
+forth_asm EXIT, '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.
+forth_asm LIT, 'LIT'
+ lodsq
+ push rax
+ next
+
+;; Given a string (a pointer following by a size), return the location of the
+;; dictionary entry for that word. If no such word exists, return 0.
+forth_asm FIND, 'FIND'
+ mov [.rsi], rsi
+
+ pop [find.search_length]
+ pop [find.search_buffer]
+ mov rsi, [latest_entry] ; Start with the last added word
+ call find
+ push rsi
+
+ mov rsi, [.rsi]
+ next
+ push rsi
+
+ mov rsi, [.rsi]
+ next
+
+;; Given an entry in the dictionary, return a pointer to the codeword of that
+;; entry.
+forth_asm TCFA, '>CFA'
+ pop rax
+ add rax, 8 ; [rax] = length of name
+ movzx rbx, byte [rax]
+ inc rax
+ add rax, rbx ; [rax] = codeword
+ push rax
+ next
+
+;; BRANCH is the fundamental mechanism for branching. BRANCH reads the next word
+;; as a signed integer literal and jumps by that offset.
+forth_asm BRANCH, '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
+
+;; 0BRANCH is like BRANCH, but it jumps only if the top of the stack is zero.
+forth_asm ZBRANCH, '0BRANCH'
+ ;; Compare top of stack to see if we should branch
+ pop rax
+ cmp rax, 0
+ jnz .dont_branch
+.do_branch:
+ jmp BRANCH.start
+.dont_branch:
+ add rsi, 8 ; We need to skip over the next word, which contains the offset.
+ next
+
+;; Duplicate the top of the stack.
+forth_asm DUP_, 'DUP'
+ push qword [rsp]
+ next
+
+;; Execute the codeword at the given address.
+forth_asm EXEC, 'EXEC'
+ pop rax
+ jmp qword [rax]
+
+;; Expects a character on the stack and prints it to standard output.
+forth_asm EMIT, 'EMIT'
+ pushr rsi
+ pushr rax
+ mov rax, 1
+ mov rdi, 1
+ lea rsi, [rsp]
+ mov rdx, 1
+ syscall
+ add rsp, 8
+ popr rax
+ popr rsi
+ next
+
+;; Prints a newline to standard output.
+forth NEWLINE, 'NEWLINE'
+ dq LIT, $A
+ dq EMIT
+ dq EXIT