Skip to content

Commit 1404d62

Browse files
committed
py/emitglue: Add more feature flags to .mpy persistent bytecode output.
Need to record in .mpy file whether unicode is enabled, and how many bits are in a small int.
1 parent adfe4ff commit 1404d62

1 file changed

Lines changed: 29 additions & 6 deletions

File tree

py/emitglue.c

Lines changed: 29 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,28 @@ mp_obj_t mp_make_closure_from_raw_code(mp_raw_code_t *rc, mp_uint_t n_closed_ove
196196

197197
#if MICROPY_PERSISTENT_CODE
198198

199+
#include "py/smallint.h"
200+
201+
// The feature flags byte encodes the compile-time config options that
202+
// affect the generate bytecode.
203+
#define MPY_FEATURE_FLAGS ( \
204+
((MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE) << 0) \
205+
| ((MICROPY_PY_BUILTINS_STR_UNICODE) << 1) \
206+
)
207+
208+
// The bytecode will depend on the number of bits in a small-int, and
209+
// this function computes that (could make it a fixed constant, but it
210+
// would need to be defined in mpconfigport.h).
211+
STATIC int mp_small_int_bits(void) {
212+
mp_int_t i = MP_SMALL_INT_MAX;
213+
int n = 1;
214+
while (i != 0) {
215+
i >>= 1;
216+
++n;
217+
}
218+
return n;
219+
}
220+
199221
typedef struct _bytecode_prelude_t {
200222
uint n_state;
201223
uint n_exc_stack;
@@ -338,13 +360,13 @@ STATIC mp_raw_code_t *load_raw_code(mp_reader_t *reader) {
338360
}
339361

340362
mp_raw_code_t *mp_raw_code_load(mp_reader_t *reader) {
341-
byte header[3];
342-
read_bytes(reader, header, 3);
363+
byte header[4];
364+
read_bytes(reader, header, sizeof(header));
343365
if (strncmp((char*)header, "M\x00", 2) != 0) {
344366
nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
345367
"invalid .mpy file"));
346368
}
347-
if (header[2] != MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE) {
369+
if (header[2] != MPY_FEATURE_FLAGS || header[3] != mp_small_int_bits()) {
348370
nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
349371
"incompatible .mpy file"));
350372
}
@@ -591,9 +613,10 @@ void mp_raw_code_save(mp_raw_code_t *rc, mp_print_t *print) {
591613
// header contains:
592614
// byte 'M'
593615
// byte version
594-
// byte feature flags (right now just OPT_CACHE_MAP_LOOKUP_IN_BYTECODE)
595-
byte header[3] = {'M', 0, MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE};
596-
mp_print_bytes(print, header, 3);
616+
// byte feature flags
617+
// byte number of bits in a small int
618+
byte header[4] = {'M', 0, MPY_FEATURE_FLAGS, mp_small_int_bits()};
619+
mp_print_bytes(print, header, sizeof(header));
597620

598621
save_raw_code(print, rc);
599622
}

0 commit comments

Comments
 (0)