Introduction
Henceforth is a programming language that aims to bridge the gap between imperative and stack-based languages, acting as a sort of softer introduction to the latter, as opposed to languages like Forth or Factor.
This reference describes the Henceforth language, its syntax, its semantics, and the constructs available to a programmer when writing Henceforth. While it may provide small guided examples related to each construct, it is not a tutorial, and it is not a formal specification of the compiler or the language. For a worked example, read the last section of the reference If you want to look something up while you already know roughly what you’re doing, this is the document for that.
Who this is for
This reference assumes you’ve programmed before and are comfortable with basic ideas like variables, functions, and control flow. It does not assume prior experience with stack-based languages or other more advanced features of the language, as those will be explained thoroughly.
How to read this reference
Each section documents one part of the language, generally moving from the smallests building blocks to larger ones. Sections are meant to be read in order the first time through, then looked independently afterwards.
Code examples will appear throughout the reference. Whenever an operation’s effect on the stack matters, it’s shown using stack notation in a comment (// (stack before) -> (stack after)), (always listing the entirety of the current stack, except for function and stack operation signatures, where only the relevant elements from the top of the stack are shown), where the top of the stack is to the right.
Structure of this reference
- Lexical Structure - how source code is divided into its lexical elements: identifiers, literals, comments, keywords and operators
- Types - the types available in Henceforth, their properties and how they’re written
- Stack Operations - the operators and keywords that work directly on the stack
- Variables - declaring and using variables
- Functions - declaring functions and function call stack context-switching
- Assignments and Calls - binding values and invoking functions, and the copy/move semantics that affect both
- Control Flow - conditionals and loops
- Arrays - array types, indexing, and bounds behavior
- Builtins - list of functions available in Henceforth and their purpose
- Tic-tac-toe - a fully worked example of a more complex Henceforth program
Lexical Structure
This section describes the basic lexical elements that make up Henceforth source code.
Comments
Comments are indicated by //.
// this is a comment
this is no longer part of the comment
Identifiers
Function and variable identifiers can contain a-z, A-Z, 0-9 and _, except for the first character, which can’t be a number.
add // valid
getValue2 // valid
_private // valid
2var // invalid (starts with number)
my-function // invalid (has hyphen)
hello world // invalid (has space)
Literals
Integer literals represent whole numbers:
42
-17
1000000
Floating-point literals represent decimal numbers:
3.14
-0.5
2.0
String literals are enclosed in double quotes:
"Hello, World!"
""
"Line 1\n Line 2"
The following escape sequences are allowed:
\n newline
\t tab
\\ backslash
\" double quote
\r carriage return
Boolean literals represent truth values:
true
false
Keywords
The following identifiers are reserved as keywords and can’t be used as an identifier.
fn
while
continue
break
return
let
if
else
false
true
i32
f32
str
bool
@pop
@pop_all
@dup
@swap
@over
@rot
@rrot
@nip
@tuck
@rev
@depth
Operators
Henceforth provides several categories of operators.
Arithmetic Operators
+ // addition
- // subtraction
* // multiplication
/ // division
% // modulo
Comparison Operators
== // equal to
!= // not equal to
< // less than
> // greater than
<= // less than or equal to
>= // greater than or equal to
Logical Operators
&& // logical AND
|| // logical OR
! // logical NOT
Miscellaneous
@ // stack block indicator
() // stack block delimiter
: // function signature separator
-> // return type indicator/argument redirection
{} // block delimiters
; // statement terminator (optional)
:= // copy top value to variable
&= // pop to variable
:> // copy arguments to function call
&> // move arguments to function call
[] // array indexing operator
[:]= // copy value to array at a certain index
[&]= // move value to array at a certain index
Types
Henceforth uses a simple, statically typed type system, which separates it from other stack-based languages, which tend to be dynamically typed or fully untyped. This allows for a more user-friendly experience.
Henceforth type system
Henceforth has four primitive types:
i32- 32-bit signed integerf32- 32-bit floating-pointstr- UTF-8 encoded textbool-trueorfalse
There are also arrays, represented by [<n>]<type> where <type> is any primitive type or an array, and n is an expression representing the size of an array. Unsized array types are allowed in function parameters and return types. More on arrays here.
Type annotations
Henceforth doesn’t have type inference, and all types must be specified in both function and variable declarations.
fn foo: ([][]i32 str) -> (bool str) { ... }
^^^^^^^^^^^ ^^^^^^^^
parameters return types
Note
Multiple parameters and return types are space-separated. For more on this, see the section about functions.
Type conversions
As of now, Henceforth does not have any explicit way to convert between types. The only implicit type conversions happen when arrays lose their size under certain conditions, explained in their own section.
Type compatibility
Henceforth checks types at compile time (if a program has a type error, it will not compile, or if using the interpreter, it will not run).
Two values are type-compatible only if they have the exact same type, with the exceptions described in Type Conversions.
Type checking applies to stack operations (except for stack keywords, which only check the current stack depth), variable assignment, array assignment and function calls. The compiler verifies that the values on the stack match what is expected.
Stack Operations
Being a stack-based language, the stack is the core of Henceforth. In case you’re unfamiliar with this data structure, it has a last-in first-out policy, where the last element that went in the stack is the first element to come out.
Stack blocks
Stack blocks are Henceforth’s way of separating imperative code from code that manipulates the stack directly. They are delimited by @( and ).
Pushing values to the stack
To push a value to the stack, just write a literal or a variable inside a stack block.
#![allow(unused)]
fn main() {
@(5) // () -> (5)
@(5.0) // (5) -> (5 5.0)
@(true) // (5 5.0) -> (5 5.0 true)
@("string") // (5 5.0 true) -> (5 5.0 true "string")
@(var) // (5 5.0 true "string") -> (5 5.0 true "string" var)
// var is only pushed to the stack if it has a value
}
Stack operators
The following operators are allowed on the stack:
#![allow(unused)]
fn main() {
+ // (i32 i32) -> (i32) or (f32 f32) -> (f32) or (str str) -> (str)
- // (i32 i32) -> (i32) or (f32 f32) -> (f32)
* // (i32 i32) -> (i32) or (f32 f32) -> (f32)
/ // (i32 i32) -> (i32) or (f32 f32) -> (f32)
% // (i32 i32) -> (i32) or (f32 f32) -> (f32)
== // (i32 i32) -> (bool) or (f32 f32) -> (bool)
!= // (i32 i32) -> (bool) or (f32 f32) -> (bool)
< // (i32 i32) -> (bool) or (f32 f32) -> (bool)
> // (i32 i32) -> (bool) or (f32 f32) -> (bool)
<= // (i32 i32) -> (bool) or (f32 f32) -> (bool)
>= // (i32 i32) -> (bool) or (f32 f32) -> (bool)
! // (bool) -> (bool)
|| // (bool bool) -> (bool)
&& // (bool bool) -> (bool)
[] // ([N]T i32) -> (T)
}
Warning
Out-of-bounds array access is checked and will cause a runtime panic. Read the section about arrays for more information on this topic.
Stack keywords
There are several keywords for working with the stack. These are denoted by the @ prefix and work with the stack despite not always being in a stack block.
#![allow(unused)]
fn main() {
@pop // (a) -> ()
@pop_all // removes everything from the stack
@dup // (a) -> (a a)
@swap // (a b) -> (b a)
@over // (a b) -> (a b a)
@rot // (a b c) -> (b c a)
@rrot // (a b c) -> (c a b) (equivalent to calling rot twice)
@nip // (a b) -> (b)
@tuck // (a b) -> (b a b)
@rev // reverses the entire stack
@depth // puts the current depth of the stack onto it, not including this element
}
Key differences from other stack-based languages
- In Henceforth, every function has its own stack, and these stacks can be seamlessly merged when entering or exiting a function (more on this here).
- Since not every operation affects the stack, Henceforth explicitly states whether something is changing it.
- For convenience, the compiler handles some of the stack manipulation when switching contexts, such as when entering or returning from a function, or when entering the body of an if statement.
Common mistakes
Some common mistakes when using the stack include:
#![allow(unused)]
fn main() {
@(+) // ERROR: stack underflow
}
If you attempt to use an operator or call a function without enough elements on the stack, you will get a stack underflow error.
#![allow(unused)]
fn main() {
@(5 "hello" +) // ERROR: type mismatch
}
A type mismatch occurs when an operator or function expects values of certain types but is given other types.
Variables
Variables are one of the many imperative features that make Henceforth so powerful. Instead of relying entirely on the stack, they allow for keeping state locally.
Declaring variables
Variables are declared with a name and a type:
#![allow(unused)]
fn main() {
let x: i32;
let y: [5]str;
}
Note
Variables can’t be initialized on declaration, they must be assigned from the stack afterward:
#![allow(unused)]
fn main() {
let x: i32 = 5; // not valid
}
Assigning from the stack
Once declared, variables can be assigned a value from the top of the stack using:
:=(copy)&=(move) See the section on assignments and calls for more details on the distinction between the two.
#![allow(unused)]
fn main() {
let var: i32;
@(1 2 3) // () -> (1 2 3)
:= var; // (1 2 3) -> (1 2 3), var = 3
}
#![allow(unused)]
fn main() {
let var: i32;
@(1 2 3) // () -> (1 2 3)
&= var; // (1 2 3) -> (1 2), var = 3
}
Reading variables
Variables can be pushed onto the stack like any other literal.
#![allow(unused)]
fn main() {
let var: bool;
@(5 6) // () -> (5 6)
@(>) := var; // (5 6) -> (false), var = false
@(var) // (false) -> (false false)
}
Warning
Reading from an unassigned variable will cause an error.
Scoping rules
Variables are always local to their scope, and you can’t declare variables on a global scope.
let x: i32; // not valid
fn foo: () -> () {
let x: i32; // valid
@(x); // valid
}
fn main: () -> () {
@(x); // invalid, x is not visible here
if @(...) {
let y: i32; // valid, scoped to this block
}
@(4) := y; // invalid, out of scope
}
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.
Arrays
Arrays are the primary way of grouping values in Henceforth. These are homogeneous collections (all elements must be the same type), and they can either have a fixed-length, or in very specific scenarios, can have an unknown length.
Declaring arrays
let arr: [4]str;
Declaring an array variable is fairly straightforward. It takes a length between square brackets, which as of version 1.0.0 must be an integer literal (no compile-time constants allowed as of now), and a type, which can be anything, including another array.
let arr: [5][3]i32; // this is an array of size 5, where each element is an array of size 3 of integers
Warning
Arrays are initialized with junk values.
Creating an array
An array can be created by either simply pushing an array literal to the stack, or by creating an array variable and assigning a value to each index.
Creating an array literal on the stack is done with the following syntax:
@([1 2 3]) // () -> ([1 2 3]), the stack depth is 1
Note
When creating an array literal, these are automatically fixed-length, and their length will always correspond to the length of the literal.
Reading from an array
Henceforth deals with indexing in a less traditional manner than imperative languages. Instead of having a single operation that lets you read an index from an array, and then simply assigning to it to write to that index, there are two separate operations.
To read from an array, we use the [] operator.
let arr: [3]i32;
@([1 2 3]) &= arr; // arr: [1 2 3]
@(arr 0);
@([]); // (arr 0) -> (arr[0])
Assigning to an array
Writing to an array in Henceforth uses the same philosophy as assigning to a variable or calling a function: there are two operators, one that copies the value to the array, and one that moves the value to it. This is further explained in the next section.
let arr: [5]i32;
let idx: i32;
@(0) &= idx;
@(2 idx) [&]= arr; // arr[idx] = 2; Since we used the move operator, the stack is empty.
@(idx 1 +) &= idx;
@(3 idx) [:]= arr; // arr[idx] = 3; We used the copy operator so the stack has (3 idx)
@pop_all;
// Now, the array contains [2, 3, _, _, _].
Note
In the given example, trying to read from indexes 2-4 will result in junk values being returned.
Type-checking arrays
As mentioned earlier, there is one exception to arrays needing a fixed-length. When defining a function with an array argument or return value, it can be of unknown length. For example:
fn index_array: ([]i32) -> () {
@(4 []); // if the array has size <= 4, this will not throw a compile-time error. (<arr>) -> (<arr[4]>)
@pop;
}
fn main: () -> () {
@([1 2 3]) &> index_array;
}
fn id_array: ([]i32) -> ([]i32) {}
fn id_array_sized: ([3]i32) -> ([3]i32) {}
fn main: () -> () {
@([1 2 3]) &> id_array; // ([1 2 3]) -> ([1 2 3]), HOWEVER, the returned array is now of type []i32
// this means that it cannot be printed, and will not throw a compile-time index out of bounds error
let arr: [3]i32;
:= arr; // we can circumvent this by assigning it back into a variable, as this makes it sized again
:> id_array_sized; // if the function returns a fixed-length array, it is already returned as such
@pop_all;
}
Casting a fixed-length array into an unknown length array is always valid as long as the element types match. The inverse operation is also always valid, however, if the array turns out to have more elements than that fixed-length, it will only keep the first N elements. If it has fewer elements, the leftover ones will be junk values.
Fixed-length array to fixed-length array type checking (e.g. passing it to a function with a fixed-length array argument, returning a fixed-length array, assigning to a variable) is only valid if both the lengths and the element types match.
Bounds checking
Whenever possible, Henceforth will throw a compile-time error if it can detect an out-of-bounds access to an array. As of version 1.0.0, this only occurs if the index is an integer literal, and the array has a fixed-length (this is already enforced to be an integer literal).
fn main: () -> () {
let arr: [4]i32;
@([1 2 3 4]) &= arr;
@(arr 5 []); // throws a compile-time error
@pop;
let n: i32;
@(6) &= n;
@(arr n []); // throws a run-time error
@pop;
}
Assignments and Calls
One of Henceforth’s defining features is the duality between copy and move operators. Essentially, a copy operator will leave its operands on the stack, while a move operator consumes them.
Henceforth has the following copy and move operators:
| Copy (keeps values on the stack) | Move (consumes them) | |
|---|---|---|
| Variable assignment | := | &= |
| Function call | :> | &> |
| Array assignment | [:]= | [&]= |
Copy operators have :, while move operators have &.
Variable assignment operators
The variable assignment operators are quite straightforward:
fn main: () -> () {
let x: i32;
@(1)
:= x; // (1) -> (1), x = 1; the value assigned to x stays in the stack
@pop;
@(3);
&= x; // (3) -> (), x = 3; the value assigned to x is removed from the stack
}
In variable assignments, doing a copy assignment is essentially equivalent to duplicating the value before doing a move assignment.
Function call operators
Similarly to variable assignment operators, function calls behave as follows:
fn drop: (i32) -> () { @pop; }
fn add: (i32 i32) -> (i32) { @(+); }
fn no_op: () -> () {}
fn main: () -> () {
@(1)
:> drop; // (1) -> (1), in copy calls, even though the function returns nothing, the argument stays on the caller's stack
@pop;
@(1)
&> drop; // (1) -> (), in move calls, the argument is consumed from the caller's stack
// this also works with multiple argument functions
@(1 2)
:> add; // (1 2) -> (1 2 3), in copy calls, all arguments get copied into the callee's stack
@pop_all;
@(1 2)
&> add; // (1 2) -> (3), in move calls, all arguments get moved to the callee's stack
@pop_all;
// calling a function that has no arguments with either operator will have the same exact result
&> no_op;
:> no_op;
}
Note
From the callee’s perspective, there is no difference between move and copy calls.
Array assignment operators
The semantics for array assignment operators can essentially be seen as a combination of both function calls and variable assignments.
fn main: () -> () {
let arr: [5]i32;
@(1 0)
[:]= arr; // (1 0) -> (1 0), arr = [1, _, _, _, _], both the index and the value stay in the stack in a copy array assignment
@pop_all;
@(2 1)
[&]= arr; // (2 1) -> (), arr = [1, 2, _, _, _], both the index and the value are moved from the stack in a move assignment
}
What actually gets copied and moved
Unlike languages with references like C++, Henceforth’s copy and move semantics are much simpler. Arrays are values, and copying or moving one into a variable, function, or the stack produces an independent array, and writes never propagate back to the source. For example:
fn f: ([]i32) -> () { ... }
fn g: () -> ([]i32) { ... }
fn main: () -> () {
let arr: [3]i32;
@([1 2 3]) := arr;
@(9 0) [&]= arr; // this modifies `arr`, but keeps the array in the stack intact
@pop_all;
@(arr) &> f; // similarly, if `f` modifies the argument, this does not modify `arr`, the same happens with `:>`
&> g;
:= arr;
@(1 0) [&]= arr; // this does not modify the array on the stack, even though its length is unknown
@pop_all;
}
When to use which
Copy operators are useful when you need to use the value for something else, e.g. comparing a number with its factorial, zeroing out an array. Move operators are useful for data transformation, and will likely be more intuitive for the average user.
Control Flow
In other stack-based languages, control flow is handled within the stack, leading to some questionable syntax (looking at you, Forth). Henceforth fixes this by handling it imperatively, leading to a more familiar way of doing things.
While loops
while is the only looping construct in Henceforth (there are no for loops).
They are used in the following way:
while @(<condition>) <optional function calls> {
<body>
}
The condition is a stack block, optionally followed by function calls (e.g. while @(x) &> is_positive {), and it must leave a bool on top of the stack. The body repeats while that bool is true. Unlike in Forth, the bool is popped automatically, so the body never sees it.
Warning
A
whileloop must not change the stack. At the end of every iteration, the stack must have the same depth and types as it had at the start, since the next iteration begins from there.
In practice, anything the body produces has to be consumed before the next iteration, usually by moving it into a variable:
fn less_than_ten: (i32) -> (bool) { @(10 <) }
fn sum_below_ten: () -> (i32) {
let i: i32; @(0) &= i;
let sum: i32; @(0) &= sum;
while @(i) &> less_than_ten {
@(sum i +) &= sum; // the result is moved into `sum`, so the stack is unchanged
@(i 1 +) &= i;
}
@(sum);
}
The following keywords can be used inside while loops to change its execution:
break- leaves the loop entirelycontinue- skips the rest of the body’s execution, starting the next iteration
If statements
if statements can be used to conditionally perform operations.
They are used in the following way:
if @(<condition1>) <optional function calls> {
<if-body>
} else if @(<condition2>) <optional function calls> {
<else-if-body>
} else if ... {
...
} else {
<else-body>
}
As in while, each condition is a stack block, optionally followed by function calls, that leaves a bool, which is popped automatically.
Since conditions consume their operands, what the stack looks like when a body starts matters:
- Every condition is evaluated starting from the stack as it was at the beginning of the
ifstatement. If the condition isfalse, the stack is restored to that state and the next condition is tried. - If a condition is
true, itsboolis popped and the body runs on whatever the condition left behind. - The
elsebranch has no condition, so it runs on the stack as it was at the beginning of theifstatement. - All branches must end with the same stack (same depth and types).
Note
An
ifwithout anelsemust leave the stack as it was at the beginning of the statement, since the “nothing happened” path has to match.
Example
This all may seem very confusing, let’s look at a simple FizzBuzz program.
fn fizz_buzz: (i32) -> (str) {
if @(15 % 0 ==) {
@("fizzbuzz");
} else if @(3 % 0 ==) {
@("fizz");
} else if @(5 % 0 ==) {
@("buzz");
} else {
@pop;
@("no fizzbuzz");
}
}
Let’s trace the program’s execution:
- On entering the
ifstatement, the stack contains only the argument:(n). - The first condition runs.
15 %consumesn, so the stack ends up as just(bool). - If the condition was
true, theboolis popped, leaving(). The body pushes"fizzbuzz", so the stack is(str), which matches the return type. - If it was
false, the stack is restored to(n)and the next condition is evaluated the same way. - Reaching the
else, there is no condition, so the stack is still(n). This is why only theelseneeds a@pop: the conditions consumed the argument, but theelsenever ran one. We popn, push"no fizzbuzz", and end with(str)as expected.
Summary
- Every
ifcondition starts from the stack at the beginning of the statement, and afalsecondition restores it. - A
truebranch starts from what its condition left, minus thebool. Theelsestarts from the stack at the beginning of the statement. - All branches of an
ifstatement must end with the same stack. - A
whileloop must end every iteration with the stack it started with.
Builtins
As of version 1.0.0, Henceforth does not contain a standard library. It does contain several builtin functions that are useful for I/O.
I/O Functions
Henceforth contains the following functions for reading input from the user and printing it out:
fn print: (T) -> ();
fn print_stack: () -> ();
fn input_int: () -> (i32);
fn input_float: () -> (f32);
fn input_str: () -> (str);
print_stack differs from other functions as it affects the caller’s entire stack, without explicitly passing it, printing it in reverse order (bottom to top), and works with any type.
print simply prints its argument, and works with any type.
The input_* functions all take input from the standard input, and put the return value in the stack. There are no internal checks to this input, e.g. passing a string as input when input_int is called is perfectly valid (will simply print 0).
Tic-Tac-Toe
To show the core ideas of Henceforth, let’s walk through a worked example of a Tic-Tac-Toe program.
Setting the stage
We will represent the board as an array with 9 strings, where " " will represent an empty square, and "X", "O" represent each player’s moves. For convenience, we will reference the player that uses X as player 1.
We define our main function, create our board array, and fill it with " " strings. This represents an empty board.
fn main: () -> () {
let board: [9]str;
// to fill the board, we iterate over each of its indices using a while loop, and use a copy array assignment to fill the array
let idx: i32; @(0) &= idx;
@(" " idx);
while @(idx 9 !=) {
// the stack state is currently (" " idx)
[:]= board;
// using a copy array assignment allows us to increment `idx`
// without pushing it repeatedly to the stack, while keeping " " in the stack for the whole duration of the loop
@(1 +) := idx;
}
@pop_all; // after the loop, the stack state is (" " idx), so we pop these values as they are no longer useful
@("\nBeginning Tic-Tac-Toe:\n") &> print;
}
Printing the board
Next, we print our board so the user can see the initial board state:
...
@(board) &> print_board;
Now, we define print_board as follows:
fn print_board: ([9]str) -> () {
let board: [9]str; &= board;
let idx: i32; @(0) &= idx;
@("\n") &> print;
// we iterate over each index in the board
while @(idx 9 !=) {
// every 3 indices, starting from the first one, we print a separating line
if @(idx 3 % 0 ==) { @(" |-----------|\n") &> print; }
// for every index we print a vertical bar, to represent the left border of the slot,
// then index into the array and print the value
@(" | ") &> print; @(board idx []) &> print;
// at the end of each line, we print the right border
if @(idx 3 % 2 ==) { @(" |\n") &> print; }
@(idx 1 +) &= idx;
}
// we finish the board by printing the final separating line
@(" |-----------|\n\n") &> print
}
The game loop
Next, back in main, we define the game loop:
#![allow(unused)]
fn main() {
...
let is_player1_turn: bool; @(true) &= is_player1_turn;
// while a win hasn't been found yet with the current board, we loop
// we use a copy call because `board` will be used inside the loop
while @(board) :> game_not_ended {
// here, the stack contains (board)
@("please input a move") &> print;
// depending on which player's turn it is, we print the corresponding prompt, and add its "piece" to the stack.
if @(is_player1_turn) {
@(" (player X's turn):\n") &> print; @("X")
} else {
@(" (player O's turn):\n") &> print; @("O")
}
// the stack now contains (board "X"/"O")
// we get the position from user input
:> input_int
// then we pass it to a function called `tic_tac_toe`
// at this point, the stack contains (board "X"/"O" position)
&> tic_tac_toe
// we need a way to update the board, since functions can't mutate arrays that are passed in,
// `tic_tac_toe` must return the new board
&= board;
// with all this information, we can infer that `tic_tac_toe`'s signature will be ([9]str str i32) -> ([9]str)
@(is_player1_turn !) &= is_player1_turn; // we swap the current player
}
}
Checking for a win
We define game_not_ended as a function that checks for a win from each player, using a helper function called player_win, and they are defined as such:
fn player_win: ([9]str str) -> (bool) {
let player: str; &= player;
let board: [9]str; &= board;
// for each of the possible win configurations for the current player,
// we check if all of those positions have the current player string
//
// each line of this stack block will produce a single boolean that represents
// whether a win was found for that configuration
// and the last line checks if any of them are true
@(
// horizontal win
board 0 [] player == board 1 [] player == && board 2 [] player == &&
board 3 [] player == board 4 [] player == && board 5 [] player == &&
board 6 [] player == board 7 [] player == && board 8 [] player == &&
// vertical win
board 0 [] player == board 3 [] player == && board 6 [] player == &&
board 1 [] player == board 4 [] player == && board 7 [] player == &&
board 2 [] player == board 5 [] player == && board 8 [] player == &&
// diagonal win
board 0 [] player == board 4 [] player == && board 8 [] player == &&
board 2 [] player == board 4 [] player == && board 6 [] player == &&
// at this point there will be 8 booleans in the stack, and we "or" them,
// so that if any of them are true (a win is found), the result is true
|| || || || || || ||
)
}
// `game_not_ended` is trivially defined, we check for a win from either player, and return false if one is found, otherwise we return true
// note that this doesn't handle ties, and will loop infinitely if one occurs
// as an exercise, you can try to implement this yourself
fn game_not_ended: ([9]str) -> (bool) {
if @("X") &> player_win {
@(false)
} else if @("O") &> player_win {
@(false)
} else {
@pop @(true)
}
}
Showing the result to the user
Back in main, after the while loop, we know that a win has been found, so we just check which player won, and print it.
#![allow(unused)]
fn main() {
...
@(board)
// the logic behaves similarly to `game_not_ended`, but instead, we add a string to the stack
// saying which player won, then print it at the end
if @("X") &> player_win {
@("the winner was player 'X'!\n")
} else if @("O") &> player_win {
@("the winner was player 'O'!\n")
}
&> print;
}
If you run this program, you get an interactive Tic-Tac-Toe program, that looks something like this:
Beginning Tic-Tac-Toe:
|-----------|
| | | |
|-----------|
| | | |
|-----------|
| | | |
|-----------|
please input a move (player O's turn):
1
|-----------|
| O | | |
|-----------|
| | | |
|-----------|
| | | |
|-----------|
please input a move (player X's turn):
2
|-----------|
| O | X | |
|-----------|
| | | |
|-----------|
| | | |
|-----------|