• Interpretive if-then

    From Ruvim@ruvim.pinka@gmail.com to comp.lang.forth on Fri Mar 15 11:09:45 2024
    From Newsgroup: comp.lang.forth

    For interactive testing a definition body, it's convenient to have
    appropriate interpretation semantics for all used words.

    Recently I came up with an idea how to easily implement such semantics
    for the if-then construct. A usual problem is that it's difficult to
    correctly skip the false branch in all edge cases [1,2].

    My idea is that the false branch is compiled into an unnamed definition
    and then discarded. Therefore, such if-then can contain only phrases
    that are usable regardless of the state.

    An implementation (PoC) is following.


    ===== begin of "cond-interpretive.fth"

    [undefined] compilation [if]
    : compilation ( -- flag ) state @ 0<> ;
    [then]

    [undefined] exch-current [if]
    : exch-current ( wid1 -- wid2 )
    get-current swap set-current
    ;
    [then]

    [undefined] >order [if]
    : >order ( wid -- ) >r get-order r> swap 1+ set-order ;
    [then]
    [undefined] order> [if]
    : order> ( -- wid ) get-order swap >r 1- set-order r> ;
    [then]


    wordlist constant cond-interpretive
    wordlist constant cond-interpretive-private

    cond-interpretive-private dup >order exch-current

    0 value n \ nesting level of "if"
    : inc-n ( -- ) 1 n + to n ;
    : dec-n ( -- ) -1 n + to n ;
    : ?n0 ( -- ) n if 0 to n -22 throw then ;

    cond-interpretive set-current
    \ NB: now the wordlist "cond-interpretive" is compilation word list,
    \ and it's absent in the search order.

    : if ( x -- | -- ) ( C: -- | -- orig )
    compilation if inc-n postpone if exit then
    ?n0 ( x ) if exit then :noname
    ; immediate

    : else ( orig1 -- orig2 )
    compilation if
    n if postpone else exit then
    postpone ; drop exit
    then ?n0 :noname
    ; immediate

    : then ( orig -- )
    compilation if
    n if dec-n postpone then exit then
    postpone ; drop exit
    then ?n0
    ; immediate

    order> drop exch-current >order
    \ NB: now the wordlist "cond-interpretive" is in the search order top.

    ===== end of "cond-interpretive.fth"


    [1] https://forth-standard.org/standard/tools/BracketELSE#contribution-74
    [2] https://github.com/ForthHub/discussion/discussions/143


    --
    Ruvim

    --- Synchronet 3.20a-Linux NewsLink 1.114