Search code examples
forthgforth

How can I access a shadowed definition in Forth?


When a word is redefined, is it possible to access the old word?

Imagine there is a word foo defined and redefined

: foo ( n -- 2*n ) 2* ;  ok
: foo ( n -- 2*n+1 ) foo 1+ ; redefined foo   ok
10 foo . 21  ok

foo here executed both definitions.

Is it possible to execute the first definition ("second-foo")?

21 second-foo . 42 ok

To see it?

see second-foo
: foo
  2* ; ok

Solution

  • A simple way to access a shadowed definition is to create a synonym for the definition before creating a new definition with the same name.

    synonym old-foo foo
    : foo ... ;
    

    Another way is to use introspection tools, namely the word traverse-wordlist. Using this word we can define a word find-name-nth-in that is similar to the standardized word find-name-in ( c-addr u wid -- nt|0 ), but it finds n-th shadowed word, as follows:

    : find-name-nth-in ( c-addr1 u1 u wid -- nt|0 )
      >r 1+
      [: ( sd u nt -- sd u true | sd nt 0 false )
        2>r 2dup r@ name>string compare if rdrop r> true exit then
        r> r> 1- dup if nip then dup 0<>
      ;] r> traverse-wordlist ( sd u | sd nt 0 )
      if 2drop 0 exit then nip nip
    ;
    

    This find-name-nth-in word returns an nt for the word that has the given name in the given word list, and after which exactly u words with the same name (case-sensitively) were defined in the word list, or 0 otherwise.

    A test case:

    : ?name ( nt|0 -- nt ) dup 0= -13 and throw ;
    
    : foo ." old" ;
    : foo ." new" ;
    
    "foo" 0 forth-wordlist find-name-nth-in ?name name>interpret execute
    \ prints "new"
    
    "foo" 1 forth-wordlist find-name-nth-in ?name name>interpret execute
    \ prints "old"
    
    

    In Gforth the word xt-see can be used as:

    "foo" 1 forth-wordlist find-name-nth-in ?name name>interpret xt-see