77#include "lexer.h"
88#include "lexerfatfs.h"
99
10- unichar file_buf_next_char (mp_lexer_file_buf_t * fb ) {
10+ typedef struct _mp_lexer_file_buf_t {
11+ FIL fp ;
12+ char buf [20 ];
13+ uint16_t len ;
14+ uint16_t pos ;
15+ } mp_lexer_file_buf_t ;
16+
17+ static unichar file_buf_next_char (mp_lexer_file_buf_t * fb ) {
1118 if (fb -> pos >= fb -> len ) {
1219 if (fb -> len < sizeof (fb -> buf )) {
1320 return MP_LEXER_CHAR_EOF ;
@@ -24,13 +31,16 @@ unichar file_buf_next_char(mp_lexer_file_buf_t *fb) {
2431 return fb -> buf [fb -> pos ++ ];
2532}
2633
27- void file_buf_close (mp_lexer_file_buf_t * fb ) {
34+ static void file_buf_close (mp_lexer_file_buf_t * fb ) {
2835 f_close (& fb -> fp );
36+ m_del_obj (mp_lexer_file_buf_t , fb );
2937}
3038
31- mp_lexer_t * mp_lexer_new_from_file (const char * filename , mp_lexer_file_buf_t * fb ) {
39+ mp_lexer_t * mp_lexer_new_from_file (const char * filename ) {
40+ mp_lexer_file_buf_t * fb = m_new_obj (mp_lexer_file_buf_t );
3241 FRESULT res = f_open (& fb -> fp , filename , FA_READ );
3342 if (res != FR_OK ) {
43+ m_del_obj (mp_lexer_file_buf_t , fb );
3444 return NULL ;
3545 }
3646 UINT n ;
@@ -40,7 +50,35 @@ mp_lexer_t *mp_lexer_new_from_file(const char *filename, mp_lexer_file_buf_t *fb
4050 return mp_lexer_new (filename , fb , (mp_lexer_stream_next_char_t )file_buf_next_char , (mp_lexer_stream_close_t )file_buf_close );
4151}
4252
53+ /******************************************************************************/
54+ // implementation of import
55+
56+ #include "ff.h"
57+
4358mp_lexer_t * mp_import_open_file (qstr mod_name ) {
44- printf ("import not implemented\n" );
59+ vstr_t * vstr = vstr_new ();
60+ FRESULT res ;
61+
62+ // look for module in src/
63+ vstr_printf (vstr , "0:/src/%s.py" , qstr_str (mod_name ));
64+ res = f_stat (vstr_str (vstr ), NULL );
65+ if (res == FR_OK ) {
66+ // found file
67+ return mp_lexer_new_from_file (vstr_str (vstr )); // TODO does lexer need to copy the string? can we free it here?
68+ }
69+
70+ // look for module in /
71+ vstr_reset (vstr );
72+ vstr_printf (vstr , "0:/%s.py" , qstr_str (mod_name ));
73+ res = f_stat (vstr_str (vstr ), NULL );
74+ if (res == FR_OK ) {
75+ // found file
76+ return mp_lexer_new_from_file (vstr_str (vstr )); // TODO does lexer need to copy the string? can we free it here?
77+ }
78+
79+ // could not find file
80+ vstr_free (vstr );
81+ printf ("import %s: could not find file in src/ or /\n" , qstr_str (mod_name ));
82+
4583 return NULL ;
4684}
0 commit comments