technoblogy / ulisp-esp

A version of the Lisp programming language for ESP32-based boards.
MIT License
111 stars 37 forks source link

non-CL behavior of `(return)` when nested inside function call #69

Open dragoncoder047 opened 1 year ago

dragoncoder047 commented 1 year ago
CL-USER> (defun bar (x)
             (if (eq x 3) (return)))
BAR
CL-USER> (defun foo ()
             (dotimes (i 10)
                (format t "~a~%" i)
                (bar i)))
FOO
CL-USER> (foo)
0
1
2
3
*** Error: RETURN-FROM: no block named NIL is currently visible

uLisp just stops, no error.

If the goal is to adhere to Common Lisp, this should be fixed. But I frankly like this behavior, because it allows you to define your own "exit" functions that can make decisions, do custom cleanup, etc. and then exit the loop even if it is farther up the call stack.

technoblogy commented 1 year ago

I would say that the goal is to adhere to Common Lisp to the extent that uLisp programs should give the same result when run on Common Lisp, but I think it's acceptable for error handling to be different. uLisp doesn't have any concept of named blocks using tagbody and go, so I'm not sure I could detect that invalid (return).

dragoncoder047 commented 1 year ago

I'm not sure I could detect that invalid (return).

If you want to fix it, I think that the place to do the check would be inside where lambdas get executed (in eval) and bail if RETURNFLAG is set when the progn returns.

dragoncoder047 commented 1 year ago

Also, while I am less hesitant to try to implement tagbody and go in uLisp (because it's basically goto), it probably would have the same approach as how I implemented throw and catch (which are also basically goto's but simpler).

dragoncoder047 commented 1 year ago

Another idea: block and return-from are pretty much semantically equivalent to catch and throw, except that catch/throw evaluate the "tag" argument (so it must be quoted or a keyword) and block/return-from don't (so you can't supply the tag in a variable)

The other two things about block/return-from (loop opens a block named nil, apparently, and blocks are not preserved across call stack entries when defun's are called) I think could be implemented using a similar technique, with a global variable called ReturningFrom or something, and check that when returning from blocks, and in the lambda implicit progn in eval().