MicroPython 是一种适用于微控制器和其他受限环境的 Python 编程语言的实现。它旨在提供与 Python 3 语言的紧密兼容,同时考虑到内存和计算资源的限制。MicroPython 库是这门语言的核心组成部分,提供了一系列的模块和函数,使得开发者能够在硬件上执行各种任务。
下面将通过系列文章,逐一解读microPython,以便让读者了解掌握microPython的整个核心逻辑.,以便读者可以透过这个Python的最小内核,掌握Python解析器的核心实现逻辑,学习世界上最优秀的源码设计之一.
microPython Python最小内核源码解析
NI-motion运动控制c语言示例代码解析
python编程示例系列 python编程示例系列二
python的Web神器Streamlit
这段代码主要是关于MicroPython REPL(Read-Eval-Print Loop)的自动补全功能的实现。它包括了检查输入是否需要继续、查找和打印补全建议、以及实现自动补全的逻辑。代码中的注释详细解释了每个函数和代码块的作用,有助于理解整个自动补全功能的工作原理。
#include <string.h>
#include "py/obj.h"
#include "py/objmodule.h"
#include "py/runtime.h"
#include "py/builtin.h"
#include "py/repl.h"
#if MICROPY_HELPER_REPL
#if MICROPY_PY_SYS_PS1_PS2
/**
* 获取特定条目对应的提示符字符串
* @param entry 提示符数组的索引
* @return 返回对应的字符串,如果不存在则返回空字符串
*/
const char *mp_repl_get_psx(unsigned int entry) {
if (mp_obj_is_str(MP_STATE_VM(sys_mutable)[entry])) {
return mp_obj_str_get_str(MP_STATE_VM(sys_mutable)[entry]);
} else {
return "";
}
}
#endif
/**
* 检查字符串是否以指定单词开头
* @param str 待检查的字符串
* @param head 开头单词
* @return 如果以指定单词开头则返回true,否则返回false
*/
static bool str_startswith_word(const char *str, const char *head) {
size_t i;
for (i = 0; str[i] && head[i]; i++) {
if (str[i] != head[i]) {
return false;
}
}
return head[i] == '\0' && (str[i] == '\0' || !unichar_isident(str[i]));
}
/**
* 判断输入的代码是否需要继续输入以完成语句
* @param input 用户输入的代码
* @return 如果需要继续输入则返回true,否则返回false
*/
bool mp_repl_continue_with_input(const char *input) {
// 检查输入是否为空
if (input[0] == '\0') {
return false;
}
// 检查输入是否以特定关键字开头
bool starts_with_compound_keyword =
input[0] == '@'
|| str_startswith_word(input, "if")
|| str_startswith_word(input, "while")
|| str_startswith_word(input, "for")
|| str_startswith_word(input, "try")
|| str_startswith_word(input, "with")
|| str_startswith_word(input, "def")
|| str_startswith_word(input, "class")
#if MICROPY_PY_ASYNC_AWAIT
|| str_startswith_word(input, "async")
#endif
;
// 检查输入中是否有不匹配的括号、引号或转义引号
#define Q_NONE (0)
#define Q_1_SINGLE (1)
#define Q_1_DOUBLE (2)
#define Q_3_SINGLE (3)
#define Q_3_DOUBLE (4)
int n_paren = 0;
int n_brack = 0;
int n_brace = 0;
int in_quote = Q_NONE;
const char *i;
for (i = input; *i; i++) {
if (*i == '\'') {
if ((in_quote == Q_NONE || in_quote == Q_3_SINGLE) && i[1] == '\'' && i[2] == '\'') {
i += 2;
in_quote = Q_3_SINGLE - in_quote;
} else if (in_quote == Q_NONE || in_quote == Q_1_SINGLE) {
in_quote = Q_1_SINGLE - in_quote;
}
} else if (*i == '"') {
if ((in_quote == Q_NONE || in_quote == Q_3_DOUBLE) && i[1] == '"' && i[2] == '"') {
i += 2;
in_quote = Q_3_DOUBLE - in_quote;
} else if (in_quote == Q_NONE || in_quote == Q_1_DOUBLE) {
in_quote = Q_1_DOUBLE - in_quote;
}
} else