py/modsys: Add optional attribute delegation.

To be enabled when needed by specific sys attributes.

Signed-off-by: Damien George <damien@micropython.org>
This commit is contained in:
Damien George 2021-07-27 00:39:04 +10:00
parent 3356b5ef8d
commit bc181550a4
3 changed files with 33 additions and 0 deletions

View File

@ -27,6 +27,7 @@
#include "py/builtin.h"
#include "py/objlist.h"
#include "py/objmodule.h"
#include "py/objtuple.h"
#include "py/objstr.h"
#include "py/objint.h"
@ -182,6 +183,18 @@ STATIC mp_obj_t mp_sys_settrace(mp_obj_t obj) {
MP_DEFINE_CONST_FUN_OBJ_1(mp_sys_settrace_obj, mp_sys_settrace);
#endif // MICROPY_PY_SYS_SETTRACE
#if MICROPY_PY_SYS_ATTR_DELEGATION
STATIC const uint16_t sys_mutable_keys[] = {
MP_QSTRnull,
};
STATIC void mp_module_sys_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) {
MP_STATIC_ASSERT(MP_ARRAY_SIZE(sys_mutable_keys) == MP_SYS_MUTABLE_NUM + 1);
MP_STATIC_ASSERT(MP_ARRAY_SIZE(MP_STATE_VM(sys_mutable)) == MP_SYS_MUTABLE_NUM);
mp_module_generic_attr(attr, dest, sys_mutable_keys, MP_STATE_VM(sys_mutable));
}
#endif
STATIC const mp_rom_map_elem_t mp_module_sys_globals_table[] = {
{ MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_sys) },
@ -244,6 +257,11 @@ STATIC const mp_rom_map_elem_t mp_module_sys_globals_table[] = {
#if MICROPY_PY_SYS_ATEXIT
{ MP_ROM_QSTR(MP_QSTR_atexit), MP_ROM_PTR(&mp_sys_atexit_obj) },
#endif
#if MICROPY_PY_SYS_ATTR_DELEGATION
// Delegation of attr lookup.
MP_MODULE_ATTR_DELEGATION_ENTRY(&mp_module_sys_attr),
#endif
};
STATIC MP_DEFINE_CONST_DICT(mp_module_sys_globals, mp_module_sys_globals_table);

View File

@ -1377,6 +1377,12 @@ typedef double mp_float_t;
#define MICROPY_PY_SYS_STDIO_BUFFER (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_EXTRA_FEATURES)
#endif
// Whether the sys module supports attribute delegation
// This is enabled automatically when needed by other features
#ifndef MICROPY_PY_SYS_ATTR_DELEGATION
#define MICROPY_PY_SYS_ATTR_DELEGATION (0)
#endif
// Whether to provide "uerrno" module
#ifndef MICROPY_PY_UERRNO
#define MICROPY_PY_UERRNO (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_EXTRA_FEATURES)

View File

@ -40,6 +40,10 @@
// memory system, runtime and virtual machine. The state is a global
// variable, but in the future it is hoped that the state can become local.
enum {
MP_SYS_MUTABLE_NUM,
};
// This structure contains dynamic configuration for the compiler.
#if MICROPY_DYNAMIC_COMPILER
typedef struct mp_dynamic_compiler_t {
@ -158,6 +162,11 @@ typedef struct _mp_state_vm_t {
// must be initialised after the call to mp_init.
mp_obj_list_t mp_sys_path_obj;
mp_obj_list_t mp_sys_argv_obj;
#if MICROPY_PY_SYS_ATTR_DELEGATION
// Contains mutable sys attributes.
mp_obj_t sys_mutable[MP_SYS_MUTABLE_NUM];
#endif
#endif
// dictionary for overridden builtins