blob: 1dc5e5760ebdd3292ea107f87d8391efbd5807b4 [file] [log] [blame]
Damiend99b0522013-12-21 18:17:45 +00001#include <stdlib.h>
2#include <stdint.h>
3
4#include "nlr.h"
5#include "misc.h"
6#include "mpconfig.h"
Damien George55baff42014-01-21 21:40:13 +00007#include "qstr.h"
Damiend99b0522013-12-21 18:17:45 +00008#include "obj.h"
Damien George1e708fe2014-01-23 18:27:51 +00009#include "runtime0.h"
Damien George71c51812014-01-04 20:21:15 +000010#include "runtime.h"
Damiend99b0522013-12-21 18:17:45 +000011
12typedef struct _mp_obj_bool_t {
13 mp_obj_base_t base;
14 bool value;
15} mp_obj_bool_t;
16
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +020017STATIC void bool_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t self_in, mp_print_kind_t kind) {
Damiend99b0522013-12-21 18:17:45 +000018 mp_obj_bool_t *self = self_in;
19 if (self->value) {
20 print(env, "True");
21 } else {
22 print(env, "False");
23 }
24}
25
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +020026STATIC mp_obj_t bool_make_new(mp_obj_t type_in, uint n_args, uint n_kw, const mp_obj_t *args) {
Damien George20006db2014-01-18 14:10:48 +000027 // TODO check n_kw == 0
28
Damien George71c51812014-01-04 20:21:15 +000029 switch (n_args) {
30 case 0: return mp_const_false;
31 case 1: if (rt_is_true(args[0])) { return mp_const_true; } else { return mp_const_false; }
Damien Georgec5966122014-02-15 16:10:44 +000032 default: nlr_jump(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "bool takes at most 1 argument, %d given", n_args));
Damien George71c51812014-01-04 20:21:15 +000033 }
34}
35
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +020036STATIC mp_obj_t bool_unary_op(int op, mp_obj_t o_in) {
Damien George1e708fe2014-01-23 18:27:51 +000037 machine_int_t value = ((mp_obj_bool_t*)o_in)->value;
38 switch (op) {
Paul Sokolovskyc1d9bbc2014-01-30 04:37:19 +020039 case RT_UNARY_OP_BOOL: return o_in;
Damien George1e708fe2014-01-23 18:27:51 +000040 case RT_UNARY_OP_POSITIVE: return MP_OBJ_NEW_SMALL_INT(value);
41 case RT_UNARY_OP_NEGATIVE: return MP_OBJ_NEW_SMALL_INT(-value);
42 case RT_UNARY_OP_INVERT:
43 default: // no other cases
44 return MP_OBJ_NEW_SMALL_INT(~value);
45 }
46}
47
Damiend99b0522013-12-21 18:17:45 +000048const mp_obj_type_t bool_type = {
Damien Georgec5966122014-02-15 16:10:44 +000049 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +000050 .name = MP_QSTR_bool,
Damien George97209d32014-01-07 15:58:30 +000051 .print = bool_print,
52 .make_new = bool_make_new,
Damien George1e708fe2014-01-23 18:27:51 +000053 .unary_op = bool_unary_op,
Damiend99b0522013-12-21 18:17:45 +000054};
55
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +020056STATIC const mp_obj_bool_t false_obj = {{&bool_type}, false};
57STATIC const mp_obj_bool_t true_obj = {{&bool_type}, true};
Damiend99b0522013-12-21 18:17:45 +000058
59const mp_obj_t mp_const_false = (mp_obj_t)&false_obj;
60const mp_obj_t mp_const_true = (mp_obj_t)&true_obj;