corth-lang / Corth

A self-hosted stack based language like Forth
MIT License
7 stars 1 forks source link

`peek` keyword #40

Closed HuseyinSimsek7904 closed 6 months ago

HuseyinSimsek7904 commented 7 months ago

let variables pop a real stack item to the local memory which can then be used by reading that memory. However, sometimes it is not required to pop that stack item and it is enough to only read it. For this purpose, peek variables can be implemented. peek variables will not be popped to the local memory and instead, whenever the program tries to load its value, it will directly read its value from the real stack.

Possible syntax:

34 35
0 while dup len @64 < do peek i in
  // The loop iteration no is stored in 'peek' variable 'i'.
  // This will however make it impossible to use the stack items that was pushed before the loop iterator.
  + // This will cause an error from the syntax as it is trying to access the original loop iterator or the items that was pushed before.
end inc end drop // No need to push 'i', as it was never popped.

This will also help make the dup macro a lot faster. Previously, the compiler would compile a dup macro as (only if the stack item is a real stack item, most virtual stack items can directly be duplicated in the virtual stack without the need for adding more instructions):

    // macro dup let _a_ in _a_ _a_ end
    mov     r15, [local_ptr]
    pop     qword [r15 + 48]  // First pop the value into local memory.
    mov     r15, [local_ptr]
    push    qword [r15 + 48]  // Now, push the value from local memory twice.
    mov     r15, [local_ptr]
    push    qword [r15 + 48]

With peek variables, the compiled macro would be something like:

    // macro dup peek _a_ in _a_ end
    push    qword [rsp]

This saves at least 1 push cycle, 1 pop cycle and 3 mov cycles.

HuseyinSimsek7904 commented 6 months ago

9c8eb0f

Added peek keyword and updated libraries to use it in them.