Skip to content
Snippets Groups Projects
Select Git revision
  • 6d3c5e4301df363055dc256e6692c610e4d0b918
  • wip-bootstrap default
  • dualcore
  • ch3/leds
  • ch3/time
  • master
6 results

builtin.c

Blame
  • builtin.c 14.14 KiB
    #include <stdio.h>
    #include <assert.h>
    
    #include "nlr.h"
    #include "misc.h"
    #include "mpconfig.h"
    #include "qstr.h"
    #include "obj.h"
    #include "objstr.h"
    #include "runtime0.h"
    #include "runtime.h"
    #include "builtin.h"
    
    #if MICROPY_ENABLE_FLOAT
    #include <math.h>
    #endif
    
    // args[0] is function from class body
    // args[1] is class name
    // args[2:] are base objects
    STATIC mp_obj_t mp_builtin___build_class__(uint n_args, const mp_obj_t *args) {
        assert(2 <= n_args);
    
        // set the new classes __locals__ object
        mp_obj_dict_t *old_locals = mp_locals_get();
        mp_obj_t class_locals = mp_obj_new_dict(0);
        mp_locals_set(class_locals);
    
        // call the class code
        mp_obj_t cell = mp_call_function_0(args[0]);
    
        // restore old __locals__ object
        mp_locals_set(old_locals);
    
        // get the class type (meta object) from the base objects
        mp_obj_t meta;
        if (n_args == 2) {
            // no explicit bases, so use 'type'
            meta = (mp_obj_t)&mp_type_type;
        } else {
            // use type of first base object
            meta = mp_obj_get_type(args[2]);
        }
    
        // TODO do proper metaclass resolution for multiple base objects
    
        // create the new class using a call to the meta object
        mp_obj_t meta_args[3];
        meta_args[0] = args[1]; // class name
        meta_args[1] = mp_obj_new_tuple(n_args - 2, args + 2); // tuple of bases
        meta_args[2] = class_locals; // dict of members
        mp_obj_t new_class = mp_call_function_n_kw(meta, 3, 0, meta_args);
    
        // store into cell if neede
        if (cell != mp_const_none) {
            mp_obj_cell_set(cell, new_class);
        }
    
        return new_class;
    }
    
    MP_DEFINE_CONST_FUN_OBJ_VAR(mp_builtin___build_class___obj, 2, mp_builtin___build_class__);
    
    STATIC mp_obj_t mp_builtin___repl_print__(mp_obj_t o) {
        if (o != mp_const_none) {
            mp_obj_print(o, PRINT_REPR);
            printf("\n");
        }
        return mp_const_none;
    }