diff --git a/python/port/port.cpp b/python/port/port.cpp index 063771268..7bce53fee 100644 --- a/python/port/port.cpp +++ b/python/port/port.cpp @@ -36,6 +36,9 @@ void MicroPython::ExecutionEnvironment::runCode(const char * str) { nlr_buf_t nlr; if (nlr_push(&nlr) == 0) { mp_lexer_t *lex = mp_lexer_new_from_str_len(0, str, strlen(str), false); + /* The input type is "single input" because the Python console is supposed + * to be fed lines and not files. */ + // TODO: add a parameter when other input types (file, eval) are required mp_parse_tree_t pt = mp_parse(lex, MP_PARSE_SINGLE_INPUT); mp_obj_t module_fun = mp_compile(&pt, lex->source_name, MP_EMIT_OPT_NONE, true); mp_hal_set_interrupt_char((int)Ion::Keyboard::Key::Back); diff --git a/python/test/mandelbrot.cpp b/python/test/mandelbrot.cpp index c84377530..b8c3b676f 100644 --- a/python/test/mandelbrot.cpp +++ b/python/test/mandelbrot.cpp @@ -1,5 +1,6 @@ #include #include +#include #include @@ -31,9 +32,37 @@ mandelbrot(2) print('ok') )"; +// TODO: this will be obsolete when runCode will take a parameter to choose the input type + +void inlineToBeSingleInput(char * buffer, size_t bufferSize, const char * script) { + static const char * openExec = "exec(\""; + static const char * closeExec = "\")"; + assert(strlen(script) + strlen(openExec) + strlen(closeExec) < bufferSize); + char * bufferChar = buffer; + bufferChar += strlcpy(buffer, openExec, bufferSize); + const char * scriptChar = script; + while (*scriptChar != 0) { + assert(bufferChar - buffer + 2 < bufferSize - 1); + if (*scriptChar == '\n') { + // Turn carriage return in {'\', 'n'} to be processed by exec + *bufferChar++ = '\\'; + *bufferChar++ = 'n'; + } else { + *bufferChar++ = *scriptChar; + } + scriptChar++; + } + bufferChar += strlcpy(bufferChar, closeExec, buffer + bufferSize - bufferChar); + assert(bufferChar - buffer < bufferSize); + *bufferChar = 0; +} + QUIZ_CASE(python_mandelbrot) { + constexpr size_t bufferSize = 500; + char buffer[bufferSize]; + inlineToBeSingleInput(buffer, bufferSize, s_mandelbrotScript); MicroPython::init(s_pythonHeap, s_pythonHeap + k_pythonHeapSize); TestExecutionEnvironment env; - env.runCode(s_mandelbrotScript); + env.runCode(buffer); MicroPython::deinit(); }