rlwhitcomb / utilities

Some of my personal utility programs
MIT License
2 stars 0 forks source link

Current implementation of "leave" in Calc is insufficient #600

Closed rlwhitcomb closed 10 months ago

rlwhitcomb commented 1 year ago

Consider a function with nested loops, where inside the innermost loop we want to leave the function on a certain condition. Just "leave x" will exit the innermost loop, but not the outer one(s), and certainly won't exit from the function.

Java handles this with a "named break" where any statement can have a label, as well as a "return" statement. So, maybe "return" in addition to "leave" would be simplest....

rlwhitcomb commented 1 year ago

Another thought would be syntax such as:

leave loop [value]
leave function [value]
leave while [value]

or

leave all loops [value]

where the keyword(s) after leave are optional. Although, I have no idea how to implement leave all loops with the current paradigm of throwing a LeaveException, or even what that would mean in the context of multiple nested loops inside a function inside of multiple nested loops ....

rlwhitcomb commented 10 months ago

I think I want to implement this as follows:

  1. Add optional "label" syntax to "loop" and "while"
  2. Add optional ": label" syntax to "leave" as in "leave : loop1 123"
  3. Allow "label" to refer to a function name as well as the loop/while labels.

Several reasons for this changed syntax:

rlwhitcomb commented 10 months ago

Changing to leave loop1: 123 instead (it repeats the label format itself and seems to flow more nicely). Note that "leave" inside a function has to work differently too: either there is a label on the "leave" and it matches the function name, or there is no label; either way. The only way it doesn't get caught is if there is a label and it doesn't match the function name. Also, the outer level catch has to produce an error if there was a label on the "leave" (meaning nobody matched on the way up).

rlwhitcomb commented 10 months ago

I briefly considered adding (optional) labels to next as well as leave, but I don't think it would solve any pressing needs, and would be confusing since next can be used inside case, but not inside a function, so the parallel to leave is not perfect. But (obviously) we could reconsider this possibility in a separate issue if the need / utility ever arises in the future.