Crate fortraith

Source
Expand description

§Compile-Time Compiler That Compiles Forth to Trait Expressions

“We all know Rust’s trait system is Turing complete, so tell me, why aren’t we exploiting this???” - Nathan Corbyn

 #![recursion_limit = "256"]
 #[macro_use] extern crate fortraith;
 use fortraith::*;

 forth!(
     : factorial (n -- n) 1 swap fact0 ;
     : fact0 (n n -- n) dup 1 = if drop else dup rot * swap pred fact0 then ;
     5 factorial
     return type Out as top
 );
 assert_eq!(Out::eval(), 120);

This crate allows the user to exploit traits as much as wanted. It contains around 10% black trait magic, around 40% of the darkest kind of evil macro magic and around 50% of good quality docs (you are here!). Everything is tested and ready for production (a joke).

Although you might not want to really use it in production it serves to show how powerful Rust’s trait system and macro_rules! really are.

If you are new to forth, it is a simple stack-based language. Every operation is done on the stack and grabs and pushes values into it. For example 2 2 + would push 2 to the top of the stack 2 times, take and add them together and push the result back to the stack (So the stack would have only 4 in it if it was empty before pushing the first 2). Its simplicity makes it a usual target for recreational implementation.

See documentation for traits and the macro to see many examples and learn how to use fortraith, and abuse the Rust’s trait system!

“Ok, ok, all that’s fine, but where is my FizzBuzz implementation?” you might ask. Fear not, as tradition dictates FizzBuzz is implemented in fortraith as well.

Macros§

forth
Compile forth to trait expressions

Traits§

Eval
trait_eval to Rust conversion
and
Logical and two top elements
drop
Remove the top element
dup
Duplicate the top element
eight
( 8 ) Constant number
eq
( = ) Check if two top elements are equal
fact
Calculate the factorial of the top element
falsef
( false ) Constant boolean
fib
Index the fibonacci sequence with the top element
five
( 5 ) Constant number
four
( 4 ) Constant number
iff
( if / else / then ) conditional expression
less
( < ) Check if the second top element is less than the top elements
minus
( - ) Subtract the top element from the second top element
modulo
( % ) Calculate the rest from dividing the second top element by the top element
mult
( * ) Multiply two top elements
nine
( 9 ) Constant number
not
Apply logical not to the top element
one
( 1 ) Constant number
or
Logical or two top elements
plus
( + ) Add two top elements together
pred
Decrement the top element
rot
Rotate three top elements
seven
( 7 ) Constant number
six
( 6 ) Constant number
swap
Swap two top elements
ten
( 10 ) Constant number
three
( 3 ) Constant number
top
Get the top element
truef
( true ) Constant boolean
two
( 2 ) Constant number
zero
( 0 ) Constant number