lexerunix.c 1.41 KB
Newer Older
1
2
3
4
5
6
#include <stdint.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>

#include "misc.h"
7
#include "mpconfig.h"
8
#include "lexer.h"
9
#include "lexerunix.h"
10

11
12
#if MICROPY_ENABLE_LEXER_UNIX

13
mp_lexer_t *mp_lexer_new_from_file(const char *filename) {
14
15
16
17
18
19
20
21
    int fd = open(filename, O_RDONLY);
    if (fd < 0) {
        printf("cannot open file %s\n", filename);
        return NULL;
    }
    uint size = lseek(fd, 0, SEEK_END);
    lseek(fd, 0, SEEK_SET);
    char *data = m_new(char, size);
22
    int read_size = read(fd, data, size);
23
    close(fd);
24
25
    if (read_size != size) {
        printf("error reading file %s\n", filename);
26
        m_del(char, data, size);
27
28
        return NULL;
    }
29

30
    return mp_lexer_new_from_str_len(filename, data, size, size);
31
}
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51

/******************************************************************************/
/* unix implementation of import                                              */

// TODO properly!

static const char *import_base_dir = NULL;

void mp_import_set_directory(const char *dir) {
    import_base_dir = dir;
}

mp_lexer_t *mp_import_open_file(qstr mod_name) {
    vstr_t *vstr = vstr_new();
    if (import_base_dir != NULL) {
        vstr_printf(vstr, "%s/", import_base_dir);
    }
    vstr_printf(vstr, "%s.py", qstr_str(mod_name));
    return mp_lexer_new_from_file(vstr_str(vstr)); // TODO does lexer need to copy the string? can we free it here?
}
52
53

#endif // MICROPY_ENABLE_LEXER_UNIX