main.c 11.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/*
 * This file is part of the Micro Python project, http://micropython.org/
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2013, 2014 Damien P. George
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

Damien's avatar
Damien committed
27
#include <stdint.h>
xbe's avatar
xbe committed
28
#include <stdbool.h>
Damien's avatar
Damien committed
29
30
#include <stdio.h>
#include <string.h>
Edd Barrett's avatar
Edd Barrett committed
31
#include <stdlib.h>
32
#include <stdarg.h>
xbe's avatar
xbe committed
33
34
#include <sys/stat.h>
#include <sys/types.h>
35
#include <errno.h>
Damien's avatar
Damien committed
36

37
#include "mpconfig.h"
38
#include "nlr.h"
Damien's avatar
Damien committed
39
#include "misc.h"
40
#include "qstr.h"
Damien's avatar
Damien committed
41
#include "lexer.h"
42
#include "lexerunix.h"
Damien's avatar
Damien committed
43
#include "parse.h"
44
#include "obj.h"
45
#include "parsehelper.h"
46
#include "compile.h"
47
48
#include "runtime0.h"
#include "runtime.h"
49
#include "repl.h"
50
#include "gc.h"
51
#include "genhdr/py-version.h"
Dave Hylands's avatar
Dave Hylands committed
52
#include "input.h"
Damien's avatar
Damien committed
53

54
55
// Command line options, with their defaults
bool compile_only = false;
56
uint emit_opt = MP_EMIT_OPT_NONE;
57
uint mp_verbose_flag;
58

59
#if MICROPY_ENABLE_GC
60
// Heap size of GC heap (if enabled)
61
62
// Make it larger on a 64 bit machine, because pointers are larger.
long heap_size = 128*1024 * (sizeof(machine_uint_t) / 4);
63
#endif
64
65
66
67

// Stack top at the start of program
void *stack_top;

68
void microsocket_init();
69
void time_init();
70
void ffi_init();
71

72
73
// returns standard error codes: 0 for success, 1 for all other errors
STATIC int execute_from_lexer(mp_lexer_t *lex, mp_parse_input_kind_t input_kind, bool is_repl) {
74
    if (lex == NULL) {
75
        return 1;
76
77
78
79
80
81
82
83
84
    }

    if (0) {
        // just tokenise
        while (!mp_lexer_is_kind(lex, MP_TOKEN_END)) {
            mp_token_show(mp_lexer_cur(lex));
            mp_lexer_to_next(lex);
        }
        mp_lexer_free(lex);
85
        return 0;
86
87
    }

88
89
    mp_parse_error_kind_t parse_error_kind;
    mp_parse_node_t pn = mp_parse(lex, input_kind, &parse_error_kind);
90
91
92

    if (pn == MP_PARSE_NODE_NULL) {
        // parse error
93
        mp_parse_show_exception(lex, parse_error_kind);
94
        mp_lexer_free(lex);
95
        return 1;
96
97
    }

98
    qstr source_name = mp_lexer_source_name(lex);
99
100
    mp_lexer_free(lex);

101
102
103
104
105
    /*
    printf("----------------\n");
    mp_parse_node_print(pn, 0);
    printf("----------------\n");
    */
106

107
    mp_obj_t module_fun = mp_compile(pn, source_name, emit_opt, is_repl);
108
109
110

    if (module_fun == mp_const_none) {
        // compile error
111
        return 1;
112
113
    }

114
    if (compile_only) {
115
        return 0;
116
117
    }

118
119
120
    // execute it
    nlr_buf_t nlr;
    if (nlr_push(&nlr) == 0) {
Damien George's avatar
Damien George committed
121
        mp_call_function_0(module_fun);
122
        nlr_pop();
123
        return 0;
124
125
    } else {
        // uncaught exception
126
        mp_obj_print_exception((mp_obj_t)nlr.ret_val);
127
        return 1;
128
129
130
    }
}

131
STATIC char *strjoin(const char *s1, int sep_char, const char *s2) {
Damien's avatar
Damien committed
132
133
    int l1 = strlen(s1);
    int l2 = strlen(s2);
134
    char *s = malloc(l1 + l2 + 2);
Damien's avatar
Damien committed
135
136
137
138
139
140
    memcpy(s, s1, l1);
    if (sep_char != 0) {
        s[l1] = sep_char;
        l1 += 1;
    }
    memcpy(s + l1, s2, l2);
141
    s[l1 + l2] = 0;
Damien's avatar
Damien committed
142
143
144
    return s;
}

145
STATIC void do_repl(void) {
146
    printf("Micro Python " MICROPY_GIT_TAG " on " MICROPY_BUILD_DATE "; UNIX version\n");
147

Damien's avatar
Damien committed
148
    for (;;) {
149
        char *line = prompt(">>> ");
Damien's avatar
Damien committed
150
151
152
153
        if (line == NULL) {
            // EOF
            return;
        }
154
155
156
157
        while (mp_repl_continue_with_input(line)) {
            char *line2 = prompt("... ");
            if (line2 == NULL) {
                break;
Damien's avatar
Damien committed
158
            }
159
160
161
162
            char *line3 = strjoin(line, '\n', line2);
            free(line);
            free(line2);
            line = line3;
Damien's avatar
Damien committed
163
        }
164

165
        mp_lexer_t *lex = mp_lexer_new_from_str_len(MP_QSTR__lt_stdin_gt_, line, strlen(line), false);
166
        execute_from_lexer(lex, MP_PARSE_SINGLE_INPUT, true);
Paul Sokolovsky's avatar
Paul Sokolovsky committed
167
        free(line);
Damien's avatar
Damien committed
168
    }
Damien's avatar
Damien committed
169
170
}

171
STATIC int do_file(const char *file) {
172
    mp_lexer_t *lex = mp_lexer_new_from_file(file);
173
    return execute_from_lexer(lex, MP_PARSE_FILE_INPUT, false);
174
}
Damien's avatar
Damien committed
175

176
STATIC int do_str(const char *str) {
177
    mp_lexer_t *lex = mp_lexer_new_from_str_len(MP_QSTR__lt_stdin_gt_, str, strlen(str), false);
178
    return execute_from_lexer(lex, MP_PARSE_SINGLE_INPUT, false);
Damien's avatar
Damien committed
179
}
Damien's avatar
Damien committed
180

181
int usage(char **argv) {
182
    printf(
183
184
185
"usage: %s [<opts>] [-X <implopt>] [-c <command>] [<filename>]\n"
"Options:\n"
"-v : verbose (trace various operations); can be multiple\n"
186
"\n"
187
"Implementation specific options:\n", argv[0]
188
189
);
    int impl_opts_cnt = 0;
190
    printf(
191
"  compile-only                 -- parse and compile only\n"
192
193
194
"  emit={bytecode,native,viper} -- set the default code emitter\n"
);
    impl_opts_cnt++;
195
196
#if MICROPY_ENABLE_GC
    printf(
197
198
"  heapsize=<n> -- set the heap size for the GC\n"
);
199
200
201
202
203
204
205
    impl_opts_cnt++;
#endif

    if (impl_opts_cnt == 0) {
        printf("  (none)\n");
    }

206
207
208
    return 1;
}

209
210
mp_obj_t mem_info(void) {
    printf("mem: total=%d, current=%d, peak=%d\n", m_get_total_bytes_allocated(), m_get_current_bytes_allocated(), m_get_peak_bytes_allocated());
211
#if MICROPY_ENABLE_GC
212
    gc_dump_info();
213
#endif
214
215
216
217
218
219
220
221
222
223
    return mp_const_none;
}

mp_obj_t qstr_info(void) {
    uint n_pool, n_qstr, n_str_data_bytes, n_total_bytes;
    qstr_pool_info(&n_pool, &n_qstr, &n_str_data_bytes, &n_total_bytes);
    printf("qstr pool: n_pool=%u, n_qstr=%u, n_str_data_bytes=%u, n_total_bytes=%u\n", n_pool, n_qstr, n_str_data_bytes, n_total_bytes);
    return mp_const_none;
}

224
225
226
227
228
229
// Process options which set interpreter init options
void pre_process_options(int argc, char **argv) {
    for (int a = 1; a < argc; a++) {
        if (argv[a][0] == '-') {
            if (strcmp(argv[a], "-X") == 0) {
                if (a + 1 >= argc) {
230
                    exit(usage(argv));
231
                }
232
                if (0) {
233
234
                } else if (strcmp(argv[a + 1], "compile-only") == 0) {
                    compile_only = true;
235
236
237
238
239
240
                } else if (strcmp(argv[a + 1], "emit=bytecode") == 0) {
                    emit_opt = MP_EMIT_OPT_BYTE_CODE;
                } else if (strcmp(argv[a + 1], "emit=native") == 0) {
                    emit_opt = MP_EMIT_OPT_NATIVE_PYTHON;
                } else if (strcmp(argv[a + 1], "emit=viper") == 0) {
                    emit_opt = MP_EMIT_OPT_VIPER;
241
#if MICROPY_ENABLE_GC
242
                } else if (strncmp(argv[a + 1], "heapsize=", sizeof("heapsize=") - 1) == 0) {
243
244
                    heap_size = strtol(argv[a + 1] + sizeof("heapsize=") - 1, NULL, 0);
#endif
245
                } else {
246
                    exit(usage(argv));
247
                }
248
249
250
251
252
253
                a++;
            }
        }
    }
}

Damien's avatar
Damien committed
254
int main(int argc, char **argv) {
255
256
257
    volatile int stack_dummy;
    stack_top = (void*)&stack_dummy;

258
259
    pre_process_options(argc, argv);

260
#if MICROPY_ENABLE_GC
261
262
    char *heap = malloc(heap_size);
    gc_init(heap, heap + heap_size);
263
264
#endif

Damien's avatar
Damien committed
265
    qstr_init();
Damien George's avatar
Damien George committed
266
    mp_init();
Damien's avatar
Damien committed
267

268
269
270
271
272
    char *home = getenv("HOME");
    char *path = getenv("MICROPYPATH");
    if (path == NULL) {
        path = "~/.micropython/lib:/usr/lib/micropython";
    }
273
    uint path_num = 1; // [0] is for current dir (or base dir of the script)
274
275
276
277
278
279
    for (char *p = path; p != NULL; p = strchr(p, ':')) {
        path_num++;
        if (p != NULL) {
            p++;
        }
    }
280
    mp_obj_list_init(mp_sys_path, path_num);
281
    mp_obj_t *path_items;
Damien George's avatar
Damien George committed
282
    mp_obj_list_get(mp_sys_path, &path_num, &path_items);
283
    path_items[0] = MP_OBJ_NEW_QSTR(MP_QSTR_);
284
    char *p = path;
285
    for (int i = 1; i < path_num; i++) {
286
287
288
289
290
291
292
293
294
        char *p1 = strchr(p, ':');
        if (p1 == NULL) {
            p1 = p + strlen(p);
        }
        if (p[0] == '~' && p[1] == '/' && home != NULL) {
            // Expand standalone ~ to $HOME
            CHECKBUF(buf, PATH_MAX);
            CHECKBUF_APPEND(buf, home, strlen(home));
            CHECKBUF_APPEND(buf, p + 1, p1 - p - 1);
295
            path_items[i] = MP_OBJ_NEW_QSTR(qstr_from_strn(buf, CHECKBUF_LEN(buf)));
296
        } else {
297
            path_items[i] = MP_OBJ_NEW_QSTR(qstr_from_strn(p, p1 - p));
298
299
300
301
        }
        p = p1 + 1;
    }

302
    mp_obj_list_init(mp_sys_argv, 0);
Paul Sokolovsky's avatar
Paul Sokolovsky committed
303

Damien George's avatar
Damien George committed
304
305
    mp_store_name(qstr_from_str("mem_info"), mp_make_function_n(0, mem_info));
    mp_store_name(qstr_from_str("qstr_info"), mp_make_function_n(0, qstr_info));
Paul Sokolovsky's avatar
Paul Sokolovsky committed
306

307
308
309
310
311
312
313
    // Here is some example code to create a class and instance of that class.
    // First is the Python, then the C code.
    //
    // class TestClass:
    //     pass
    // test_obj = TestClass()
    // test_obj.attr = 42
314
315
316
317
318
    //
    // mp_obj_t test_class_type, test_class_instance;
    // test_class_type = mp_obj_new_type(QSTR_FROM_STR_STATIC("TestClass"), mp_const_empty_tuple, mp_obj_new_dict(0));
    // mp_store_name(QSTR_FROM_STR_STATIC("test_obj"), test_class_instance = mp_call_function_0(test_class_type));
    // mp_store_attr(test_class_instance, QSTR_FROM_STR_STATIC("attr"), mp_obj_new_int(42));
319

320
321
322
323
324
325
326
    /*
    printf("bytes:\n");
    printf("    total %d\n", m_get_total_bytes_allocated());
    printf("    cur   %d\n", m_get_current_bytes_allocated());
    printf("    peak  %d\n", m_get_peak_bytes_allocated());
    */

327
328
    const int NOTHING_EXECUTED = -2;
    int ret = NOTHING_EXECUTED;
329
330
331
332
    for (int a = 1; a < argc; a++) {
        if (argv[a][0] == '-') {
            if (strcmp(argv[a], "-c") == 0) {
                if (a + 1 >= argc) {
333
                    return usage(argv);
334
                }
335
                ret = do_str(argv[a + 1]);
336
337
338
                a += 1;
            } else if (strcmp(argv[a], "-X") == 0) {
                a += 1;
339
340
            } else if (strcmp(argv[a], "-v") == 0) {
                mp_verbose_flag++;
341
            } else {
342
                return usage(argv);
343
            }
344
345
        } else {
            char *basedir = realpath(argv[a], NULL);
346
347
348
349
            if (basedir == NULL) {
                fprintf(stderr, "%s: can't open file '%s': [Errno %d] ", argv[0], argv[1], errno);
                perror("");
                // CPython exits with 2 in such case
350
351
                ret = 2;
                break;
352
            }
353
354
355
356
357
358

            // Set base dir of the script as first entry in sys.path
            char *p = strrchr(basedir, '/');
            path_items[0] = MP_OBJ_NEW_QSTR(qstr_from_strn(basedir, p - basedir));
            free(basedir);

359
            for (int i = a; i < argc; i++) {
360
                mp_obj_list_append(mp_sys_argv, MP_OBJ_NEW_QSTR(qstr_from_str(argv[i])));
361
            }
362
            ret = do_file(argv[a]);
363
            break;
364
        }
Damien's avatar
Damien committed
365
    }
366

367
    if (ret == NOTHING_EXECUTED) {
368
        do_repl();
369
        ret = 0;
370
371
    }

Damien George's avatar
Damien George committed
372
    mp_deinit();
Damien's avatar
Damien committed
373
374

    //printf("total bytes = %d\n", m_get_total_bytes_allocated());
375
    return ret;
Damien's avatar
Damien committed
376
}
377

378
379
380
381
382
383
384
385
386
STATIC mp_obj_t mp_sys_exit(uint n_args, const mp_obj_t *args) {
    int rc = 0;
    if (n_args > 0) {
        rc = mp_obj_get_int(args[0]);
    }
    exit(rc);
}
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_sys_exit_obj, 0, 1, mp_sys_exit);

387
388
389
390
391
392
393
394
395
396
397
uint mp_import_stat(const char *path) {
    struct stat st;
    if (stat(path, &st) == 0) {
        if (S_ISDIR(st.st_mode)) {
            return MP_IMPORT_STAT_DIR;
        } else if (S_ISREG(st.st_mode)) {
            return MP_IMPORT_STAT_FILE;
        }
    }
    return MP_IMPORT_STAT_NO_EXIST;
}
398
399
400
401
402
403
404
405

int DEBUG_printf(const char *fmt, ...) {
    va_list ap;
    va_start(ap, fmt);
    int ret = vfprintf(stderr, fmt, ap);
    va_end(ap);
    return ret;
}
406
407
408
409
410

void nlr_jump_fail(void *val) {
    printf("FATAL: uncaught NLR %p\n", val);
    exit(1);
}