Forth in Arm64
我們知道 forth 是一個 stack-based 的連接語言,極度簡單的概念讓它非常容易被 port 到各種機器上,並且不需要太多的 runtime 支援。下面我就來介紹怎麼在 arm64(aarch64) 的 macOS 下寫出對應的 forth 指令。
1. Integer
對整數這種字面值,我們只需要推進 stack
mov x0, #<integer value> str x0, [sp]
2. arithmetic
對 +, -, *, / 這些二元運算來說,我們都把 current_offset 加上
=wordsize=(在 64bits 系統下是 8),然後
ldp x0, x1, [sp, <current_offset>] <op> x0, x1, x0 str x0, [sp, <current_offset + wordsize>]
+:add-:sub*:mul/:sdiv
3. dup
dup 應該算是經典了,它的用途就是把 stack top 複製一份再放到 top 上
ldp x0 [sp, <current_offset>] stp x0, x0, [sp, <current_offset>]
4. 定義 word
自定義 word 的方式是用 : 開始, ; 結束,例如
: ^2 ( x -- x^x ) dup * ;
這樣我們就可以寫出
3 ^2
的程式。對 compiler 來說,就是把 ^2 展開成裡面的 word