https://github.com/ponyatov/nims/blob/67bf8b774f0a113edb933ff1b23055fd35722d5a/habr/FORTH.nim
How can I limit VM addresses size using Nim type system?
I want to write very limited FORTH machine using bytecode interpreter, so need to limit addresses size to Msz or at least of 16-bit addressing. The same about integer sizes.
Is it possible with type system only, or I need to hack with templates or macro to do it?
what if I want int5 and int3 in some places? (memory addressing and stack pointers)
As example here
type # IoT 16bit
cell = int16
ucell = uint16
I run this bytecode interpreter in 64-bit systems. But I limit the "machine" word [u]CELL size to 16bit as it mostly will run in on-air microcontroller devices (Lora/NbIoT). There is lot of roaring about the power of rich type systems especially in Haskell community 8-) So I thought about using type checking in Nim code which will track the type clearance in memory and stacks fluffing code.
Next,
const # memory sizes
Msz = 0x1000
Rsz = 0x100
Dsz = 0x10
These constants limit VM memory sizes, they should be mostly the power of two. I can limit all registers by applying bitmask on every instruction or stack pointer increment. Here the Nim metaprogramming can play by automatically insertion addition checking and limiting code.
var # memory
M : array[Msz,byte ]
Cp = cell(0)
Ip = cell(0)
var # data stack
D : array[Dsz,int16 ]
Dp = cell(0)
Well there is
type
Int3 = range[0..7]
but watch out, its size is 1 byte. There is also:
type
Obj = object
a {.bitsize: 3.}: int
b {.bitsize: 5.}: int
Which is Nim's syntax for C's bit fields.
Do subrange types not offer what you are looking for?
type VmAddr = range[0..63]
PS: I wrote a forth once, and it's even in production in a few embedded devices! See https://github.com/zevv/zForth