Functions
Functions in Henceforth are statically typed, giving the programmer a better abstraction than the normal approach of “pop arguments from stack, do operation x, push return values to stack”, ensuring richer behavior than other untyped stack-based languages.
Declaring functions
Functions are declared with a name, argument types, and return types:
fn function_name: (i32) -> (str bool) {
...
}
Note
Functions must be declared on the global scope. Nested functions are not allowed.
Calling functions
There are two operators to call a function:
@(1 2 3) // () -> (1 2 3)
:> foo; // (1 2 3) -> (1 2 3 <return values of foo>)
@pop_all;
@(1 2 3) // () -> (1 2 3)
&> foo; // (1 2 3) -> (<return values of foo>)
@pop_all;
This mirrors the := and &= variable assignment operators, and behaves similarly. As with variable assignments, which are type-checked against the variable’s declared type, a function call’s arguments are type-checked against the function’s declared parameter types.
More on the semantics between these operators on Assignments and Calls.
Context switching between calls
Every function has its own stack. When a function is called, the arguments are moved into the callee’s stack. When it returns, its remaining stack is first type-checked against the declared return type, and then merged back into the caller’s stack.
Here’s an example of a function that mimics the @dup keyword, duplicating the top of the stack.
fn dup: (i32) -> (i32 i32) {
let temp: i32;
:= temp; // (<arg>) -> (<arg>), temp = <arg>
@(temp); // (<arg>) -> (<arg> <arg>)
}
fn main: () -> () {
@(5) &> dup;
@pop_all;
}
Now we can trace the program’s execution:
mainstarts with an empty stack.@(5) &> duppushes 5, then moves it out ofmain’s stack and intodup’s stack.main’s stack is now(),dup’s is(5).- Inside
dup,:=temp copies the top of the stack intotemp, which now has the value5, without popping it from the stack. @(temp)pushes the value of that variable to the stack, sodup’s stack is now(5 5).dupthen returns. No explicitreturnstatement is needed, since a function implicitly returns whatever is left on its stack.returnis only required for early returns. As mentioned earlier, when leaving a function, before merging the stacks, its stack is type-checked against its return types. Sinceduphas return type(i32 i32)and the current stack is(5 5), it matches the expected types and return successfully.- On return,
dup’s stack merges back intomain’s, which is now(5 5). Since we moved the argument ofdupout ofmain’s stack when callingdup,main’s stack was left empty, so it is simply the return values ofdup. - To ensure that
maintype-checks on return, since this function is expected to have nothing on the stack on return, we pop all of the existing elements using@pop_all.