ValueError: Invalid CFG, inconsistent stackdepth
I’m writing my own match pattern that calls a python function that returns true and false for match and fail
given
def Logic(a):
return a
then
case $Logic(1):
matches as expected but
case $Logic(1) | $Logic(0):
gives ValueError: Invalid CFG, inconsistent stackdepth and does not run any code.
The error is related to the runtime stack, generated in flowgraph.c
The DOLLAR is simply used to make the grammar work.
The code that does this has been inserted into codegen.c. and the tokens, grammar, ast definitions etc have been changed to make it work, using Python 3.14.8 and Ubunto and WSL
codegen_pattern_func(compiler *c, pattern_ty p, pattern_context *pc)
{
assert(p->kind == MatchFunc_kind);
//~ ADDOP_I(c, LOC(p), LOAD_SMALL_INT, 1); // line 4
VISIT(c, expr, p->v.MatchFunc.e); // line 5
ADDOP(c, LOC(p), TO_BOOL);
RETURN_IF_ERROR(jump_to_fail_pop(c, LOC(p), pc, POP_JUMP_IF_FALSE));
return SUCCESS;
}
This compiles without errors or warnings. If I uncomment line 4 and comment line 5 (i.e. not call the function) then both case statements match.
I believe it is something to do with the runtime stack. Does a function returning 1 object leave it at the top of stack after clearing all the call information?
I don’t expect a solution but any ideas where I might look would be gratefully accepted.
I’m doing this as a learning/recreational project and have successfully added ‘equals’ as an alias to ‘==’, a approx b or a ~= b to allow approximately equal for floating/complex numbers/strings. The next goal is a simple ‘and’ pattern hence the interest in ‘or’ patterns. I’d like to be able to write
case $Logic(x > 2.) & $Logic( x < -2):
or
case $GT(2) & $LT(-2.):
where the comparison is with the match value. If I can solve the ValueError then I have a simple solution to passing the match value.
I don’t propose these features for any future version of python.