Wrongforth

About

Wrongforth is an attempt to make Forth suitable for reversable computing ( inspired by Janus ). Currently Wrongforth is implemented in GForth.

Implementation

There are two implementation attempts for wrongForth:

Dual Compilation

As Forth is postfix reversing at operand level is a tricky, so in this implementation the word is reversed line wise to keep the postfix semantics. Here is an example computing the Fibernachi numbers:

1 direction ! include utils.fs : fib ( -- ) recursive n @ 0= _if x1 1 over @ swap _+ swap ! x2 1 += _else n 1 -= fib x1 x2 @ += x1 x2 <=> x1 @ x2 @ = _then ;

and the backwards code:

0 direction ! \ redefine primitive words like += with backward semantics include utils.fs : fib-1 ( -- ) recursive x1 @ x2 @ = _then x1 x2 <=> x1 x2 @ += fib-1 n 1 -= _else x2 1 += x1 1 += n @ 0= _if ;

This attempt is pretty much straight foreward and easy to implement, it works on every Forth system and is as fast as normal computations, but words only need to be implemented in one direction, the backward implemantation is just line flipping.

Reverse Computation

A more elaborate approach is to make the forth system itself reversible. To accomplish that the following things need to be thought of:

Primitives:

: over+ forewards? if over+ else over- then [resume] ; : over- forewards? if over- else over+ then [resume] ; : swap swap [resume] ;

The [resume] words contains the magic of manipulating the IP, although its quite simple:

: [resume] POSTPONE direction POSTPONE @ POSTPONE r> POSTPONE swap POSTPONE + POSTPONE >r ; immediate

But now lets see the Fibernachi implemantation itself:

: fib ( n x1 x2 -- n x1 x2 ) beg bwdcheck third0= if 1+ \ increment x2 swap 1+ \ increment x1 swap else rot \ decrement n 1- -rot callfib \ recurse swap \ add x2 to x1 and exchange the values over+ then 2dup= fwdcheck end ;

Explanation of the Code:

Howto

Dual Compilation

Write foreward code and use a script to get a backward version of it, don't forget to redefine ( include ) the reversible primitives after each direction change

Reverse Computation

Currently there are lots of restrictions for this attempt, as it only imposes a proof of concept, download the full Fibernachi-example and if you have any further questions, do not hesitate to ask me ;)

Future

As this proof of concept showed its basically possible to make forth reversible, the next step is to create a fully reversible forth system, which has features like paired branches, reversible words down to machine code and a direction register. Maybe Bruteforth will be reversible.


Downloads