diff --git a/dl/script/dl_script.cpp b/dl/script/dl_script.cpp index d25b5727..ff8b0132 100644 --- a/dl/script/dl_script.cpp +++ b/dl/script/dl_script.cpp @@ -3,54 +3,323 @@ #include #include "io/dl_log.h" +#include "base/dl_string.h" namespace dl { enum class ScriptLogType { + E_debug, E_info, - E_err, // Óû§´íÎó - E_damage, // ÒýÇæbug + E_err, // 用户错误 + E_damage, // 引擎bug E_compile, }; - void dl_script_print(ScriptLogType type, std::string_view str) + void script_print(ScriptLogType type, std::string_view str) { switch (type) { - case dl::ScriptLogType::E_info: - log_msg("dl_script:¡¾Ìáʾ¡¿ {}", str); + case ScriptLogType::E_debug: + log_msg("script:【调试】 {}", str); break; - case dl::ScriptLogType::E_err: - log_warn("dl_script:¡¾´íÎó¡¿ {}", str); + case ScriptLogType::E_info: + log_msg("script:【提示】 {}", str); break; - case dl::ScriptLogType::E_damage: - log_err("dl_script:¡¾ÑÏÖشíÎó¡¿ {}", str); + case ScriptLogType::E_err: + log_warn("script:【错误】 {}", str); break; - case dl::ScriptLogType::E_compile: - log_err("dl_script:¡¾±àÒë´íÎó¡¿ {}", str); + case ScriptLogType::E_damage: + log_err("script:【严重错误】 {}", str); + break; + case ScriptLogType::E_compile: + log_err("script:【编译错误】 {}", str); break; default: assert(0); break; } } - void dl_script_damage(std::string_view str) + struct Token { - log_err("dl_script:¡¾ÑÏÖشíÎó¡¿{}", str); - } -#define dl_script_err log_err + enum Type + { + NORMAL, + STRING, + LBRACE, // 括号类 + RBRACE, + }; + Token() : + _type{ Type::NORMAL } + {} + Token(Type type, std::string_view str) : + _type{ type }, + _str{ std::string{str} } + {} + Type _type; + std::string _str; + }; ScriptBlock ScriptSystem::Compile(std::string_view src) { + script_print(ScriptLogType::E_debug, fmt::format("{:=^32}", "开始编译脚本")); + script_print(ScriptLogType::E_debug, fmt::format("源:\n{}", src)); + ScriptBlock ret; + std::vector& vec_seg = ret._allSeg; + std::size_t beg = 0; + std::size_t end = 0; + std::vector vec_token; + // 括号层级 + size_t level_brace = 0; + + enum class State + { + FREE,// 空闲 + NORMAL,// 单词匹配 + STRING,// 字符串 + }; + State state = State::FREE; + + // 构造当前 + auto fn_string = [&]() { +#if DL_PLATFORM == DL_PLATFORM_WIN32 + return std::string_view{ src.begin() + beg, src.begin() + end }; +#else + return std::string_view{ str.begin(), end - beg }; +#endif + }; + // 构造word + auto fn_make_word = [&](Token::Type type) { + std::string_view word = fn_string(); + if (!word.empty()) + { + script_print(ScriptLogType::E_debug, fmt::format("匹配到token{}:[{}]", (int)type, word)); + vec_token.push_back({ type, word }); + } + }; + // 一段完成 + auto fn_segment = [&]() { + script_print(ScriptLogType::E_debug, fmt::format("代码段完成,词数量 {}", vec_token.size())); + + if (vec_token.empty()) + { + log_warn("空代码段!"); + return; + } + + vec_seg.push_back({}); + ScriptSegment& seg = vec_seg.back(); + + size_t i = 0; + for (Token& token : vec_token) + { + //script_print(ScriptLogType::E_debug, fmt::format("{}: {}", (int)token._type, token._str)); + //if (i == 0) + //{ + // if (token._str == "if") + // { + // } + // else + // {// 变量 + + // } + //} + //seg._expr._allVar.push_back(token.) + } + + + // 首token + std::string_view t0 = vec_token[0]._str; + size_t num_token = vec_token.size(); + if (t0.empty()) + { + script_print(ScriptLogType::E_compile, fmt::format("首字为空!")); + return; + } + bool is_keyword = g_script->IsKeyword(t0); + if (is_keyword) + { + + } + else + { + if (num_token > 2) + { + std::string_view t1 = vec_token[1]._str; + std::string_view t2 = vec_token[2]._str; + seg._type = ScriptSegmentType::E_expr; + seg._expr._allVar.resize(3); + seg._expr._allVar[0] = ScriptVar(String::toInt64(t0)); + seg._expr._allVar[1] = ScriptVar(String::toInt64(t2)); + //if(g_script->IsVariable(t0)) + seg._expr._allVar[2] = String2Operator(t1); + } + } + // + vec_token.clear(); + }; + + while (true) + { + char ch = src[end]; + switch (state) + { + case State::FREE: + {// 空闲状态,跳过空白字符 + if (ch == ' ' || ch == '\t' || ch == '\n') + { + ++beg; + ++end; + } + else + { + state = State::NORMAL; + ++end; + } + } + break; + case State::NORMAL: + {// 普通字符则继续, + if (ch == ' ' || ch == '\t' || ch == '\n') + { + fn_make_word(Token::Type::NORMAL); + if (ch == '\n' && level_brace == 0) + { + fn_segment(); // 解析代码段 + } + ++end; + beg = end; + } + else if (ch == '\'' || ch == '\"') + { + state = State::STRING; + ++beg; + ++end; + } + else if (ch == '(' || ch == '{' || ch == '[') + { + fn_make_word(Token::Type::LBRACE); + ++level_brace; + } + else if (ch == ')' || ch == '}' || ch == ']') + { + fn_make_word(Token::Type::RBRACE); + if (level_brace == 0) + { + script_print(ScriptLogType::E_compile, fmt::format("括号数量不匹配,右括号数量过多!")); + return {}; + } + else if (level_brace == 1) + { + fn_segment(); + ++end; + beg = end; + } + else + ++end; + --level_brace; + } + else + ++end; + } + break; + case State::STRING: + { + if (ch == '\'' || ch == '\"') + { + fn_make_word(Token::Type::STRING); + + ++end; + beg = end; + state = State::NORMAL; + } + else + ++end; + } + break; + default: + break; + } + + if (end >= src.size()) + { + fn_make_word(Token::Type::NORMAL); + fn_segment(); + break; + } + } + + script_print(ScriptLogType::E_debug, fmt::format("{:=^32}", "词法分析完成")); + + return ret; + } + + bool ScriptSystem::IsKeyword(std::string_view str) + { + return _allKeyword.contains(std::string{ str }); + } + + bool ScriptSystem::IsVariable(std::string_view str) + { + /*变量名称只能使用字母、数字和下划线。 + + 第一个字符必须是字母或下划线,因为C++不允许数字作为变量名的首字符。 + + 区分大小写,即变量name和Name是不同的。 + + 避免使用C++的关键字和保留字作为变量名。*/ + assert(!str.empty()); + if (!std::isalpha(str[0]) && str[0] != '_') + return false; + + for (auto& iter : str) + { + if (iter != '_' + && !std::isalpha(iter) + && !std::isdigit(iter)) + return false; + } + return true; + } + + dl::ScriptVar ScriptSystem::String2Operator(std::string_view str) + { + if (str == "=") + return ScriptOperator::E_assign; + if (str == "+") + return ScriptOperator::E_add; + if (str == "-") + return ScriptOperator::E_sub; + if (str == "*") + return ScriptOperator::E_mul; + if (str == "/") + return ScriptOperator::E_div; + return {}; + } + + ScriptSystem::ScriptSystem() + { + _allKeyword["function"] = 0; + _allKeyword["param"] = 0; + _allKeyword["typeof"] = 0; + _allKeyword["is_null"] = 0; + _allKeyword["operator"] = 0; + _allKeyword["return"] = 0; + _allKeyword["new"] = 0; + _allKeyword["if"] = 0; + _allKeyword["elseif"] = 0; + _allKeyword["else"] = 0; + _allKeyword["while"] = 0; + _allKeyword["for"] = 0; + _allKeyword["goto"] = 0; } void ScriptVM::Execute(const ScriptBlock& block) { - dl_script_print(ScriptLogType::E_info, fmt::format("¿ªʼִÐдúÂë¿飺{}", block._name)); + script_print(ScriptLogType::E_info, fmt::format("开始执行代码块:{}", block._name)); size_t cur = 0; while (cur < block._allSeg.size()) @@ -72,10 +341,12 @@ namespace dl case ScriptSegmentType::E_for: break; default: - dl_script_print(ScriptLogType::E_damage, fmt::format("δ֪´úÂë¶ÎÀàÐͣº{}ÐУ¬{}", seg._lineNumber, seg._type)); + script_print(ScriptLogType::E_damage, fmt::format("未知代码段类型:{}行,{}", seg._lineNumber, (int)seg._type)); return; } + ++cur; } + script_print(ScriptLogType::E_info, fmt::format("完成执行代码块:{}", block._name)); } /*switch (seg._expr._op) @@ -89,7 +360,7 @@ namespace dl case ScriptExprOperator::E_div: break; default: - dl_script_print(ScriptLogType::E_compile, fmt::format("δ֪²Ù×÷·û£º{}", block._name)); + script_print(ScriptLogType::E_compile, fmt::format("未知操作符:{}", block._name)); break; }*/ void ScriptVM::_exec_expr(const ScriptExpr& expr) @@ -104,34 +375,39 @@ namespace dl const ScriptVar& var = vec_var[i]; if (var._type == ScriptVarType::E_operator) { - ScriptOperator& op = _get_var_operator(var); - switch (op) + ScriptOperator* op = _get_var_operator(var); + switch (*op) { + case ScriptOperator::E_add: + var_ret = _op_assign(vec_var, stack_var); + break; case ScriptOperator::E_add: var_ret = _op_add(vec_var, stack_var); break; case ScriptOperator::E_sub: - break; + //break; case ScriptOperator::E_mul: - break; + //break; case ScriptOperator::E_div: - break; + //break; default: - dl_script_print(ScriptLogType::E_damage, fmt::format("δ֪²Ù×÷·û£º{}", (int)op)); + script_print(ScriptLogType::E_damage, fmt::format("未知操作符:{}", (int)op)); break; } } + else + { + stack_var.push(i); + } } } - constexpr ScriptIndex - ScriptVar ScriptVM::_op_add(const std::vector& vec_var, std::stack& stack_var) { if (stack_var.size() < 2) { - dl_script_print(ScriptLogType::E_damage, fmt::format("²Ù×÷ÊýÁ¿²»ƥÅ䣺add£¬{}", 2)); - return { ScriptVarType::E_null }; + script_print(ScriptLogType::E_damage, fmt::format("操作数量不匹配:add,{}", 2)); + return {}; } ScriptIndex v0 = stack_var.top(); stack_var.pop(); @@ -141,17 +417,84 @@ namespace dl const ScriptVar& var0 = vec_var[v0]; const ScriptVar& var1 = vec_var[v1]; - if (var0._type != var1._type) + if (var0._type == ScriptVarType::E_int) { - dl_script_print(ScriptLogType::E_damage, fmt::format("²Ù×÷ÀàÐͲ»ƥÅ䣺add£¬{}, {}", var0._type, var1._type)); - stack_var.push(-1); - return { ScriptVarType::E_null }; + if (var1._type == ScriptVarType::E_int) + { + stack_var.push((size_t)-1); + return ScriptVar(var0.ToInt() + var1.ToInt()); + } + else if(var1._type == ScriptVarType::E_float) + { + return ScriptVar((ScriptFloat)var0.ToInt() + var1.ToFloat()); + } + else + { + goto error; + } } + else if (var0._type == ScriptVarType::E_float) + { + if (var1._type == ScriptVarType::E_int) + { + return ScriptVar(var0.ToInt() + (ScriptFloat)var1.ToInt()); + } + else if (var1._type == ScriptVarType::E_float) + { + return ScriptVar(var0.ToInt() + var1.ToFloat()); + } + else + { + goto error; + } + } + else + { + goto error; + } + error: + script_print(ScriptLogType::E_damage, + fmt::format("不能执行操作:add,{}, {}", var0.GetTypeString(), var1.GetTypeString())); + return {}; + } - ScriptVar ret; - ret._type = var0._type; - ret._index = (ScriptIndex)-1; - return ret; + dl::ScriptVar ScriptVM::_op_assign(const std::vector& vec_var, std::stack& stack_var) + { + + } + + std::string_view ScriptVar::GetTypeString() const + { + switch (_type) + { + case dl::ScriptVarType::E_null: + return "null"; + case dl::ScriptVarType::E_int: + return "int"; + case dl::ScriptVarType::E_float: + return "float"; + case dl::ScriptVarType::E_string: + return "string"; + case dl::ScriptVarType::E_class: + return "class"; + case dl::ScriptVarType::E_vector: + return "vector"; + case dl::ScriptVarType::E_table: + return "table"; + case dl::ScriptVarType::E_function: + return "function"; + case dl::ScriptVarType::E_userdata: + return "userdata"; + case dl::ScriptVarType::E_expr: + return "expr"; + case dl::ScriptVarType::E_operator: + return "operator"; + case dl::ScriptVarType::E_max: + default: + script_print(ScriptLogType::E_damage, + fmt::format("错误的变量类型:{}", (int)_type)); + return "error"; + } } } diff --git a/dl/script/dl_script.h b/dl/script/dl_script.h index fd140bd5..ff361781 100644 --- a/dl/script/dl_script.h +++ b/dl/script/dl_script.h @@ -18,6 +18,7 @@ #include #include #include +#include namespace dl { @@ -26,6 +27,8 @@ namespace dl using ScriptFloat = double; using ScriptString = std::string; + constexpr ScriptIndex SCRIPT_INDEX_NAG_1 = (ScriptIndex)-1; + //! 变量类型 enum class ScriptVarType : ScriptIndex { @@ -43,25 +46,67 @@ namespace dl E_max }; - //! 变量 + //! 操作类型 + enum class ScriptOperator : ScriptIndex + { + E_assign, // 赋值 + E_add, // + E_sub, + E_mul, + E_div, + }; + + //! 变量(大小严格控制) struct ScriptVar { + public: + ScriptVar() + { + _type = ScriptVarType::E_null; + } + ScriptVar(ScriptInt v) + { + _type = ScriptVarType::E_int; + *(ScriptInt*)&_value = *(ScriptInt*)&v; + } + ScriptVar(ScriptFloat v) + { + _type = ScriptVarType::E_float; + *(ScriptFloat*)&_value = *(ScriptFloat*)&v; + } + ScriptVar(ScriptOperator v) + { + _type = ScriptVarType::E_operator; + *(ScriptVarType*)&_value = *(ScriptVarType*)&v; + } + + ScriptInt ToInt() const + { + assert(_type == ScriptVarType::E_int); + return *(ScriptInt*)&_value; + } + ScriptFloat ToFloat() const + { + assert(_type == ScriptVarType::E_float); + return *(ScriptFloat*)&_value; + } + ScriptOperator ToOperator() const + { + assert(_type == ScriptVarType::E_operator); + return *(ScriptOperator*)&_value; + } + + std::string_view GetTypeString() const; + public: ScriptVarType _type; - ScriptIndex _index; + uint8_t _indexVarSpace;// 所在变量空间 + uint64_t _value; }; using ScriptVector = std::vector; using ScriptTable = std::unordered_map; using ScriptFunction = std::function; - //! 操作类型 - enum class ScriptOperator : ScriptIndex - { - E_add, - E_sub, - E_mul, - E_div, - }; //! 后缀表达式 struct ScriptExpr { @@ -72,45 +117,15 @@ namespace dl //! 变量空间 struct ScriptVarSpace { - std::vector _vecInt; - std::vector _vecFloat; std::vector _vecString; std::vector _vecClass; std::vector _vecVector; std::vector _vecTable; std::vector _vecFunction; - std::vector _vecUserdata; std::vector _vecExpr; - std::vector _vecOperator; - }; - - //! 控制语句 - struct ScriptControlIf - { - ScriptExpr _cond; - ScriptSegment _seg; - }; - struct ScriptControlIfElse - { - ScriptExpr _cond; - ScriptSegment _seg; - }; - struct ScriptControlElse - { - ScriptExpr _cond; - ScriptSegment _seg; - }; - struct ScriptControlFor - { - std::array _cond; - ScriptSegment _seg; - }; - struct ScriptControlWhile - { - ScriptExpr _cond; - ScriptSegment _seg; }; + enum class ScriptSegmentType : ScriptIndex { E_expr, @@ -137,6 +152,34 @@ namespace dl std::string _name; }; + + //! 控制语句 + struct ScriptControlIf + { + ScriptExpr _cond; + ScriptSegment _seg; + }; + struct ScriptControlIfElse + { + ScriptExpr _cond; + ScriptSegment _seg; + }; + struct ScriptControlElse + { + ScriptExpr _cond; + ScriptSegment _seg; + }; + struct ScriptControlFor + { + std::array _cond; + ScriptSegment _seg; + }; + struct ScriptControlWhile + { + ScriptExpr _cond; + ScriptSegment _seg; + }; + //! 虚拟机 class ScriptVM { @@ -148,13 +191,17 @@ namespace dl void _exec_expr(const ScriptExpr& expr); - ScriptOperator& _get_var_operator(const ScriptVar& var) + ScriptOperator* _get_var_operator(const ScriptVar& var) { assert(var._type == ScriptVarType::E_operator); - return _varGlobal->_vecOperator[var._index]; + return (ScriptOperator*)&var._value; + /*if(var._indexVarSpace == SCRIPT_INDEX_NAG_1) + return _varGlobal->_vecOperator[var._index]; + return _varGlobal->_vecOperator[var._index];*/ } ScriptVar _op_add(const std::vector& vec_var, std::stack& stack_var); + ScriptVar _op_assign(const std::vector& vec_var, std::stack& stack_var); }; //! 管理器 @@ -162,6 +209,15 @@ namespace dl { public: ScriptBlock Compile(std::string_view src); + + //! 是否关键字 + bool IsKeyword(std::string_view str); + //! 是否变量 + bool IsVariable(std::string_view str); + //! 字符串转操作符变量 + ScriptVar String2Operator(std::string_view str); + + ScriptSystem(); private: // 关键字 std::unordered_map _allKeyword; diff --git a/dlconsole/main.cpp b/dlconsole/main.cpp index c3a81865..6654fe9a 100644 --- a/dlconsole/main.cpp +++ b/dlconsole/main.cpp @@ -46,7 +46,15 @@ int main() // } //} - g_script->Execute() + ScriptBlock block = g_script->Compile(R"( +print "hello dl!" +a = 1 +b = 2 +print a + b + )"); + + ScriptVM vm; + vm.Execute(block); Engine::Release(); return 0; diff --git a/document/脚本设计文档.txt b/document/脚本设计文档.txt index d9789d7a..42f4b082 100644 --- a/document/脚本设计文档.txt +++ b/document/脚本设计文档.txt @@ -6,6 +6,12 @@ is_null 变量为空,等价 typeof == "null" operator操作符重载 return 函数返回值 new 定义 +if +elseif +else +while +for +goto 【内置函数表】 print 打印字符串 @@ -62,6 +68,9 @@ add(1, 2) ! 逻辑取反,非0为true &&、|| 逻辑与或 +算术运算: + float和int可以进行算术运算 + 【作用域】 以{}包含一个作用域,作用域内的局部变量,超出作用域会删除 @@ -136,7 +145,8 @@ while i < 10 { 代码段: 代码段是执行的基本单元。 代码段按顺序执行,或通过控制语句跳转。 - 代码段包含表达式、控制语句, + 代码段包含表达式、控制语句……。 + 代码段默认为单行,未匹配的(、{、[可以将单行拓展为多行 虚拟机: 动态变化的内容,维护内存数据。 表达式: