Generally, in order to save memory and ensure that there are enough operators, the bytecode is declared as unsigned char type. Therefore, a virtual machine can have only 255 operation commands. However, in order to improve the running efficiency, some interpretation languages need more operation commands to implement built-in functions. Once the number exceeds 255, unsigned char is obviously not enough.
As a virtual machine that explains the LPC language, mudos has the same problem. The solution is as follows:
1. All operator and efunctions are implemented as unsigned char.
2. Define the indexes of all operator and built-in functions in Opcodes. h. Define three identification macros: Base, onearg_max, num_opcodes, from 0 ~ (Base-1) is the operator index, from base ~ (Onearg_max-1) is the index of a single parameter efunctions, from onearg_max ~ Num_opcodes is an index with multiple parameters or without efunctions.
3. in the operator's first several declarations, there are the following macros: f_efun0 -- efunction is 0 parameter, f_efun1 -- efunction is 1 parameter, f_efun2 -- efunction is 2 parameter, f_efun3 -- efunction is 3 parameter, f_efunv -- the number of efunction parameters is not fixed, similar to the C function printf. You can find these efunction lists in efun_defs.c. This table describes the function name, bytecode value, number of parameters, return value type, parameter type, index value, and default value of efunction.
4. Handle operator and efunctions according to the following rules when generating bytecode in the compilation phase. For details, see the I _generate_node function:
L if the index value of F _ * is smaller than onearg_max, the index value of F _ * is used as the bytecode and stored in the bytecode sequence.
L if the index value of F _ * is greater than onearg_max, and the number of parameters of this function isNFirst, store the f_efunNThen, the index value of F _ * Minus the value of onearg_max is saved to form a dual-byte bytecode.
L if the index value of F _ * is greater than onearg_max and the number of parameters of this function is not fixed, first the index value of f_efunv is saved, and then the actual number of parameters is saved, the index value stored in F _ * Minus the value of onearg_max constitutes a three-byte bytecode.
5. During the interpretation phase, the evaluation process is completed according to the above bytecode order.