* 脚本系统改进

This commit is contained in:
2024-05-31 19:07:47 +08:00
parent 8c993517fe
commit df05468fcd
4 changed files with 498 additions and 81 deletions
+379 -36
View File
@@ -3,54 +3,323 @@
#include <cassert>
#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<ScriptSegment>& vec_seg = ret._allSeg;
std::size_t beg = 0;
std::size_t end = 0;
std::vector<Token> 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<ScriptVar>& vec_var, std::stack<size_t>& 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<ScriptVar>& vec_var, std::stack<size_t>& 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";
}
}
}