gbdev/rgbds

[Feature request] EXEC/EVAL a string

Closed this issue · 1 comments

It's common to do metaprogramming in macros by building a string, assigning it a name, and interpolating that name. This is a decent solution, with a few drawbacks:

  • Uses an extra line of code (REDEF s EQUS "..." and then {s})
  • Pollutes the name space, unless you use a third line to PURGE the name
  • Can't be done recursively without extra complexity (REDEF s\@ EQUS "..."?)

For the common case of building up a string and interpolating it as a whole line, we could introduce an EXEC or EVAL directive. This would take one string parameter (or maybe multiple ones and implicitly concatenate them, for convenience), and then expand them into the code just like interpolations and macro arguments do.


Some before-and-after examples:

Nested macros:

MACRO outer
    DEF definition EQUS """
        MACRO inner
            println (\1) - (\\1)
        \nENDM"""
    {definition}
    PURGE definition
ENDM
; ------
MACRO outer
    EXEC """
        MACRO inner
            println (\1) - (\\1)
        \nENDM"""
ENDM

"X macros" but by replacing a "?" character (from Polished Crystal):

MACRO with_each
	for _with_each_i, 1, _NARG
		redef _with_each_str EQUS STRRPL(\<_NARG>, "?", "\<_with_each_i>")
		{_with_each_str}
	endr
ENDM
; ------
MACRO with_each
	for _with_each_i, 1, _NARG
		exec STRRPL(\<_NARG>, "?", "\<_with_each_i>")
	endr
ENDM

I'm rejecting my own feature proposal here, since you often need a named string anyway to build up the code in multiple/conditional steps.