koka-lang / libmprompt

Robust multi-prompt delimited control and effect handlers in C/C++
MIT License
106 stars 11 forks source link

Tail resumptions can't be discarded #10

Open teofr opened 1 year ago

teofr commented 1 year ago

The semantics of MPE_OP_TAIL_NOOP and MPE_OP_TAIL_NOOP don't follow their description, nor the one of the similar tags on libhandler.

MPE_OP_TAIL_NOOP,   ///< resume at most once without performing operations; and if resumed, it is the last action performed by the operation function.
MPE_OP_TAIL,        ///< resume at most once; and if resumed, it is the last action performed by the operation function.

The problem is that the implementation seems to assume that the resumption is always resumed, even when the handler discards it and just returns. libhandler has a marker to indicate whether the resumption was resumed or not. A similar approach could be taken.

I may be missing a correct way to discard a resumption instead of just discarding it.

A small test:

MPE_DEFINE_EFFECT1(sphinx, answer)
MPE_DEFINE_VOIDOP1(sphinx, answer, mpe_string_t)

void* brian(void* arg){
    UNUSED(arg);
    // Arrive at Thebes
    sphinx_answer("Scooters");
    // Die
    mpt_assert(false, "Brian should have been eaten by the sphinx");
    return mpe_voidp_int(1);
}

/*-----------------------------------------------------------------
  Sphinx handler
-----------------------------------------------------------------*/

static void* _sphinx_answer(mpe_resume_t* r, void* local, void* arg){
    if (strcmp(mpe_mpe_string_t_voidp(arg), "Person") == 0) {
        return mpe_resume_tail(r, local, NULL);
    } else {
        // I couldn't find a way to release it, this one is not intended for MPE_RESUMPTION_INPLACE
        // mpe_resume_release(r);
        return mpe_voidp_int(0);
    }
}

static const mpe_handlerdef_t sphinx_hdef = { MPE_EFFECT(sphinx), NULL, {
    { MPE_OP_TAIL, MPE_OPTAG(sphinx, answer), &_sphinx_answer },
    { MPE_OP_NULL, mpe_op_null, NULL}
}};

static void* sphinx_handle(mpe_actionfun_t action) {
    return mpe_handle(&sphinx_hdef, NULL, action, NULL);
}
teofr commented 1 year ago

A complete test and a possible solution can be found in https://github.com/koka-lang/libmprompt/pull/11