cppo icon indicating copy to clipboard operation
cppo copied to clipboard

Add support for local scopes (`#scope ... #endscope`)

Open fpottier opened this issue 1 year ago • 0 comments

This PR adds support for #scope ... #endscope. This construct limits the effect of macro definitions and undefinitions. In other words, #endscope restores the macro environment that existed when #scope was entered. It is analogous to \bgroup and \egroup in LaTeX.

I find this feature to be strongly desirable, as it often removes the need to use #undef, which is very inelegant and painful.

This feature can be used to obtain a form of #include-with-parameters, as in this example:

#scope
#define FOO 42
#include "bar.ml"
#endscope

I find this very useful in practice, and I hope to use it in the next version of baby.

The changes to the source code are minimal; beyond lexer and parser support, the main change is one more case in the function expand_node, as follows:

    | `Scope body ->
        (* A [body] is just a [node]. We expand this node, and drop
           the resulting environment; instead, we return the current
           environment. *)
        let env = expand_node ~top g env0 body in
        ignore env;
        env0

I have added a new test (test/scope.{cppo,ref}) and updated README.md and Changes.md.

fpottier avatar Oct 28 '24 09:10 fpottier