• Stack-Guard Operators

    From Lawrence D'Oliveiro@21:1/5 to All on Sun Jun 2 03:45:04 2024
    In my toy GXScript language, I have added a pair of stack-guard operators,
    and the concept of multiple operand stacks.

    The “stackbegin” operator, invoked as

    «n» </

    pops the top «n» 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 “stackend” operator, invoked as

    «n» />

    expects to find exactly «n» 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 “try” 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 “5”.

    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 “2 3 try =” as before, you will get the exception “stackmismatch”.

    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 “5”, followed by the “leaveme” 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 “leaveme” string, it will fail with a “stackunderflow” 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.

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)