\ not a module, needs 'load' to define undefined symbols
\ -*- forth -*-


\ neeed to be provided by users
\ declare console-on
\ declare console-off
\ declare receive
\ declare transmit
\ declare hello


\ --- INTERPRETER ---

\ control xts
: jsr    push receive TOSL ! receive TOSH ! ;
: ack    0 transmit ;  \ 0, so it's compatible with sending strings

    
\ programming: these run code to protect the receiver/transmitter
\ console to get confused from interrupts being disabled during
\ programming, and send an ack.
: ferase   console-off flash erase   console-on ack ;
: fprog    console-off flash program console-on ack ;


\ token 0 is nop, so a stream of zeros can be used as soft interrupt

\ Except for nop and reset, all tokens return at least one byte result
\ to synchronize on. The protocol has Remote Procedure Call (RPC)
\ semantics, but implements it without the need for simultaneous
\ buffering and handling.
    
\ token --
: interpret
    #x0F and route
             ., receive/ack  ., transmit ., jsr/ack .,
     lda     ., ldf          ., ack      ., reset
     n@a+    ., n@f+         ., n!a+     ., n!f+    .,    
     chkblk  ., preply       ., ferase   ., fprog   ;



: receive/ack receive ack ;
: jsr/ack jsr ack ;    
        
\ bytecode interpreter main loop
: interpreter receive interpret interpreter ;

\ Block transfer. These take the size from the command input to make
\ the host -> target protocol context-free.
    
: n@f+
    receive
: fsend \ n --   
    for @f+ transmit next ;
    
: n@a+  receive for @a+ transmit next ;
: n!f+  receive for receive !f+ next ack ;
: n!a+  receive for receive !a+ next ack ;

\ strings    
: preply hello @f 1+ fsend ;   


\ pointer initialization
: lda  receive receive a!! ack ;
: ldf  receive receive f!! ack ;
    
\ program block memory check
: chkblk 255 64 for @f+ and next transmit ;

