Copying snippet from Brainstorming OP_EVAL - #10 by bitjson :
OP_EVAL vs. word definition
Yes! I definitely need to include a section comparing the OP_EVAL CHIP with “proper” Forth-like word definition (also called
OP_DEFINE
/OP_UNDEFINE
/OP_INVOKE
in old Libauth branches).As you pointed out, a full “word definition” upgrade proposal is quite a bit more involved: how and where we track definitions, any necessary limits for those new data structures, whether or not a word can be undefined (we only have
OP_0
toOP_16
+ maybeOP_1NEGATE
!), what makes a valid identifier (only numbers? any single byte? multi-byte?), should we include Forth OP_FETCH/OP_STORE corollaries for data (some discussion of OP_EVAL vs. a TX-wide “data annex” here), and probably many more details.Fortunately, we have a great argument for avoiding this bikeshed altogether: we can easily prove that OP_EVAL is the optimal construction for single-use evaluations (as you mentioned). Even if a “word definition” upgrade were hammered out and activated in the future, OP_EVAL would still be the most efficient option for many constructions. (This coincidentally was the same argument that made P2SH32 a strong proposal vs. OP_EVAL – even with OP_EVAL, P2SH32 remains the more byte-efficient construction for those use cases.)
As BCH VM bytecode is a concatenative language, a perfectly-optimizing compiler is quite likely to produce single-use evaluations from common pieces of different words/functions, even if the contract author didn’t deliberately design something requiring OP_EVAL (e.g. MAST-like constructions).
So:
- OP_EVAL is feature-equivalent to word definition (each enables all the same use cases)
- OP_EVAL typically requires 1 extra byte per invocation, but sometimes saves 1 byte vs. OP_INVOKE.
- OP_EVAL is 3 bytes (
<index> OP_PICK OP_EVAL
) for many calls, but some will be optimized to only 1 byte (justOP_EVAL
)- OP_INVOKE is always 2 bytes (
<identifer> OP_INVOKE
).- OP_EVAL always saves 1 byte per definition by avoiding the
OP_DEFINE
.- OP_EVAL remains optimal for some uses even if a future upgrade added word definition (as a 1-byte optimization for some function calls).