tsoding / porth

It's like Forth but in Python
628 stars 50 forks source link

Implement Casting Intrinsics for casting types during the type checking stage #88

Closed ItsVerday closed 1 year ago

ItsVerday commented 2 years ago

Currently, there is no way to cast types during the type checking step. If you want to interpret an int as a bool or a ptr, you're out of luck. This PR implements three new Intrinsics, Intrinsic.CASTINT, Intrinsic.CASTBOOL, and Intrinsic.CASTPTR, which cast the top element of the stack to the specified type. These Intrinsics do nothing during the simulation process or when compiled, they are purely used during the type-checking step. The words for these Intrinsics are (int), (bool), and (ptr) (inspired by many of the C-style languages).

Example usage:

include "std.porth"

// Push the integer 1 (type = int) onto the stack. Then, cast the integer into a boolean. The type checker will no longer error when trying to use the value as a condition.
1 (bool)
// Use the value as a condition
if
  "No error!" stdout write drop
end

Additionally, this PR adds two new macros in std.porth: true and false, which are shorthand for 1 (bool) and 0 (bool) respectively.