• Stack-Guard Operators

    From Lawrence D'Oliveiro@ldo@nz.invalid to comp.lang.postscript on Sun Jun 2 03:45:04 2024
    From Newsgroup: comp.lang.postscript

    In my toy GXScript language, I have added a pair of stack-guard operators,
    and the concept of multiple operand stacks.

    The rCLstackbeginrCY operator, invoked as

    -2n-+ </

    pops the top -2n-+ operands off the current operand stack and copies them to
    a new, initially empty operand stack, which becomes the current operand
    stack (the previous one being saved on a stack of operand stacks).

    The corresponding rCLstackendrCY operator, invoked as

    -2n-+ />

    expects to find exactly -2n-+ operands on the current operand stack; it pops these off, discards the current operand stack and restoring the previous
    one popped off the stack of operand stacks, and copies these onto this
    stack.

    These operators enforce a discipline to try to minimize stack confusion, accumulation of unwanted junk on the stack etc.

    Here is a very simple example: a function called rCLtryrCY which takes 2 operands and returns one result.

    /try
    {
    2 </
    add
    1 />
    }
    ddef

    If you invoke it as follows:

    2 3 try =

    it returns the expected result rCL5rCY.

    Supposing there was a bug in the code, where it ended up leaving an extra
    item on the stack before returning:

    /try
    {
    2 </
    add
    (junk)
    1 />
    }
    ddef

    Now when you try invoking it as rCL2 3 try =rCY as before, you will get the exception rCLstackmismatchrCY.

    Conversely, supposing there are extra items on the stack that should not
    be accidentally gobbled by the function:

    (leaveme) 2 3 try = =

    is expected to print the result rCL5rCY, followed by the rCLleavemerCY string that
    was pushed there before. Supposing the function had a bug in it like this:

    /try
    {
    2 </
    pop add
    1 />
    }
    ddef

    Instead of accidentally gobbling the rCLleavemerCY string, it will fail with a rCLstackunderflowrCY exception. This helps to catch the bug sooner, rather than getting to some later point and wondering why there are fewer items
    on the stack than you expect.
    --- Synchronet 3.21d-Linux NewsLink 1.2