From dd4135aeaf0669b8c61daf2a1f810eec12bf1336 Mon Sep 17 00:00:00 2001 From: Damien George Date: Wed, 28 Sep 2016 10:55:23 +1000 Subject: [PATCH] py/objset: Use mp_check_self() to check args of set/frozenset methods. Following how other objects work, set/frozenset methods should use the mp_check_self() macro to check the type of the self argument, because in most cases this check can be a null operation. Saves about 100-180 bytes of code for builds with set and frozenset enabled. --- py/objset.c | 28 +++++++++++----------------- 1 file changed, 11 insertions(+), 17 deletions(-) diff --git a/py/objset.c b/py/objset.c index fb89c07f3d..0425499008 100644 --- a/py/objset.c +++ b/py/objset.c @@ -57,27 +57,21 @@ STATIC bool is_set_or_frozenset(mp_obj_t o) { ; } -#if MICROPY_PY_BUILTINS_FROZENSET -STATIC void check_set_or_frozenset(mp_obj_t o) { - if (!is_set_or_frozenset(o)) { - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "'set' object required")); - } -} -#else -#define check_set_or_frozenset(o) check_set(o) -#endif +// This macro is shorthand for mp_check_self to verify the argument is a +// set or frozenset for methods that operate on both of these types. +#define check_set_or_frozenset(o) mp_check_self(is_set_or_frozenset(o)) +// This function is used to verify the argument for methods that modify +// the set object, and raises an exception if the arg is a frozenset. STATIC void check_set(mp_obj_t o) { - if (!MP_OBJ_IS_TYPE(o, &mp_type_set)) { - // Emulate CPython behavior + #if MICROPY_PY_BUILTINS_FROZENSET + if (MP_OBJ_IS_TYPE(o, &mp_type_frozenset)) { + // Mutable method called on frozenset; emulate CPython behavior, eg: // AttributeError: 'frozenset' object has no attribute 'add' - #if MICROPY_PY_BUILTINS_FROZENSET - if (MP_OBJ_IS_TYPE(o, &mp_type_frozenset)) { - nlr_raise(mp_obj_new_exception_msg(&mp_type_AttributeError, "'frozenset' has no such attribute")); - } - #endif - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "'set' object required")); + nlr_raise(mp_obj_new_exception_msg(&mp_type_AttributeError, "'frozenset' has no such attribute")); } + #endif + mp_check_self(MP_OBJ_IS_TYPE(o, &mp_type_set)); } STATIC void set_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {