Bytecode uint varlen encoding: support arbitrary values.

This commit is contained in:
Paul Sokolovsky 2014-02-18 21:21:22 +02:00
parent 46239413d0
commit 0f96ec8268
2 changed files with 24 additions and 14 deletions

View File

@ -108,19 +108,19 @@ STATIC void emit_write_byte_code_byte_byte(emit_t* emit, byte b1, uint b2) {
} }
STATIC void emit_write_byte_code_uint(emit_t* emit, uint num) { STATIC void emit_write_byte_code_uint(emit_t* emit, uint num) {
if (num <= 127) { // fits in 0x7f // We store each 7 bits in a separate byte, and that's how many bytes needed
// fit argument in single byte byte buf[(BYTES_PER_WORD * 8 + 7) / 7];
byte* c = emit_get_cur_to_write_byte_code(emit, 1); byte *p = buf + sizeof(buf);
c[0] = num; // We encode in little-ending order, but store in big-endian, to help decoding
} else if (num <= 16383) { // fits in 0x3fff do {
// fit argument in two bytes *--p = num & 0x7f;
byte* c = emit_get_cur_to_write_byte_code(emit, 2); num >>= 7;
c[0] = (num >> 8) | 0x80; } while (num != 0);
c[1] = num; byte* c = emit_get_cur_to_write_byte_code(emit, buf + sizeof(buf) - p);
} else { while (p != buf + sizeof(buf) - 1) {
// larger numbers not implemented/supported *c++ = *p++ | 0x80;
assert(0);
} }
*c = *p;
} }
// integers (for small ints) are stored as 24 bits, in excess // integers (for small ints) are stored as 24 bits, in excess

14
py/vm.c
View File

@ -38,10 +38,20 @@ typedef enum {
UNWIND_JUMP, UNWIND_JUMP,
} mp_unwind_reason_t; } mp_unwind_reason_t;
#define DECODE_UINT do { unum = *ip++; if (unum > 127) { unum = ((unum & 0x3f) << 8) | (*ip++); } } while (0) #define DECODE_UINT { \
unum = 0; \
do { \
unum = (unum << 7) + (*ip & 0x7f); \
} while ((*ip++ & 0x80) != 0); \
}
#define DECODE_ULABEL do { unum = (ip[0] | (ip[1] << 8)); ip += 2; } while (0) #define DECODE_ULABEL do { unum = (ip[0] | (ip[1] << 8)); ip += 2; } while (0)
#define DECODE_SLABEL do { unum = (ip[0] | (ip[1] << 8)) - 0x8000; ip += 2; } while (0) #define DECODE_SLABEL do { unum = (ip[0] | (ip[1] << 8)) - 0x8000; ip += 2; } while (0)
#define DECODE_QSTR do { qst = *ip++; if (qst > 127) { qst = ((qst & 0x3f) << 8) | (*ip++); } } while (0) #define DECODE_QSTR { \
qst = 0; \
do { \
qst = (qst << 7) + (*ip & 0x7f); \
} while ((*ip++ & 0x80) != 0); \
}
#define PUSH(val) *++sp = (val) #define PUSH(val) *++sp = (val)
#define POP() (*sp--) #define POP() (*sp--)
#define TOP() (*sp) #define TOP() (*sp)