builtinevex.c 1.71 KB
Newer Older
Damien George's avatar
Damien George committed
1
2
3
4
5
6
7
8
9
10
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <assert.h>

#include "nlr.h"
#include "misc.h"
#include "mpconfig.h"
11
#include "qstr.h"
Damien George's avatar
Damien George committed
12
13
14
15
16
17
18
19
20
21
#include "lexer.h"
#include "lexerunix.h"
#include "parse.h"
#include "obj.h"
#include "compile.h"
#include "runtime0.h"
#include "runtime.h"
#include "map.h"
#include "builtin.h"

Damien George's avatar
Damien George committed
22
static mp_obj_t parse_compile_execute(mp_obj_t o_in, mp_parse_input_kind_t parse_input_kind) {
23
    uint str_len;
24
    const char *str = mp_obj_str_get_data(o_in, &str_len);
Damien George's avatar
Damien George committed
25
26

    // create the lexer
27
    mp_lexer_t *lex = mp_lexer_new_from_str_len(MP_QSTR__lt_string_gt_, str, str_len, 0);
28
    qstr source_name = mp_lexer_source_name(lex);
Damien George's avatar
Damien George committed
29
30
31
32

    // parse the string
    qstr parse_exc_id;
    const char *parse_exc_msg;
Damien George's avatar
Damien George committed
33
    mp_parse_node_t pn = mp_parse(lex, parse_input_kind, &parse_exc_id, &parse_exc_msg);
Damien George's avatar
Damien George committed
34
35
36
37
38
39
40
41
    mp_lexer_free(lex);

    if (pn == MP_PARSE_NODE_NULL) {
        // parse error; raise exception
        nlr_jump(mp_obj_new_exception_msg(parse_exc_id, parse_exc_msg));
    }

    // compile the string
42
    mp_obj_t module_fun = mp_compile(pn, source_name, false);
43
    mp_parse_node_free(pn);
Damien George's avatar
Damien George committed
44
45
46
47
48
49
50
51
52
53

    if (module_fun == mp_const_none) {
        // TODO handle compile error correctly
        return mp_const_none;
    }

    // complied successfully, execute it
    return rt_call_function_0(module_fun);
}

Damien George's avatar
Damien George committed
54
55
56
57
static mp_obj_t mp_builtin_eval(mp_obj_t o_in) {
    return parse_compile_execute(o_in, MP_PARSE_EVAL_INPUT);
}

Damien George's avatar
Damien George committed
58
MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_eval_obj, mp_builtin_eval);
Damien George's avatar
Damien George committed
59
60
61
62
63
64

static mp_obj_t mp_builtin_exec(mp_obj_t o_in) {
    return parse_compile_execute(o_in, MP_PARSE_FILE_INPUT);
}

MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_exec_obj, mp_builtin_exec);