main.c 11.5 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
STATIC void execute_from_lexer(mp_lexer_t *lex, mp_parse_input_kind_t input_kind, bool is_repl) {
73
74
75
76
77
78
79
80
81
82
83
84
85
86
    if (lex == NULL) {
        return;
    }

    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);
        return;
    }

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

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

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

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

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

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

113
114
115
116
    if (compile_only) {
        return;
    }

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

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

142
STATIC void do_repl(void) {
143
    printf("Micro Python " MICROPY_GIT_TAG " on " MICROPY_BUILD_DATE "; UNIX version\n");
144

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

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

168
STATIC void do_file(const char *file) {
169
    mp_lexer_t *lex = mp_lexer_new_from_file(file);
170
171
    execute_from_lexer(lex, MP_PARSE_FILE_INPUT, false);
}
Damien's avatar
Damien committed
172

173
STATIC void do_str(const char *str) {
174
    mp_lexer_t *lex = mp_lexer_new_from_str_len(MP_QSTR__lt_stdin_gt_, str, strlen(str), false);
175
    execute_from_lexer(lex, MP_PARSE_SINGLE_INPUT, false);
Damien's avatar
Damien committed
176
}
Damien's avatar
Damien committed
177

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

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

203
204
205
    return 1;
}

206
207
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());
208
#if MICROPY_ENABLE_GC
209
    gc_dump_info();
210
#endif
211
212
213
214
215
216
217
218
219
220
    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;
}

221
222
223
224
225
226
// 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) {
227
                    exit(usage(argv));
228
                }
229
                if (0) {
230
231
                } else if (strcmp(argv[a + 1], "compile-only") == 0) {
                    compile_only = true;
232
233
234
235
236
237
                } 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;
238
#if MICROPY_ENABLE_GC
239
                } else if (strncmp(argv[a + 1], "heapsize=", sizeof("heapsize=") - 1) == 0) {
240
241
                    heap_size = strtol(argv[a + 1] + sizeof("heapsize=") - 1, NULL, 0);
#endif
242
                } else {
243
                    exit(usage(argv));
244
                }
245
246
247
248
249
250
                a++;
            }
        }
    }
}

Damien's avatar
Damien committed
251
int main(int argc, char **argv) {
252
253
254
    volatile int stack_dummy;
    stack_top = (void*)&stack_dummy;

255
256
    pre_process_options(argc, argv);

257
#if MICROPY_ENABLE_GC
258
259
    char *heap = malloc(heap_size);
    gc_init(heap, heap + heap_size);
260
261
#endif

Damien's avatar
Damien committed
262
    qstr_init();
Damien George's avatar
Damien George committed
263
    mp_init();
Damien's avatar
Damien committed
264

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

299
    mp_obj_list_init(mp_sys_argv, 0);
Paul Sokolovsky's avatar
Paul Sokolovsky committed
300

Damien George's avatar
Damien George committed
301
302
    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
303

304
305
306
307
308
309
310
    // 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
311
312
313
314
315
    //
    // 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));
316

317
318
319
320
321
322
323
    /*
    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());
    */

324
325
326
327
328
    bool executed = false;
    for (int a = 1; a < argc; a++) {
        if (argv[a][0] == '-') {
            if (strcmp(argv[a], "-c") == 0) {
                if (a + 1 >= argc) {
329
                    return usage(argv);
330
                }
331
332
333
334
335
                do_str(argv[a + 1]);
                executed = true;
                a += 1;
            } else if (strcmp(argv[a], "-X") == 0) {
                a += 1;
336
337
            } else if (strcmp(argv[a], "-v") == 0) {
                mp_verbose_flag++;
338
            } else {
339
                return usage(argv);
340
            }
341
342
        } else {
            char *basedir = realpath(argv[a], NULL);
343
344
345
346
347
            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
                exit(2);
348
            }
349
350
351
352
353
354

            // 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);

355
            for (int i = a; i < argc; i++) {
356
                mp_obj_list_append(mp_sys_argv, MP_OBJ_NEW_QSTR(qstr_from_str(argv[i])));
357
358
359
360
            }
            do_file(argv[a]);
            executed = true;
            break;
361
        }
Damien's avatar
Damien committed
362
    }
363

364
365
366
367
    if (!executed) {
        do_repl();
    }

Damien George's avatar
Damien George committed
368
    mp_deinit();
Damien's avatar
Damien committed
369
370
371
372

    //printf("total bytes = %d\n", m_get_total_bytes_allocated());
    return 0;
}
373

374
375
376
377
378
379
380
381
382
383
384
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;
}
385
386
387
388
389
390
391
392

int DEBUG_printf(const char *fmt, ...) {
    va_list ap;
    va_start(ap, fmt);
    int ret = vfprintf(stderr, fmt, ap);
    va_end(ap);
    return ret;
}
393
394
395
396
397

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