5 comments

[ 15.4 ms ] story [ 433 ms ] thread
Pretty ugly Forth code. I'm surprised that big chain of "SWAP DUP XXX =" didn't get factored into a loop over a lookup table. Is this code time-critical somehow?

edit: for example, ('cause who doesn't like seeing more Forth code on HN?)

  create table 66 , 271 , 3 , 40 , 101 ,
  4 constant table-size-1
  \ ...
  false table-size-1 for
    over i table + @ = or
  next swap drop
Would've made that bug harder to miss, too.
Isn't this generated code, ie. a nicer FORTH macro in the original source (which we don't see) is being turned into some ugly case-like series of SWAP DUP XXX =?
Possibly. I guess the other part that gets me is that you could make the straight-line sequence quite a bit shorter (and with a constant stack footprint) by reordering stack arguments slightly.

Their code starts with a value on the stack, primes the unrolled loop and then goes into a series of nested constructs like:

  DUP X1 =
  SWAP DUP X2 = 
    SWAP DUP X3 =
      SWAP DUP X4 =
        ...
        SWAP DROP
      OR
    OR
  OR
This builds up a growing mound of flags on the stack and then collapses them down at the end. As the mound is built, the value is constantly flipped up to the top of the stack and then covered with a flag. A better way to do this would be to collapse the flags as you go:

  DUP  X1 =
  OVER X2 = OR
  OVER X3 = OR
  ...
  SWAP XN = OR