From f0ab6615b29930319424b90e284381aa95612599 Mon Sep 17 00:00:00 2001 From: esrrhs Date: Fri, 27 Nov 2026 09:25:56 +0800 Subject: [PATCH] fix: resolve project-wide review findings Co-authored-by: Cursor --- cmd/main.cpp | 11 +- include/fakelua.h | 68 +- src/compile/c_gen.cpp | 657 +++++++---- src/compile/c_gen.h | 96 +- src/compile/c_runtime_cov.h | 146 ++- src/compile/c_runtime_header.h | 146 ++- src/compile/compile_common.h | 74 +- src/compile/flex/scanner.cpp | 109 +- src/compile/flex/scanner.l | 113 +- src/compile/my_flexer.cpp | 14 +- src/compile/preprocessor.cpp | 4 +- src/compile/semantic_analysis.cpp | 194 +++- src/compile/semantic_analysis.h | 3 +- src/compile/type_inferencer.cpp | 1281 +++++++++++++++++---- src/compile/type_inferencer.h | 53 +- src/interp/codegen.cpp | 153 ++- src/interp/codegen.h | 3 + src/interp/func_proto.h | 4 + src/interp/interpreter.cpp | 178 ++- src/interp/opcode.h | 7 +- src/interp/vm_ops.h | 9 +- src/jit/code_binding.h | 4 +- src/jit/gcc_jit.cpp | 12 +- src/jit/tcc_handle.cpp | 1 + src/jit/tcc_jit.cpp | 6 +- src/jit/vm.cpp | 37 + src/jit/vm.h | 20 +- src/jit/vm_function.h | 8 +- src/native/basic/native_basic.cpp | 93 +- src/native/compress/compress_lz4.cpp | 52 +- src/native/compress/compress_zlib.cpp | 29 +- src/native/crypto/crypto_aes.cpp | 118 +- src/native/crypto/crypto_cipher.cpp | 155 ++- src/native/crypto/native_crypto.cpp | 85 +- src/native/event/native_event.cpp | 106 +- src/native/http/native_http.cpp | 196 +++- src/native/ini/native_ini.cpp | 4 +- src/native/io/native_io.cpp | 46 +- src/native/json/native_json.cpp | 2 +- src/native/mysql/mysql_connection.cpp | 238 +++- src/native/mysql/mysql_connection.h | 14 + src/native/mysql/native_mysql.cpp | 39 +- src/native/mysql/native_mysql_pool.cpp | 31 +- src/native/native_common.h | 74 ++ src/native/net/native_net.cpp | 226 ++-- src/native/net/net_event.cpp | 82 +- src/native/net/net_event.h | 9 +- src/native/object/native_object.cpp | 169 ++- src/native/object/native_object.h | 5 +- src/native/os/native_os.cpp | 30 +- src/native/process/native_process.cpp | 267 ++++- src/native/protobuf/native_protobuf.cpp | 29 +- src/native/protobuf/protobuf_parser.cpp | 195 +++- src/native/random/native_random.cpp | 33 +- src/native/redis/native_redis.cpp | 146 ++- src/native/serialize/native_serialize.cpp | 43 +- src/native/sqlite/native_sqlite.cpp | 2 + src/native/string/native_string.cpp | 187 +-- src/native/table/native_table.cpp | 155 ++- src/native/table/native_table.h | 1 + src/native/timer/native_timer.cpp | 133 +-- src/native/tls_util.h | 45 +- src/native/toml/native_toml.cpp | 84 +- src/native/url/native_url.cpp | 12 +- src/native/xml/native_xml.cpp | 8 +- src/native/yaml/native_yaml.cpp | 101 +- src/state/fakelua.cpp | 278 ++++- src/state/heap.cpp | 22 +- src/state/state.h | 55 +- src/util/file_util.cpp | 15 +- src/util/logging.cpp | 20 +- src/var/var.cpp | 23 +- src/var/var_closure.h | 13 + test/test_infer.cpp | 27 +- test/test_jitter.cpp | 117 +- 75 files changed, 5427 insertions(+), 1798 deletions(-) diff --git a/cmd/main.cpp b/cmd/main.cpp index 0fe3fc44..94f642e3 100644 --- a/cmd/main.cpp +++ b/cmd/main.cpp @@ -241,14 +241,17 @@ int main(int argc, char **argv) { try { RegisterExitApi(s); + if (FLAGS_jit_type < 0 || FLAGS_jit_type >= static_cast(JIT_MAX)) { + std::cerr << "flua: invalid --jit_type=" << FLAGS_jit_type << " (expected 0=TCC, 1=GCC, 2=INTERP)" << std::endl; + return 1; + } CompileConfig cfg; cfg.debug_mode = FLAGS_debug; - // 只编译实际要用的后端:三个都编的话,选 interp 也要为每个文件付一次 GCC 编译 - // (几百毫秒)和它的告警。interp 模式下仍留 TCC:pcall / load 的源码闭包按 - // JIT_TCC 调起,关掉会让它们没有可去的引擎。 + // 只编译并初始化实际选中的那一个后端,避免 __fakelua_init 在多个后端重复执行副作用。 const auto chosen = static_cast(FLAGS_jit_type); - cfg.disable_jit[JIT_TCC] = (chosen != JIT_TCC && chosen != JIT_INTERP); + cfg.disable_jit[JIT_TCC] = (chosen != JIT_TCC); cfg.disable_jit[JIT_GCC] = (chosen != JIT_GCC); + cfg.disable_jit[JIT_INTERP] = (chosen != JIT_INTERP); for (const auto &file: CollectLuaFiles(argv[1])) { CompileFile(s, file, cfg); } diff --git a/include/fakelua.h b/include/fakelua.h index b3cb7179..4719813d 100644 --- a/include/fakelua.h +++ b/include/fakelua.h @@ -666,6 +666,8 @@ CVar AllocMultiCVar(State *s, int count); void SetMultiCVarElement(CVar &multi, int idx, CVar val); CVar GetMultiCVarElement(const CVar &multi, int idx); int GetMultiCVarCount(const CVar &multi); +CVar GetReturnElement(State *s, const CVar &ret_var, std::size_t idx); +CVar UnboxFirstReturn(State *s, const CVar &ret_var); int64_t CVarToInteger(const CVar &v, int64_t default_val = 0); double CVarToNumber(const CVar &v, double default_val = 0.0); bool CVarToBool(const CVar &v, bool default_val); @@ -673,6 +675,14 @@ std::string CVarToString(const CVar &v, const char *default_val); CVar GetNativeArg(State *s, CVar *args, int n, int idx); +struct PreservedCVarArg { + CVar raw{}; + bool has_saved_str = false; + std::string saved_str; +}; +PreservedCVarArg PreserveCVarBeforeReset(const CVar &v, bool will_reset); +CVar MaterializePreservedCVar(State *s, const PreservedCVarArg &p); + }// namespace inter // --------------------------------------------------------------------------- @@ -692,7 +702,31 @@ namespace inter { template void UnpackMultiToTuple(State *s, const CVar &ret_var, Tuple &tuple, std::index_sequence) { - ((std::get(tuple) = FakeluaToNative>>>(s, inter::GetMultiCVarElement(ret_var, I))), ...); + ((std::get(tuple) = FakeluaToNative>>>(s, inter::GetReturnElement(s, ret_var, I))), ...); +} + +template +decltype(auto) PrepareCallArgBeforeReset(T &&arg, [[maybe_unused]] bool will_reset) { + using Decayed = std::remove_cvref_t; + if constexpr (std::is_same_v) { + return std::string(arg); + } else if constexpr (std::is_same_v || std::is_same_v) { + return arg ? std::string(arg) : std::string{}; + } else if constexpr (std::is_same_v) { + return PreserveCVarBeforeReset(arg, will_reset); + } else { + return std::forward(arg); + } +} + +template +CVar MarshalPreparedCallArg(State *s, T &&prepared) { + using Decayed = std::remove_cvref_t; + if constexpr (std::is_same_v) { + return MaterializePreservedCVar(s, prepared); + } else { + return NativeToFakelua(s, std::forward(prepared)); + } } }// namespace inter @@ -727,17 +761,27 @@ void Call(State *s, JITType type, const std::string_view &name, Ret &&ret, Args inter::ThrowInterFakeluaException(std::format("Call failed, function {} arg count not match, need {} get {}", name, arg_count, user_arg_count)); } - if (const auto reentrant_count = inter::GetReentrantCount(s); !reentrant_count) { - inter::Reset(s); - } - inter::ReentryCounter rc(s); - - // 将模板参数转为 CVar 数组 + const bool will_reset = !inter::GetReentrantCount(s); CVar call_cvars[kMaxFunctionInputParams] = {}; - if constexpr (sizeof...(Args) > 0) { - int idx = 0; - ((call_cvars[idx++] = inter::NativeToFakelua(s, std::forward(args))), ...); + if constexpr (sizeof...(Args) == 0) { + if (will_reset) { + inter::Reset(s); + } + } else { + // 先保存可能指向旧 temp_heap 的 string_view / const char* / CVar 字符串,再 Reset,避免被新实参原地覆盖。 + auto prepared_args = std::tuple(args), will_reset))...>{ + inter::PrepareCallArgBeforeReset(std::forward(args), will_reset)...}; + if (will_reset) { + inter::Reset(s); + } + std::apply( + [&](auto &&...items) { + int idx = 0; + ((call_cvars[idx++] = inter::MarshalPreparedCallArg(s, std::forward(items))), ...); + }, + std::move(prepared_args)); } + inter::ReentryCounter rc(s); // vararg:将多余参数打包为 Multi if (__builtin_expect(is_vararg, 0)) { @@ -758,8 +802,10 @@ void Call(State *s, JITType type, const std::string_view &name, Ret &&ret, Args if constexpr (is_std_tuple_v) { constexpr std::size_t N = std::tuple_size_v; inter::UnpackMultiToTuple(s, ret_var, ret, std::make_index_sequence{}); - } else { + } else if constexpr (std::is_same_v) { ret = inter::FakeluaToNative(s, ret_var); + } else { + ret = inter::FakeluaToNative(s, inter::UnboxFirstReturn(s, ret_var)); } } diff --git a/src/compile/c_gen.cpp b/src/compile/c_gen.cpp index 168522a9..15a01042 100644 --- a/src/compile/c_gen.cpp +++ b/src/compile/c_gen.cpp @@ -37,10 +37,85 @@ bool CGen::IsFuncLocalName(const std::string &lua_name) const { return false; } +std::string CGen::FileCIdent(const std::string &lua_name) { + if (const auto it = file_c_ident_map_.find(lua_name); it != file_c_ident_map_.end()) { + return it->second; + } + std::string base = SanitizeCIdent(lua_name); + if (base.empty()) { + base = "flua_id"; + } + std::string cand = base; + int n = 0; + while (!file_c_ident_used_.insert(cand).second) { + cand = base + "_" + std::to_string(++n); + } + file_c_ident_map_[lua_name] = cand; + return cand; +} + +std::string CGen::AllocFuncVarCIdent(FuncInfo *func, const std::string &lua_name) { + DEBUG_ASSERT(func != nullptr); + std::string base = SanitizeCIdent(lua_name); + if (base.empty()) { + base = "flua_id"; + } + if (!func->c_ident_map.contains(lua_name)) { + std::string cand = base; + int n = 0; + while (!func->c_ident_used.insert(cand).second) { + cand = base + "_" + std::to_string(++n); + } + func->c_ident_map[lua_name] = cand; + return cand; + } + const std::string shadow_base = "flua_s_" + base; + int n = 0; + std::string cand; + do { + cand = shadow_base + "_" + std::to_string(++n); + } while (!func->c_ident_used.insert(cand).second); + return cand; +} + +std::string CGen::DefSlotCIdent(const SyntaxTreeInterface *stmt_ptr, size_t slot, const std::string &fallback_name) { + if (stmt_ptr != nullptr) { + if (const auto it = stmt_defs_.find(stmt_ptr); it != stmt_defs_.end() && slot < it->second.size()) { + const VarDef *def = it->second[slot]; + if (def && def->defining_func != nullptr && !def->c_ident.empty()) { + return def->c_ident; + } + } + } + return CIdent(fallback_name); +} + +std::string CGen::VarCIdent(const SyntaxTreeVar *var_ptr) { + if (!var_ptr) { + return ""; + } + if (const auto it = var_to_def_map_.find(var_ptr); it != var_to_def_map_.end()) { + const VarDef *def = it->second; + if (def && def->defining_func != nullptr && !def->c_ident.empty()) { + return def->c_ident; + } + if (def && def->defining_func == nullptr) { + return FileCIdent(var_ptr->GetName()); + } + } + if (!BindsLocalValue(var_ptr)) { + return FileCIdent(var_ptr->GetName()); + } + return CIdent(var_ptr->GetName()); +} + std::string CGen::CIdent(const std::string &lua_name) { const bool is_local = IsFuncLocalName(lua_name); - auto &map = is_local ? cur_func_info_->c_ident_map : file_c_ident_map_; - auto &used = is_local ? cur_func_info_->c_ident_used : file_c_ident_used_; + if (!is_local) { + return FileCIdent(lua_name); + } + auto &map = cur_func_info_->c_ident_map; + auto &used = cur_func_info_->c_ident_used; if (const auto it = map.find(lua_name); it != map.end()) { return it->second; } @@ -88,8 +163,9 @@ std::string CGen::LookupFuncCName(const std::string &lua_name) const { } void CGen::UniquifyFuncCNames() { - file_c_ident_used_.insert({"__fakelua_bind", "_S", "__fakelua_init_flag__", "fl_temp_heap", "fl_const_heap", "fl_lua_loc", "fl_active_loc", "fl_vm_version", "fl_lua_file", "fl_lua_frames", - "fl_lua_depth", "fl_active_base", "fl_lua_fn_map", "fl_lua_fn_map_n", "__fl_saved_frame", "__fl_frame_ret", "kNil", "kTrue", "kFalse", kInitFunctionName}); + file_c_ident_used_.insert({"__fakelua_bind", "_S", "__fakelua_init_flag__", "fl_const_alloc", "fl_const_alloc_false", "fl_temp_heap", "fl_const_heap", "fl_lua_loc", "fl_active_loc", + "fl_vm_version", "fl_lua_file", "fl_lua_frames", "fl_lua_depth", "fl_active_base", "fl_lua_fn_map", "fl_lua_fn_map_n", "__fl_saved_frame", "__fl_frame_ret", "kNil", + "kTrue", "kFalse", kInitFunctionName}); FuncInfo *real_init = nullptr; for (auto it = all_funcs_.rbegin(); it != all_funcs_.rend(); ++it) { @@ -175,6 +251,8 @@ bool CGen::ClassifyLiteralKey(const SyntaxTreeInterfacePtr &exp, LiteralKeyInfo if (ClassifyConstNumberExp(exp, kind, canonical, int_value, float_value)) { out.kind = kind; out.repr = canonical; + out.int_value = int_value; + out.float_value = float_value; return true; } } @@ -211,8 +289,8 @@ GenResult CGen::Generate(const ParseResult &pr, const InferResult &ir, const Ana LOG_DEBUG(s_, "engine", "CGen::Build complete: {} functions, {} bytes of C code", gr.function_names.size(), gr.c_code.size()); - // 如果开启了调试模式,将生成的 C 代码转储到临时文件中以供调试 - if (cfg.debug_mode) { + // 如果开启了调试模式且日志级别为 Debug/Trace,将生成的 C 代码转储到临时文件中以供调试 + if (cfg.debug_mode && s_ && s_->GetLogLevel() <= LogLevel::Debug) { const auto dumpfile = GenerateTmpFilename("fakelua_jit_", ".c"); if (std::ofstream ofs(dumpfile); ofs.is_open()) { ofs << gr.c_code; @@ -324,12 +402,13 @@ void CGen::GenerateBindings() { Out() << "};\n"; Out() << "static const int fl_lua_fn_map_n = " << fn_map_n << ";\n"; Out() << "#endif\n"; - Out() << "void *__fakelua_bind(void *s, void *temp, void *constant, const char *file, int64_t (*intern)(void *, const char *, size_t), void *active_loc, const void *vm_ver, void *lua_frames, int *lua_depth) {\n" + Out() << "void *__fakelua_bind(void *s, void *temp, void *constant, const char *file, int64_t (*intern)(void *, const char *, size_t), void *active_loc, const void *vm_ver, void *lua_frames, int *lua_depth, const void *const_alloc) {\n" << " _S = s; fl_temp_heap = temp; fl_const_heap = constant; fl_lua_file = file;\n" << " if (active_loc) { fl_active_loc = (FlLuaLoc *) active_loc; fl_active_base = fl_active_loc; }\n" << " if (vm_ver) fl_vm_version = (const uint64_t *) vm_ver;\n" << " if (lua_frames) fl_lua_frames = (FlLuaFrame *) lua_frames;\n" << " if (lua_depth) fl_lua_depth = lua_depth;\n" + << " if (const_alloc) fl_const_alloc = (const bool *) const_alloc;\n" << "#if !FL_SPEC_TRACK_FRAME\n" << " if (fl_lua_fn_map_n > 0) FakeluaRegisterFnMap((State *) s, &fl_lua_loc, fl_lua_fn_map, fl_lua_fn_map_n, file);\n" << "#endif\n"; @@ -407,9 +486,9 @@ void CGen::EmitSpecAccessorBody(const SpecTypeMetadata &meta, bool is_get) { for (const auto &f: meta.fields) { if (f.key_kind == TableKeyKind::kInt) { if (is_get) { - Out() << " case " << f.int_value << ": *__finish = true; return s->" << f.c_field_name << ";\n"; + Out() << " case " << FormatCInt64Literal(f.int_value) << ": *__finish = true; return s->" << f.c_field_name << ";\n"; } else { - Out() << " case " << f.int_value << ": s->" << f.c_field_name << " = v; tbl->spec_vals[" << f_idx << "] = v; tbl->spec_keys[" << f_idx + Out() << " case " << FormatCInt64Literal(f.int_value) << ": s->" << f.c_field_name << " = v; tbl->spec_vals[" << f_idx << "] = v; tbl->spec_keys[" << f_idx << "] = k; *__finish = true; return;\n"; } } @@ -423,10 +502,10 @@ void CGen::EmitSpecAccessorBody(const SpecTypeMetadata &meta, bool is_get) { for (const auto &f: meta.fields) { if (f.key_kind == TableKeyKind::kInt) { if (is_get) { - Out() << " if (__fval == (double)" << f.int_value << ") { *__finish = true; return s->" << f.c_field_name << "; }\n"; + Out() << " if (FL_INT_FLOAT_EQUAL(" << FormatCInt64Literal(f.int_value) << ", __fval)) { *__finish = true; return s->" << f.c_field_name << "; }\n"; } else { - Out() << " if (__fval == (double)" << f.int_value << ") { s->" << f.c_field_name << " = v; tbl->spec_vals[" << f_idx << "] = v; tbl->spec_keys[" << f_idx - << "] = k; *__finish = true; return; }\n"; + Out() << " if (FL_INT_FLOAT_EQUAL(" << FormatCInt64Literal(f.int_value) << ", __fval)) { s->" << f.c_field_name << " = v; tbl->spec_vals[" << f_idx << "] = v; tbl->spec_keys[" + << f_idx << "] = k; *__finish = true; return; }\n"; } } f_idx++; @@ -456,10 +535,10 @@ void CGen::EmitSpecAccessorBody(const SpecTypeMetadata &meta, bool is_get) { for (const auto &f: meta.fields) { if (f.key_kind == TableKeyKind::kFloat) { if (is_get) { - Out() << " if ((double)__ival == " << FormatCDoubleLiteral(f.float_value) << ") { *__finish = true; return s->" << f.c_field_name << "; }\n"; + Out() << " if (FL_INT_FLOAT_EQUAL(__ival, " << FormatCDoubleLiteral(f.float_value) << ")) { *__finish = true; return s->" << f.c_field_name << "; }\n"; } else { - Out() << " if ((double)__ival == " << FormatCDoubleLiteral(f.float_value) << ") { s->" << f.c_field_name << " = v; tbl->spec_vals[" << f_idx << "] = v; tbl->spec_keys[" - << f_idx << "] = k; *__finish = true; return; }\n"; + Out() << " if (FL_INT_FLOAT_EQUAL(__ival, " << FormatCDoubleLiteral(f.float_value) << ")) { s->" << f.c_field_name << " = v; tbl->spec_vals[" << f_idx + << "] = v; tbl->spec_keys[" << f_idx << "] = k; *__finish = true; return; }\n"; } } f_idx++; @@ -527,6 +606,7 @@ void CGen::GenerateHeader() { #include #include #include +#include )"; @@ -959,11 +1039,21 @@ bool CGen::StmtCanThrow(const SyntaxTreeInterfacePtr &stmt) { return false; case SyntaxTreeType::If: { const auto if_stmt = std::dynamic_pointer_cast(stmt); - return !if_stmt || TryCompileNativeBoolExpr(if_stmt->Exp()).empty(); + if (!if_stmt || !IsPureNativeBoolExp(if_stmt->Exp())) { + return true; + } + if (const auto elseifs = std::dynamic_pointer_cast(if_stmt->ElseIfs())) { + for (size_t i = 0; i < elseifs->ElseifSize(); ++i) { + if (!IsPureNativeBoolExp(elseifs->ElseifExp(i))) { + return true; + } + } + } + return false; } case SyntaxTreeType::While: { const auto while_stmt = std::dynamic_pointer_cast(stmt); - return !while_stmt || TryCompileNativeBoolExpr(while_stmt->Exp()).empty(); + return !while_stmt || !IsPureNativeBoolExp(while_stmt->Exp()); } case SyntaxTreeType::Assign: { const auto assign = std::dynamic_pointer_cast(stmt); @@ -1133,22 +1223,23 @@ void CGen::CompileFuncBody(const std::string &func_name, const SyntaxTreeInterfa } if (parlist_ptr) { - for (const auto &pname: cur_func_info_->params) { - if (IsCapturedInStmt(parlist_ptr, pname)) { - const auto cpname = CIdent(pname); - func_temp_decls_ << " CVar *__box_" << cpname << " = (CVar *)FlFastAlloc(_S, sizeof(CVar), !__fakelua_init_flag__);\n"; + for (size_t pi = 0; pi < cur_func_info_->params.size(); ++pi) { + const auto &pname = cur_func_info_->params[pi]; + if (IsSlotCapturedInStmt(parlist_ptr, pi, pname)) { + const auto cpname = DefSlotCIdent(parlist_ptr, pi, pname); + func_temp_decls_ << " CVar *__box_" << cpname << " = FlAllocUpvalueBox(_S, FL_IN_CONST_INIT);\n"; if (cur_spec_ctx_) { if (const auto pit = cur_spec_ctx_->param_types.find(pname); pit != cur_spec_ctx_->param_types.end()) { if (pit->second == T_INT) { - func_temp_decls_ << std::format(" *__box_{0} = (CVar){{.type_ = VAR_INT, .data_.i = {0}}};\n", cpname); + func_temp_decls_ << std::format(" FlStoreUpvalueBox(_S, __box_{0}, (CVar){{.type_ = VAR_INT, .data_.i = {0}}});\n", cpname); continue; } else if (pit->second == T_FLOAT) { - func_temp_decls_ << std::format(" *__box_{0} = (CVar){{.type_ = VAR_FLOAT, .data_.f = {0}}};\n", cpname); + func_temp_decls_ << std::format(" FlStoreUpvalueBox(_S, __box_{0}, (CVar){{.type_ = VAR_FLOAT, .data_.f = {0}}});\n", cpname); continue; } } } - func_temp_decls_ << " *__box_" << cpname << " = " << cpname << ";\n"; + func_temp_decls_ << " FlStoreUpvalueBox(_S, __box_" << cpname << ", " << cpname << ");\n"; } } } @@ -1168,6 +1259,9 @@ void CGen::CompileFuncBody(const std::string &func_name, const SyntaxTreeInterfa if (func_name == kInitFunctionName) { // 编译完成加载执行 __fakelua_init 时,初始化文件名并将本编译单元的文件级全局位置变量地址 // 传给宿主 State,后续运行期只修改 fl_lua_loc.line,抛异常时宿主直接从该地址读取文件与行号。 + // 若宿主已绑定 fl_const_alloc,入口即置位 __fakelua_init_flag__,使 init 中途失败后由 + // ConstAllocScope 析构自动回落到常规堆分配。 + out << " if (fl_const_alloc != &fl_const_alloc_false) __fakelua_init_flag__ = true;\n"; out << " fl_lua_loc.file = fl_lua_file;\n"; out << " FakeluaRegisterLuaLoc(_S, FAKELUA_JIT_TYPE, &fl_lua_loc);\n"; } @@ -1249,9 +1343,11 @@ InferredType CGen::GetType(const SyntaxTreeInterfacePtr &exp) const { if (const auto native_type = GetNativeVarType(name, var.get()); native_type == T_INT || native_type == T_FLOAT) { return native_type; } - if (const auto git = ir().global_const_vars.find(name); git != ir().global_const_vars.end()) { - if (git->second == T_INT || git->second == T_FLOAT) { - return git->second; + if (!BindsLocalValue(var.get())) { + if (const auto git = ir().global_const_vars.find(name); git != ir().global_const_vars.end()) { + if (git->second == T_INT || git->second == T_FLOAT) { + return git->second; + } } } return T_DYNAMIC; @@ -1265,10 +1361,16 @@ InferredType CGen::GetType(const SyntaxTreeInterfacePtr &exp) const { return T_DYNAMIC; } -// 尝试将表达式编译为高效的原生 C 数值运算表达式。若中途由于类型不匹配等抛出异常,则优雅捕获并返回空字符串(指示回退到动态分发计算) +// 尝试将表达式编译为高效的原生 C 数值运算表达式。若中途由于类型不匹配等抛出异常,则回滚半截输出并返回空字符串 std::string CGen::TryCompileNativeExpr(const SyntaxTreeInterfacePtr &exp) { + CodegenSnapshot snap(*this); try { - return CompileNumericExp(exp); + auto res = CompileNumericExp(exp); + if (!res.empty()) { + snap.Commit(); + return res; + } + return {}; } catch (...) { return {}; } @@ -1352,14 +1454,58 @@ std::string CGen::TryCompileNativeBoolExpr(const SyntaxTreeInterfacePtr &exp, bo if (require_pure && (!IsPureNativeNumericExp(e->Left()) || !IsPureNativeNumericExp(e->Right()))) { return {}; } + CodegenSnapshot snap(*this); const auto left_native = TryCompileNativeExpr(e->Left()); + if (left_native.empty()) { + return {}; + } const auto right_native = TryCompileNativeExpr(e->Right()); - DEBUG_ASSERT(!left_native.empty() && !right_native.empty()); + if (right_native.empty()) { + return {}; + } + snap.Commit(); return FormatNativeNumericComparison(left_native, right_native, left_type, right_type, op_kind); } return {}; } +bool CGen::IsPureNativeBoolExp(const SyntaxTreeInterfacePtr &exp) const { + if (!exp || exp->Type() != SyntaxTreeType::Exp) { + return false; + } + const auto e = std::dynamic_pointer_cast(exp); + if (!e) { + return false; + } + if (e->GetExpKind() == ExpKind::kPrefixExp) { + const auto pexp = std::dynamic_pointer_cast(e->Right()); + if (!pexp || pexp->GetPrefixKind() != PrefixExpKind::kExp) { + return false; + } + return IsPureNativeBoolExp(pexp->GetValue()); + } + if (e->GetExpKind() == ExpKind::kUnop) { + const auto unop = std::dynamic_pointer_cast(e->Op()); + if (!unop || unop->GetOpKind() != UnOpKind::kNot) { + return false; + } + return IsPureNativeBoolExp(e->Right()); + } + if (e->GetExpKind() != ExpKind::kBinop) { + return false; + } + const auto op = std::dynamic_pointer_cast(e->Op()); + if (!op || !kCmpOpMap.contains(op->GetOpKind())) { + return false; + } + const auto lt = e->Left() ? GetType(e->Left()) : T_DYNAMIC; + const auto rt = e->Right() ? GetType(e->Right()) : T_DYNAMIC; + if ((lt != T_INT && lt != T_FLOAT) || (rt != T_INT && rt != T_FLOAT)) { + return false; + } + return IsPureNativeNumericExp(e->Left()) && IsPureNativeNumericExp(e->Right()); +} + // 判定数值表达式能否编译为「不输出任何语句」的纯 C 表达式。 // 口径必须与 CompileNumericExp / CompileRawNativeArithBinop / CompileRawNativeUnop // 中每一处向 Out() 写语句(FlLenInt / FlFloorDivInt / FlModInt / FlLShiftInt / @@ -1680,12 +1826,13 @@ void CGen::CompileStmtLocalVar(const SyntaxTreeInterfacePtr &stmt) { // Compile prior expressions first (M - 1 expressions) for (size_t i = 0; i < exps.size() - 1; ++i) { const auto &name = names[i]; - const auto cname = CIdent(name); + const auto cname = DefSlotCIdent(stmt.get(), i, name); if (ar().global_const_names.contains(name)) { ThrowError("local variable conflicts with global constant: " + name, stmt); } - if (IsCapturedInStmt(stmt.get(), name)) { - EmitCapturedBoxDecl(name, CompileExp(exps[i])); + if (IsSlotCapturedInStmt(stmt.get(), i, name)) { + const std::string init = CompileExp(exps[i]); + EmitCapturedBoxDecl(cname, init); continue; } // All prior expressions map one-to-one to variables @@ -1693,14 +1840,7 @@ void CGen::CompileStmtLocalVar(const SyntaxTreeInterfacePtr &stmt) { if (type == T_INT || type == T_FLOAT) { const auto native_expr = CompileNumericExp(exps[i]); const std::string type_str = (type == T_INT) ? "int64_t" : "double"; - if (ir().shadowed_decls.contains({stmt.get(), name})) { - const auto tmp = std::format("flua_local_{}", tmp_var_counter_++); - func_temp_decls_ << " " << type_str << " " << tmp << ";\n"; - Out() << GenTab() << tmp << " = " << native_expr << ";\n"; - Out() << GenTab() << type_str << " " << cname << " = " << tmp << ";\n"; - } else { - Out() << GenTab() << type_str << " " << cname << " = " << native_expr << ";\n"; - } + Out() << GenTab() << type_str << " " << cname << " = " << native_expr << ";\n"; } else { const std::string init = CompileExp(exps[i]); Out() << GenTab() << "CVar " << cname << " = " << init << ";\n"; @@ -1716,12 +1856,12 @@ void CGen::CompileStmtLocalVar(const SyntaxTreeInterfacePtr &stmt) { // Assign unboxed values to remaining variables for (size_t i = exps.size() - 1; i < names.size(); ++i) { const auto &name = names[i]; - const auto cname = CIdent(name); + const auto cname = DefSlotCIdent(stmt.get(), i, name); if (ar().global_const_names.contains(name)) { ThrowError("local variable conflicts with global constant: " + name, stmt); } - if (IsCapturedInStmt(stmt.get(), name)) { - EmitCapturedBoxDecl(name, std::format("FlUnboxMulti({}, {})", tmp_res, i - (exps.size() - 1))); + if (IsSlotCapturedInStmt(stmt.get(), i, name)) { + EmitCapturedBoxDecl(cname, std::format("FlUnboxMulti({}, {})", tmp_res, i - (exps.size() - 1))); } else { Out() << GenTab() << "CVar " << cname << " = FlUnboxMulti(" << tmp_res << ", " << (i - (exps.size() - 1)) << ");\n"; } @@ -1730,14 +1870,15 @@ void CGen::CompileStmtLocalVar(const SyntaxTreeInterfacePtr &stmt) { // Standard one-to-one compilation path (or fallback path where extra variables get nil) for (size_t i = 0; i < names.size(); ++i) { const auto &name = names[i]; - const auto cname = CIdent(name); + const auto cname = DefSlotCIdent(stmt.get(), i, name); if (ar().global_const_names.contains(name)) { ThrowError("local variable conflicts with global constant: " + name, stmt); } - if (IsCapturedInStmt(stmt.get(), name)) { - EmitCapturedBoxDecl(name, (i < exps.size()) ? CompileExp(exps[i]) : "kNil"); + if (IsSlotCapturedInStmt(stmt.get(), i, name)) { + const std::string init = (i < exps.size()) ? CompileExp(exps[i]) : "kNil"; + EmitCapturedBoxDecl(cname, init); continue; } @@ -1745,14 +1886,7 @@ void CGen::CompileStmtLocalVar(const SyntaxTreeInterfacePtr &stmt) { if (type == T_INT || type == T_FLOAT) { const auto native_expr = CompileNumericExp(exps[i]); const std::string type_str = (type == T_INT) ? "int64_t" : "double"; - if (ir().shadowed_decls.contains({stmt.get(), name})) { - const auto tmp = std::format("flua_local_{}", tmp_var_counter_++); - func_temp_decls_ << " " << type_str << " " << tmp << ";\n"; - Out() << GenTab() << tmp << " = " << native_expr << ";\n"; - Out() << GenTab() << type_str << " " << cname << " = " << tmp << ";\n"; - } else { - Out() << GenTab() << type_str << " " << cname << " = " << native_expr << ";\n"; - } + Out() << GenTab() << type_str << " " << cname << " = " << native_expr << ";\n"; } else if (i < exps.size()) { const auto init_exp = std::dynamic_pointer_cast(exps[i]); bool is_degraded_expression = false; @@ -1813,7 +1947,7 @@ void CGen::CompileStmtAssign(const SyntaxTreeInterfacePtr &stmt) { DEBUG_ASSERT(v_ptr->GetVarKind() == VarKind::kSimple); if (const auto &name = v_ptr->GetName(); IsTypedNativeVar(name, v_ptr.get())) { // 被赋值变量是原生类型(int64_t / double)变量: - const auto cname = CIdent(name); + const auto cname = VarCIdent(v_ptr.get()); const auto var_type = GetNativeVarType(name, v_ptr.get()); if (const auto native_rhs = TryCompileNativeExpr(exps[0]); !native_rhs.empty()) { // RHS 可以直接编译为原生数值表达式——无需临时 CVar。 @@ -1867,6 +2001,12 @@ void CGen::CompileStmtAssign(const SyntaxTreeInterfacePtr &stmt) { } } else { const std::string rhs = CompileExp(exps[0]); + if (const auto dit = var_to_def_map_.find(v_ptr.get()); dit != var_to_def_map_.end() && dit->second->is_captured) { + if (const auto box_ptr = CompileUpvaluePointer(dit->second); box_ptr != "NULL") { + Out() << GenTab() << "FlStoreUpvalueBox(_S, " << box_ptr << ", " << rhs << ");\n"; + return; + } + } Out() << GenTab() << CompileVar(v_ptr) << " = " << rhs << ";\n"; // CONST_FLAG 由 init 内 SET_TABLE 创建时打上,不在赋值处注入 } @@ -2173,7 +2313,7 @@ void CGen::CompileTypedNumericForLoop(const std::shared_ptr & Out() << GenTab() << ctrl_var << " = " << cast_prefix << "(" << native_begin << ");\n"; const auto native_end = CompileNumericExp(for_stmt->ExpEnd()); if (float_end_to_int) { - const std::string step_expr = is_constant_step ? (std::to_string(step_int_val) + "LL") : step_var; + const std::string step_expr = is_constant_step ? FormatCInt64Literal(step_int_val) : step_var; if (!is_constant_step) { const auto native_step = CompileNumericExp(for_stmt->ExpStep()); Out() << GenTab() << step_var << " = " << native_step << ";\n"; @@ -2198,17 +2338,17 @@ void CGen::CompileTypedNumericForLoop(const std::shared_ptr & if (loop_type == T_INT) { Out() << GenTab() << stop_var << " = 0;\n"; if (step_int_val > 0) { - Out() << GenTab() << "for (; " << ctrl_var << " <= " << end_var << " && !" << stop_var << "; " << ctrl_var << " >= INT64_MAX - " << (step_int_val - 1) << "LL ? (" << stop_var - << " = 1) : (" << ctrl_var << " += " << step_int_val << "LL)) {\n"; + Out() << GenTab() << "for (; " << ctrl_var << " <= " << end_var << " && !" << stop_var << "; " << ctrl_var << " >= INT64_MAX - " << FormatCInt64Literal(step_int_val - 1) << " ? (" + << stop_var << " = 1) : (" << ctrl_var << " += " << FormatCInt64Literal(step_int_val) << ")) {\n"; } else { - Out() << GenTab() << "for (; " << ctrl_var << " >= " << end_var << " && !" << stop_var << "; " << ctrl_var << " <= INT64_MIN - (" << (step_int_val + 1) << "LL) ? (" << stop_var - << " = 1) : (" << ctrl_var << " += " << step_int_val << "LL)) {\n"; + Out() << GenTab() << "for (; " << ctrl_var << " >= " << end_var << " && !" << stop_var << "; " << ctrl_var << " <= (-9223372036854775807LL - 1LL) - (" + << FormatCInt64Literal(step_int_val + 1) << ") ? (" << stop_var << " = 1) : (" << ctrl_var << " += " << FormatCInt64Literal(step_int_val) << ")) {\n"; } } else if (step_double_val > 0.0) { - const std::string incr = (step_double_val == 1.0) ? (ctrl_var + "++") : (ctrl_var + " += " + std::to_string(step_double_val)); + const std::string incr = (step_double_val == 1.0) ? (ctrl_var + "++") : (ctrl_var + " += " + FormatCDoubleLiteral(step_double_val)); emit_float_for("!(" + end_var + " < " + ctrl_var + ")", incr + ", " + ctrl_var + " <= " + end_var); } else { - const std::string incr = (step_double_val == -1.0) ? (ctrl_var + "--") : (ctrl_var + " += " + std::to_string(step_double_val)); + const std::string incr = (step_double_val == -1.0) ? (ctrl_var + "--") : (ctrl_var + " += " + FormatCDoubleLiteral(step_double_val)); emit_float_for("!(" + ctrl_var + " < " + end_var + ")", incr + ", " + end_var + " <= " + ctrl_var); } } else if (!float_end_to_int) { @@ -2229,9 +2369,9 @@ void CGen::CompileTypedNumericForLoop(const std::shared_ptr & << " = !FlForIntAdvance(&" << ctrl_var << ", " << step_var << ")) {\n"; } cur_tab_++; - const auto loop_cname = CIdent(for_stmt->Name()); - if (IsCapturedInStmt(for_stmt.get(), for_stmt->Name())) { - EmitCapturedBoxDecl(for_stmt->Name(), BoxNativeValue(ctrl_var, loop_type)); + const auto loop_cname = DefSlotCIdent(for_stmt.get(), 0, for_stmt->Name()); + if (IsSlotCapturedInStmt(for_stmt.get(), 0, for_stmt->Name())) { + EmitCapturedBoxDecl(loop_cname, BoxNativeValue(ctrl_var, loop_type)); } else { const auto inferred = LookupNodeType(for_stmt.get()); // 循环变量被赋成非数值时快照是 T_DYNAMIC,必须发 CVar。 @@ -2336,9 +2476,9 @@ void CGen::CompileDynamicForLoop(const std::shared_ptr &for_s cur_tab_++; const auto &loop_var_name = for_stmt->Name(); - const auto loop_cname = CIdent(loop_var_name); - if (IsCapturedInStmt(for_stmt.get(), loop_var_name)) { - EmitCapturedBoxDecl(loop_var_name, ctrl_var); + const auto loop_cname = DefSlotCIdent(for_stmt.get(), 0, loop_var_name); + if (IsSlotCapturedInStmt(for_stmt.get(), 0, loop_var_name)) { + EmitCapturedBoxDecl(loop_cname, ctrl_var); } else { Out() << GenTab() << "CVar " << loop_cname << " = " << ctrl_var << ";\n"; } @@ -2439,11 +2579,12 @@ void CGen::CompileStmtForIn(const SyntaxTreeInterfacePtr &stmt) { DEBUG_ASSERT(explist->Type() == SyntaxTreeType::ExpList); const auto explist_ptr = std::dynamic_pointer_cast(explist); - auto HandleLoopVar = [&](const std::string &vname, const std::string &src_tmp) { - if (IsCapturedInStmt(for_in.get(), vname)) { - EmitCapturedBoxDecl(vname, src_tmp); + auto HandleLoopVar = [&](size_t slot, const std::string &vname, const std::string &src_tmp) { + const auto vcname = DefSlotCIdent(for_in.get(), slot, vname); + if (IsSlotCapturedInStmt(for_in.get(), slot, vname)) { + EmitCapturedBoxDecl(vcname, src_tmp); } else { - Out() << GenTab() << "CVar " << CIdent(vname) << " = " << src_tmp << ";\n"; + Out() << GenTab() << "CVar " << vcname << " = " << src_tmp << ";\n"; } }; @@ -2469,9 +2610,9 @@ void CGen::CompileStmtForIn(const SyntaxTreeInterfacePtr &stmt) { const auto tmp_k = std::format("flua_fi_k_{}", tmp_var_counter_++); Out() << GenTab() << "CVar " << tmp_k << " = (CVar){.type_ = VAR_INT, .data_.i = " << idx_var << "};\n"; - HandleLoopVar(names[0], tmp_k); + HandleLoopVar(0, names[0], tmp_k); if (names.size() >= 2) { - HandleLoopVar(names[1], tmp_v); + HandleLoopVar(1, names[1], tmp_v); } Out() << GenTab() << "{\n"; @@ -2517,9 +2658,9 @@ void CGen::CompileStmtForIn(const SyntaxTreeInterfacePtr &stmt) { Out() << GenTab() << std::format("if ({} == VAR_NIL) {{ continue; }}\n", dummy_val + ".type_"); } - HandleLoopVar(key_name, tmp_k); + HandleLoopVar(0, key_name, tmp_k); if (names.size() >= 2) { - HandleLoopVar(names[1], tmp_v); + HandleLoopVar(1, names[1], tmp_v); } Out() << GenTab() << "{\n"; @@ -2598,7 +2739,7 @@ void CGen::CompileStmtForIn(const SyntaxTreeInterfacePtr &stmt) { Out() << GenTab() << iter_var << " = " << loop_var_tmps[0] << ";\n"; for (size_t i = 0; i < names.size(); ++i) { - HandleLoopVar(names[i], loop_var_tmps[i]); + HandleLoopVar(i, names[i], loop_var_tmps[i]); } Out() << GenTab() << "{\n"; @@ -2635,16 +2776,13 @@ std::string CGen::CompileExp(const SyntaxTreeInterfacePtr &exp, bool preserve_mu return (cur_section_ == Section::Globals) ? "(CVar){.type_ = VAR_BOOL, .data_.b = false}" : "kFalse"; case ExpKind::kTrue: return (cur_section_ == Section::Globals) ? "(CVar){.type_ = VAR_BOOL, .data_.b = true}" : "kTrue"; - case ExpKind::kNumber: - // Number literal type is a purely syntactic property of the source text - // (integer vs float format). CompileExp is also called from global-init - // contexts where the snapshot may not cover this node, so we derive it - // directly from the literal rather than consulting the snapshot. - if (IsInteger(value)) { - return std::format("(CVar){{.type_ = VAR_INT, .data_.i = {}}}", ToInteger(value)); - } else { - return std::format("(CVar){{.type_ = VAR_FLOAT, .data_.f = {}}}", ToFloat(value)); + case ExpKind::kNumber: { + int64_t ival = 0; + if (TryParseLuaIntLiteral(value, ival)) { + return std::format("(CVar){{.type_ = VAR_INT, .data_.i = {}}}", FormatCInt64Literal(ival)); } + return std::format("(CVar){{.type_ = VAR_FLOAT, .data_.f = {}}}", FormatCDoubleLiteral(ToFloat(value))); + } case ExpKind::kString: return std::format("(CVar){{.type_ = VAR_STRINGID, .data_.i = {}}}", StringId(value)); case ExpKind::kPrefixExp: @@ -2709,7 +2847,8 @@ std::string CGen::CompilePrefixexp(const SyntaxTreeInterfacePtr &pe, bool preser } return std::format("FlUnboxMulti({}, 0)", call); } else /*if (pe_kind == PrefixExpKind::kExp)*/ { - return CompileExp(value, preserve_multi); + // Lua 语义:圆括号表达式 `(exp)` 始终截断为单个值。 + return CompileExp(value, false); } } @@ -2770,13 +2909,11 @@ std::string CGen::CompileTableconstructor(const SyntaxTreeInterfacePtr &tc) { break; } case TableKeyKind::kInt: { - int64_t int_val = std::stoll(key_info.repr, nullptr, 0); - Out() << GenTab() << std::format("FlSetTableInt({}, {}, {});\n", var_name, int_val, value_str); + Out() << GenTab() << std::format("FlSetTableInt({}, {}, {});\n", var_name, FormatCInt64Literal(key_info.int_value), value_str); break; } case TableKeyKind::kFloat: { - double float_val = std::stod(key_info.repr); - Out() << GenTab() << std::format("FlSetTable({}, (CVar){{.type_ = VAR_FLOAT, .data_.f = {}}}, {});\n", var_name, float_val, value_str); + Out() << GenTab() << std::format("FlSetTable({}, (CVar){{.type_ = VAR_FLOAT, .data_.f = {}}}, {});\n", var_name, FormatCDoubleLiteral(key_info.float_value), value_str); break; } case TableKeyKind::kBool: @@ -2992,6 +3129,20 @@ std::string CGen::CompileUnop(const SyntaxTreeInterfacePtr &exp, const SyntaxTre const auto op_ptr = std::dynamic_pointer_cast(op); const auto op_kind = op_ptr->GetOpKind(); const auto right = std::dynamic_pointer_cast(exp)->Right(); + + if (op_kind == UnOpKind::kMinus) { + TableKeyKind kind = TableKeyKind::kInt; + std::string canonical; + int64_t int_value = 0; + double float_value = 0; + if (ClassifyConstNumberExp(exp, kind, canonical, int_value, float_value)) { + if (ConstNumberExpIsIntValue(kind, exp)) { + return BoxNativeValue(FormatCInt64Literal(int_value), T_INT); + } + return BoxNativeValue(FormatCDoubleLiteral(ConstNumberExpToDouble(kind, int_value, float_value, exp)), T_FLOAT); + } + } + // Derive result type from the operand type via GetType (respects local scope, // unlike the snapshot which can be stale for degraded variables). const auto rt = GetType(right); @@ -3041,12 +3192,20 @@ std::string CGen::CompileNativeArithBinop(const SyntaxTreeInterfacePtr &left, co DEBUG_ASSERT(result_type == T_INT || result_type == T_FLOAT); - const auto native_expr = CompileRawNativeArithBinop(left, right, op_kind, result_type); - DEBUG_ASSERT(!native_expr.empty()); - const auto tmp = std::format("flua_op_{}", tmp_var_counter_++); - func_temp_decls_ << " CVar " << tmp << ";\n"; - Out() << GenTab() << tmp << " = " << BoxNativeValue(native_expr, result_type) << ";\n"; - return tmp; + CodegenSnapshot snap(*this); + try { + const auto native_expr = CompileRawNativeArithBinop(left, right, op_kind, result_type); + if (native_expr.empty()) { + return ""; + } + const auto tmp = std::format("flua_op_{}", tmp_var_counter_++); + func_temp_decls_ << " CVar " << tmp << ";\n"; + Out() << GenTab() << tmp << " = " << BoxNativeValue(native_expr, result_type) << ";\n"; + snap.Commit(); + return tmp; + } catch (...) { + return ""; + } } std::string CGen::CompileRawNativeArithBinop(const SyntaxTreeInterfacePtr &left, const SyntaxTreeInterfacePtr &right, BinOpKind op_kind, InferredType result_type) { @@ -3148,13 +3307,17 @@ std::string CGen::CompileNativeCmpBinop(const SyntaxTreeInterfacePtr &left, cons if (lt == T_INT || lt == T_FLOAT) { const auto rt = GetType(right); if (rt == T_INT || rt == T_FLOAT) { + CodegenSnapshot snap(*this); const auto left_native = TryCompileNativeExpr(left); - if (const auto right_native = TryCompileNativeExpr(right); !left_native.empty() && !right_native.empty()) { - const auto native_bool = FormatNativeNumericComparison(left_native, right_native, lt, rt, op_kind); - const auto tmp = std::format("flua_op_{}", tmp_var_counter_++); - func_temp_decls_ << " CVar " << tmp << ";\n"; - Out() << GenTab() << std::format("SET_BOOL({}, {});\n", tmp, native_bool); - return tmp; + if (!left_native.empty()) { + if (const auto right_native = TryCompileNativeExpr(right); !right_native.empty()) { + const auto native_bool = FormatNativeNumericComparison(left_native, right_native, lt, rt, op_kind); + const auto tmp = std::format("flua_op_{}", tmp_var_counter_++); + func_temp_decls_ << " CVar " << tmp << ";\n"; + Out() << GenTab() << std::format("SET_BOOL({}, {});\n", tmp, native_bool); + snap.Commit(); + return tmp; + } } } } @@ -3165,12 +3328,18 @@ std::string CGen::CompileNativeCmpBinop(const SyntaxTreeInterfacePtr &left, cons std::string CGen::CompileNativeUnop(const SyntaxTreeInterfacePtr &right, UnOpKind op_kind, InferredType result_type) { if (op_kind == UnOpKind::kMinus || op_kind == UnOpKind::kBitNot) { if (result_type == T_INT || result_type == T_FLOAT) { - if (const auto native_operand = TryCompileNativeExpr(right); !native_operand.empty()) { + CodegenSnapshot snap(*this); + try { const auto native_expr = CompileRawNativeUnop(right, op_kind, result_type); - const auto tmp = std::format("flua_op_{}", tmp_var_counter_++); - func_temp_decls_ << " CVar " << tmp << ";\n"; - Out() << GenTab() << tmp << " = " << BoxNativeValue(native_expr, result_type) << ";\n"; - return tmp; + if (!native_expr.empty()) { + const auto tmp = std::format("flua_op_{}", tmp_var_counter_++); + func_temp_decls_ << " CVar " << tmp << ";\n"; + Out() << GenTab() << tmp << " = " << BoxNativeValue(native_expr, result_type) << ";\n"; + snap.Commit(); + return tmp; + } + } catch (...) { + return ""; } } } @@ -3225,15 +3394,8 @@ std::string CGen::CompileVar(const SyntaxTreeInterfacePtr &v) { if (const auto it = var_to_def_map_.find(v_ptr.get()); it != var_to_def_map_.end()) { VarDef *def = it->second; if (def->is_captured) { - if (def->defining_func == cur_func_info_) { - return "(*__box_" + CIdent(name) + ")"; - } - if (cur_func_info_) { - const auto vit = std::ranges::find(cur_func_info_->captured_vars, def); - if (vit != cur_func_info_->captured_vars.end()) { - int idx = static_cast(vit - cur_func_info_->captured_vars.begin()); - return std::format("(*_CL->upvalues[{}])", idx); - } + if (const auto box_ptr = CompileUpvaluePointer(def); box_ptr != "NULL") { + return std::format("FlLoadUpvalueBox({})", box_ptr); } } } @@ -3248,16 +3410,18 @@ std::string CGen::CompileVar(const SyntaxTreeInterfacePtr &v) { // 3. Regular native variable checking if (const auto native_type = GetNativeVarType(name, v_ptr.get()); native_type != T_DYNAMIC) { - return BoxNativeValue(CIdent(name), native_type); + return BoxNativeValue(VarCIdent(v_ptr.get()), native_type); } // 文件级数值常量(static const int64_t / double):装箱为 CVar 后返回。 - if (const auto git = ir().global_const_vars.find(name); git != ir().global_const_vars.end()) { - if (git->second == T_INT || git->second == T_FLOAT) { - return BoxNativeValue(CIdent(name), git->second); + if (!BindsLocalValue(v_ptr.get())) { + if (const auto git = ir().global_const_vars.find(name); git != ir().global_const_vars.end()) { + if (git->second == T_INT || git->second == T_FLOAT) { + return BoxNativeValue(FileCIdent(name), git->second); + } } } // 拦截 _VERSION 全局常量(编译期替换为 "Fakelua x.y.z") - if (name == "_VERSION") { + if (!BindsLocalValue(v_ptr.get()) && name == "_VERSION") { std::string ver = std::string("Fakelua ") + FAKELUA_VERSION_STRING; return std::format("(CVar){{.type_ = VAR_STRINGID, .data_.i = {}}}", StringId(ver)); } @@ -3266,11 +3430,11 @@ std::string CGen::CompileVar(const SyntaxTreeInterfacePtr &v) { // 若直接输出 raw name,当 name 恰好是 C 标准库符号(如 fmod、sin、cos、time 等)时, // C 编译器会把它解析为 C 函数指针,作为 CVar 传参时引发类型混淆甚至 crash; // 当 name 不是任何 C 符号时则会引起 C 语法/编译错误。 - if (!var_to_def_map_.contains(v_ptr.get()) && !ir().global_const_vars.contains(name) && !global_const_table_vars_.contains(name)) { + if (!var_to_def_map_.contains(v_ptr.get()) && !ir().global_const_vars.contains(name) && !global_const_table_vars_.contains(FileCIdent(name)) && !global_const_table_vars_.contains(name)) { return (cur_section_ == Section::Globals) ? "(CVar){.type_ = VAR_NIL}" : "kNil"; } - return CIdent(name); + return VarCIdent(v_ptr.get()); } else if (var_kind == VarKind::kSquare) { DEBUG_ASSERT(cur_section_ != Section::Globals); const auto pe = v_ptr->GetPrefixexp(); @@ -3292,9 +3456,9 @@ std::string CGen::CompileVar(const SyntaxTreeInterfacePtr &v) { return std::format("FlGetTableStrId({}, {})", pe_ret, id); } case TableKeyKind::kInt: - return std::format("FlGetTableInt({}, {})", pe_ret, info.repr); + return std::format("FlGetTableInt({}, {})", pe_ret, FormatCInt64Literal(info.int_value)); case TableKeyKind::kFloat: - return std::format("FlGetTable({}, (CVar){{.type_ = VAR_FLOAT, .data_.f = {}}})", pe_ret, info.repr); + return std::format("FlGetTable({}, (CVar){{.type_ = VAR_FLOAT, .data_.f = {}}})", pe_ret, FormatCDoubleLiteral(info.float_value)); case TableKeyKind::kBool: return std::format("FlGetTable({}, {})", pe_ret, info.repr == "true" ? "kTrue" : "kFalse"); } @@ -3318,7 +3482,7 @@ std::string CGen::CompileVar(const SyntaxTreeInterfacePtr &v) { if (pe && pe->Type() == SyntaxTreeType::PrefixExp) { if (const auto pe_ptr = std::dynamic_pointer_cast(pe); pe_ptr && pe_ptr->GetPrefixKind() == PrefixExpKind::kVar) { const auto base_var = std::dynamic_pointer_cast(pe_ptr->GetValue()); - if (base_var && base_var->GetVarKind() == VarKind::kSimple) { + if (base_var && base_var->GetVarKind() == VarKind::kSimple && !var_to_def_map_.contains(base_var.get())) { // 拦截 math 静态库常量访问 (math.pi / math.huge / math.maxinteger / math.mininteger) if (base_var->GetName() == "math") { if (name == "pi") { @@ -3418,18 +3582,19 @@ std::string CGen::CompileNumericExp(const SyntaxTreeInterfacePtr &exp) { double float_value = 0; if (ClassifyConstNumberExp(exp, kind, canonical, int_value, float_value)) { if (ConstNumberExpIsIntValue(kind, exp)) { - return std::to_string(int_value); + return FormatCInt64Literal(int_value); } return FormatCDoubleLiteral(ConstNumberExpToDouble(kind, int_value, float_value, exp)); } } if (const auto exp_kind = e->GetExpKind(); exp_kind == ExpKind::kNumber) { - if (LookupNodeType(e.get()) == T_INT) { - return std::to_string(ToInteger(e->ExpValue())); + int64_t ival = 0; + if (LookupNodeType(e.get()) == T_INT && TryParseLuaIntLiteral(e->ExpValue(), ival)) { + return FormatCInt64Literal(ival); } if (LookupNodeType(e.get()) == T_FLOAT) { - return std::format("{}", ToFloat(e->ExpValue())); + return FormatCDoubleLiteral(ToFloat(e->ExpValue())); } ThrowSpecMiss("number node is not inferred as numeric", exp); } else if (exp_kind == ExpKind::kPrefixExp) { @@ -3437,25 +3602,32 @@ std::string CGen::CompileNumericExp(const SyntaxTreeInterfacePtr &exp) { DEBUG_ASSERT(pe); if (pe->GetPrefixKind() == PrefixExpKind::kVar) { const auto var = std::dynamic_pointer_cast(pe->GetValue()); - DEBUG_ASSERT(var && var->GetVarKind() == VarKind::kSimple); + if (!var || var->GetVarKind() != VarKind::kSimple) { + ThrowSpecMiss("table access cannot be unboxed directly as numeric", exp); + } const auto &vname = var->GetName(); if (IsTypedNativeVar(vname, var.get())) { - return CIdent(vname); + return VarCIdent(var.get()); } // 文件级数值常量(static const int64_t / double):直接用名称。 - if (const auto git = ir().global_const_vars.find(vname); git != ir().global_const_vars.end()) { - if (git->second == T_INT || git->second == T_FLOAT) { - return CIdent(vname); + if (!BindsLocalValue(var.get())) { + if (const auto git = ir().global_const_vars.find(vname); git != ir().global_const_vars.end()) { + if (git->second == T_INT || git->second == T_FLOAT) { + return FileCIdent(vname); + } } } - std::string cvar_expr = CIdent(vname); + std::string cvar_expr = VarCIdent(var.get()); if (const auto it = var_to_def_map_.find(var.get()); it != var_to_def_map_.end() && it->second->is_captured) { ThrowSpecMiss("captured variable cannot be unboxed directly as numeric", exp); } if (LookupNodeType(e.get()) == T_FLOAT) { return std::format("{}.data_.f", cvar_expr); } - return std::format("{}.data_.i", cvar_expr); + if (LookupNodeType(e.get()) == T_INT) { + return std::format("{}.data_.i", cvar_expr); + } + ThrowSpecMiss("variable is not specialized as numeric", exp); } if (pe->GetPrefixKind() == PrefixExpKind::kExp) { return CompileNumericExp(pe->GetValue()); @@ -3476,9 +3648,9 @@ std::string CGen::CompileNumericExp(const SyntaxTreeInterfacePtr &exp) { const auto op_kind = op->GetOpKind(); if (op_kind == BinOpKind::kAnd) { - // Numeric values are always truthy in Lua, so `a and b` = b. - // Evaluate a for side effects only (e.g. function-call statements - // already emitted by CompileNumericExp); the result is discarded. + if (!IsNumericInferredType(GetType(e->Left())) || !IsNumericInferredType(GetType(e->Right()))) { + ThrowSpecMiss("and operand is not numeric", exp); + } CompileNumericExp(e->Left()); return CompileNumericExp(e->Right()); } @@ -3491,11 +3663,14 @@ std::string CGen::CompileNumericExp(const SyntaxTreeInterfacePtr &exp) { const auto val1 = left_exp->Right(); const auto val2 = e->Right(); + const auto result_type = LookupNodeType(e.get()); + if ((result_type != T_INT && result_type != T_FLOAT) || !IsNumericInferredType(GetType(val1)) || !IsNumericInferredType(GetType(val2))) { + ThrowSpecMiss("ternary branch is not numeric", exp); + } + const auto cond_bool = TryCompileNativeBoolExpr(cond); const auto cond_str = !cond_bool.empty() ? std::format("({})", cond_bool) : std::format("FlIsTrue({})", CompileExp(cond)); - const auto result_type = LookupNodeType(e.get()); - DEBUG_ASSERT(result_type == T_INT || result_type == T_FLOAT); const auto result_tmp = std::format("flua_ternary_{}", tmp_var_counter_++); func_temp_decls_ << " " << SpecReturnCTypeName(result_type) << " " << result_tmp << ";\n"; Out() << GenTab() << "if (" << cond_str << ") {\n"; @@ -3513,6 +3688,9 @@ std::string CGen::CompileNumericExp(const SyntaxTreeInterfacePtr &exp) { } } } + if (!IsNumericInferredType(GetType(e->Left())) || !IsNumericInferredType(GetType(e->Right()))) { + ThrowSpecMiss("or operand is not numeric", exp); + } return CompileNumericExp(e->Left()); } @@ -3588,38 +3766,55 @@ std::string CGen::TryCompileNativeSpecCallExpr(const SyntaxTreeInterfacePtr &fun return {}; } const auto &callee_name = callee_var->GetName(); + const auto fn_it = local_func_names_.find(callee_name); + if (fn_it == local_func_names_.end() || fn_it->second.is_vararg) { + return {}; + } if (!ir().math_param_positions.contains(callee_name)) { return {}; } const auto explist_ptr = std::dynamic_pointer_cast(args_ptr->Explist()); DEBUG_ASSERT(explist_ptr); const auto &raw_args = explist_ptr->Exps(); + if (static_cast(raw_args.size()) != fn_it->second.params_count) { + return {}; + } + if (!raw_args.empty()) { + const bool last_is_func = ar().function_call_exps.contains(raw_args.back().get()); + const std::string last_callee = (last_is_func && ar().callee_names.contains(raw_args.back().get())) ? ar().callee_names.at(raw_args.back().get()) : ""; + const bool is_last_single_return = !last_callee.empty() && ar().function_max_returns.contains(last_callee) && ar().function_max_returns.at(last_callee) == 1; + if ((last_is_func && !is_last_single_return) || IsVarargExp(raw_args.back())) { + return {}; + } + } int bitmask = 0; - InferredType spec_ret = T_DYNAMIC; - [[maybe_unused]] bool ok = TryInferMathCallSpec(callee_name, raw_args, bitmask, spec_ret); - DEBUG_ASSERT(ok); - DEBUG_ASSERT(spec_ret == T_INT || spec_ret == T_FLOAT); + if (!TryInferMathCallBitmask(callee_name, raw_args, bitmask)) { + return {}; + } + const InferredType spec_ret = GetSpecReturnType(callee_name, bitmask); + if (spec_ret != T_INT && spec_ret != T_FLOAT) { + return {}; + } const auto &math_params = ir().math_param_positions.at(callee_name); + const std::unordered_set math_param_set(math_params.begin(), math_params.end()); - std::unordered_map native_exprs; - for (int param_pos: math_params) { - const auto native_expr = TryCompileNativeExpr(raw_args[param_pos]); - DEBUG_ASSERT(!native_expr.empty()); - native_exprs[param_pos] = native_expr; - } - + CodegenSnapshot snap(*this); const auto spec_name = SpecFuncName(LookupFuncCName(callee_name), math_params, bitmask); std::string call = spec_name + "("; for (int i = 0; i < static_cast(raw_args.size()); ++i) { if (i > 0) { call += ", "; } - if (const auto ne_it = native_exprs.find(i); ne_it != native_exprs.end()) { - call += ne_it->second; + if (math_param_set.contains(i)) { + const auto native_expr = TryCompileNativeExpr(raw_args[static_cast(i)]); + if (native_expr.empty()) { + return {}; + } + call += native_expr; } else { - call += CompileExp(raw_args[i]); + call += CompileExp(raw_args[static_cast(i)]); } } call += ")"; @@ -3627,6 +3822,7 @@ std::string CGen::TryCompileNativeSpecCallExpr(const SyntaxTreeInterfacePtr &fun const auto ntmp = std::format("flua_native_{}", tmp_var_counter_++); func_temp_decls_ << " " << SpecReturnCTypeName(spec_ret) << " " << ntmp << ";\n"; Out() << GenTab() << ntmp << " = " << call << ";\n"; + snap.Commit(); return ntmp; } @@ -3783,6 +3979,12 @@ std::string CGen::TryCompileBuiltinMathCall(const std::shared_ptrsecond.is_vararg) { return ""; } if (const auto math_it = ir().math_param_positions.find(callee_name); math_it != ir().math_param_positions.end()) { @@ -4469,25 +4674,32 @@ std::string CGen::TryCompileSpecDirectCall(const std::shared_ptr(raw_args.size()) != fn_it->second.params_count) { return ""; } - - if (int bitmask = 0; TryInferMathCallBitmask(callee_name, raw_args, bitmask)) { - std::unordered_map native_exprs; - for (int param_pos: math_params) { - const auto native_expr = TryCompileNativeExpr(raw_args[param_pos]); - DEBUG_ASSERT(!native_expr.empty()); - native_exprs[param_pos] = native_expr; + if (!raw_args.empty()) { + const bool last_is_func = ar().function_call_exps.contains(raw_args.back().get()); + const std::string last_callee = (last_is_func && ar().callee_names.contains(raw_args.back().get())) ? ar().callee_names.at(raw_args.back().get()) : ""; + const bool is_last_single_return = !last_callee.empty() && ar().function_max_returns.contains(last_callee) && ar().function_max_returns.at(last_callee) == 1; + if ((last_is_func && !is_last_single_return) || IsVarargExp(raw_args.back())) { + return ""; } + } + if (int bitmask = 0; TryInferMathCallBitmask(callee_name, raw_args, bitmask)) { + const std::unordered_set math_param_set(math_params.begin(), math_params.end()); + CodegenSnapshot snap(*this); const auto spec_name = SpecFuncName(LookupFuncCName(callee_name), math_params, bitmask); std::string call = spec_name + "("; for (int i = 0; i < static_cast(raw_args.size()); ++i) { if (i > 0) { call += ", "; } - if (const auto ne_it = native_exprs.find(i); ne_it != native_exprs.end()) { - call += ne_it->second; + if (math_param_set.contains(i)) { + const auto native_expr = TryCompileNativeExpr(raw_args[static_cast(i)]); + if (native_expr.empty()) { + return ""; + } + call += native_expr; } else { - call += CompileExp(raw_args[i]); + call += CompileExp(raw_args[static_cast(i)]); } } call += ")"; @@ -4504,6 +4716,7 @@ std::string CGen::TryCompileSpecDirectCall(const std::shared_ptrExplist(); const auto explist_arg_ptr = std::dynamic_pointer_cast(explist_arg); const auto &raw_args = explist_arg_ptr->Exps(); + if (!raw_args.empty() && (IsFunctionCallExp(raw_args.back()) || IsVarargExp(raw_args.back()))) { + return {}; + } + + // 避免未命中分支在 func_temp_decls_ 留下悬空声明 + if (method_name != "char" && method_name != "lower" && method_name != "upper" && method_name != "byte" && method_name != "format" && method_name != "len" && method_name != "rep" && + method_name != "reverse" && method_name != "find") { + return {}; + } const auto tmp = std::format("flua_call_{}", tmp_var_counter_++); func_temp_decls_ << " CVar " << tmp << ";\n"; @@ -4831,18 +5053,15 @@ std::string CGen::TryCompileBuiltinBasicCall(const std::shared_ptr(raw_args[0]); idx_exp && idx_exp->GetExpKind() == ExpKind::kString && idx_exp->ExpValue() == "#") { const std::string vararg = CompileExp(raw_args[1], /*preserve_multi=*/true); Out() << GenTab() << tmp << " = FlSelectHash(" << vararg << ");\n"; return tmp; } - // select(i, ...) —— i 为 INT 时直接取首个元素(表达式上下文) const std::string idx_c = CompileExp(raw_args[0]); const std::string vararg = CompileExp(raw_args[1], /*preserve_multi=*/true); const auto idx_tmp = std::format("flua_sel_i_{}", tmp_var_counter_++); @@ -4859,6 +5078,10 @@ std::string CGen::TryCompileBuiltinBasicCall(const std::shared_ptrspec_keys[{}] = (CVar){{.type_ = VAR_INT, .data_.i = {}}};\n", tbl_str, index, info.repr); + Out() << GenTab() << std::format("{}.data_.t->spec_keys[{}] = (CVar){{.type_ = VAR_INT, .data_.i = {}}};\n", tbl_str, index, int_key_c); break; case TableKeyKind::kFloat: - Out() << GenTab() << std::format("{}.data_.t->spec_keys[{}] = (CVar){{.type_ = VAR_FLOAT, .data_.f = {}}};\n", tbl_str, index, info.repr); + Out() << GenTab() << std::format("{}.data_.t->spec_keys[{}] = (CVar){{.type_ = VAR_FLOAT, .data_.f = {}}};\n", tbl_str, index, float_key_c); break; case TableKeyKind::kBool: Out() << GenTab() << std::format("{}.data_.t->spec_keys[{}] = {};\n", tbl_str, index, info.repr == "true" ? "kTrue" : "kFalse"); @@ -4948,6 +5175,7 @@ std::string CGen::TryCompileSetTableCall(const std::shared_ptr(raw_args[2])) { if (val_exp->GetExpKind() == ExpKind::kTrue) { - Out() << GenTab() << std::format("FlSetTableInt_Bool({}, {}, true);\n", tbl_str, info.repr); + Out() << GenTab() << std::format("FlSetTableInt_Bool({}, {}, true);\n", tbl_str, int_key_c); break; } if (val_exp->GetExpKind() == ExpKind::kFalse) { - Out() << GenTab() << std::format("FlSetTableInt_Bool({}, {}, false);\n", tbl_str, info.repr); + Out() << GenTab() << std::format("FlSetTableInt_Bool({}, {}, false);\n", tbl_str, int_key_c); break; } } - Out() << GenTab() << std::format("FlSetTableInt({}, {}, {});\n", tbl_str, info.repr, val_str); + const auto val_str = CompileExp(raw_args[2]); + Out() << GenTab() << std::format("FlSetTableInt({}, {}, {});\n", tbl_str, int_key_c, val_str); break; } - case TableKeyKind::kFloat: - Out() << GenTab() << std::format("FlSetTable({}, (CVar){{.type_ = VAR_FLOAT, .data_.f = {}}}, {});\n", tbl_str, info.repr, val_str); + case TableKeyKind::kFloat: { + const auto val_str = CompileExp(raw_args[2]); + Out() << GenTab() << std::format("FlSetTable({}, (CVar){{.type_ = VAR_FLOAT, .data_.f = {}}}, {});\n", tbl_str, float_key_c, val_str); break; - case TableKeyKind::kBool: + } + case TableKeyKind::kBool: { + const auto val_str = CompileExp(raw_args[2]); Out() << GenTab() << std::format("FlSetTable({}, (CVar){{.type_ = VAR_BOOL, .data_.b = {}}}, {});\n", tbl_str, info.repr == "true" ? "true" : "false", val_str); break; + } } } Out() << GenTab() << std::format("SET_NIL({});\n", tmp); @@ -4991,7 +5224,6 @@ std::string CGen::TryCompileSetTableCall(const std::shared_ptr def->def_node = def_node; def->defining_func = cur_func; def->is_captured = false; + if (cur_func != nullptr) { + def->c_ident = AllocFuncVarCIdent(cur_func, name); + } VarDef *ptr = def.get(); scopes.back().vars[name] = ptr; all_defs_.push_back(std::move(def)); stmt_var_to_def_[{def_node, name}] = ptr; + stmt_defs_[def_node].push_back(ptr); }; switch (node->Type()) { @@ -5385,10 +5620,12 @@ void CGen::ResolveScopes(const SyntaxTreeInterfacePtr &node, std::vector def->name = pname; def->def_node = parlist.get(); def->defining_func = pf; + def->c_ident = AllocFuncVarCIdent(pf, pname); VarDef *ptr = def.get(); all_defs_.push_back(std::move(def)); scopes.back().vars[pname] = ptr; stmt_var_to_def_[{parlist.get(), pname}] = ptr; + stmt_defs_[parlist.get()].push_back(ptr); } } } @@ -5489,9 +5726,20 @@ void CGen::ResolveScopes(const SyntaxTreeInterfacePtr &node, std::vector break; } case SyntaxTreeType::Repeat: { + // Lua:until 条件可见 repeat 块内声明的 local。不能走 Block 的 + // Enter/Exit,否则 until 里的名字会掉出作用域。 const auto rep = std::dynamic_pointer_cast(node); - ResolveScopes(rep->Block(), scopes, func_stack, cur_func); + EnterScope(); + if (rep->Block() && rep->Block()->Type() == SyntaxTreeType::Block) { + const auto block = std::dynamic_pointer_cast(rep->Block()); + for (const auto &stmt: block->Stmts()) { + ResolveScopes(stmt, scopes, func_stack, cur_func); + } + } else { + ResolveScopes(rep->Block(), scopes, func_stack, cur_func); + } ResolveScopes(rep->Exp(), scopes, func_stack, cur_func); + ExitScope(); break; } case SyntaxTreeType::If: { @@ -5527,7 +5775,7 @@ void CGen::ResolveScopes(const SyntaxTreeInterfacePtr &node, std::vector std::string CGen::CompileUpvaluePointer(VarDef *def) { if (def->defining_func == cur_func_info_) { - return "__box_" + CIdent(def->name); + return "__box_" + (def->c_ident.empty() ? CIdent(def->name) : def->c_ident); } else { if (cur_func_info_) { const auto vit = std::ranges::find(cur_func_info_->captured_vars, def); @@ -5561,11 +5809,19 @@ bool CGen::IsCapturedInStmt(const SyntaxTreeInterface *stmt_ptr, const std::stri return false; } -void CGen::EmitCapturedBoxDecl(const std::string &name, const std::string &init_expr) { - const auto cn = CIdent(name); - Out() << GenTab() << "CVar *__box_" << cn << " = (CVar *)FlFastAlloc(_S, sizeof(CVar), !__fakelua_init_flag__);\n"; +bool CGen::IsSlotCapturedInStmt(const SyntaxTreeInterface *stmt_ptr, size_t slot, const std::string &name) const { + if (stmt_ptr != nullptr) { + if (const auto it = stmt_defs_.find(stmt_ptr); it != stmt_defs_.end() && slot < it->second.size()) { + return it->second[slot]->is_captured; + } + } + return IsCapturedInStmt(stmt_ptr, name); +} + +void CGen::EmitCapturedBoxDecl(const std::string &c_ident, const std::string &init_expr) { + Out() << GenTab() << "CVar *__box_" << c_ident << " = FlAllocUpvalueBox(_S, FL_IN_CONST_INIT);\n"; if (!init_expr.empty()) { - Out() << GenTab() << "*__box_" << cn << " = " << init_expr << ";\n"; + Out() << GenTab() << "FlStoreUpvalueBox(_S, __box_" << c_ident << ", " << init_expr << ");\n"; } } @@ -5590,10 +5846,11 @@ void CGen::CompileStmtLocalFunction(const SyntaxTreeInterfacePtr &stmt) { closure_expr += ")"; } - if (IsCapturedInStmt(lf.get(), name)) { - EmitCapturedBoxDecl(name, closure_expr); + const auto lfcname = DefSlotCIdent(lf.get(), 0, name); + if (IsSlotCapturedInStmt(lf.get(), 0, name)) { + EmitCapturedBoxDecl(lfcname, closure_expr); } else { - Out() << GenTab() << "CVar " << CIdent(name) << " = " << closure_expr << ";\n"; + Out() << GenTab() << "CVar " << lfcname << " = " << closure_expr << ";\n"; } } diff --git a/src/compile/c_gen.h b/src/compile/c_gen.h index 6d6e2602..d7a88268 100644 --- a/src/compile/c_gen.h +++ b/src/compile/c_gen.h @@ -42,9 +42,44 @@ class CGen { } }; - // ========================================== - // 第一部分:核心调度与编排 - // ========================================== + // RAII 快照:在试探性编译(TryCompileNative* / TryCompileSpec*)失败或抛 SpecMiss 时, + // 完整回滚当前输出段、函数头临时声明、缩进层级与临时计数器,防止半截语句泄漏。 + struct CodegenSnapshot { + CGen &gen; + Section sec; + std::string out_str; + std::string temp_decls_str; + int cur_tab; + int tmp_counter; + bool committed = false; + + explicit CodegenSnapshot(CGen &g) + : gen(g), sec(g.cur_section_), out_str(g.sections_[static_cast(g.cur_section_)].str()), temp_decls_str(g.func_temp_decls_.str()), cur_tab(g.cur_tab_), + tmp_counter(g.tmp_var_counter_) { + } + + void Commit() { + committed = true; + } + + void Restore() { + auto &ss = gen.sections_[static_cast(sec)]; + ss.str(out_str); + ss.clear(); + ss.seekp(0, std::ios::end); + gen.func_temp_decls_.str(temp_decls_str); + gen.func_temp_decls_.clear(); + gen.func_temp_decls_.seekp(0, std::ios::end); + gen.cur_tab_ = cur_tab; + gen.tmp_var_counter_ = tmp_counter; + } + + ~CodegenSnapshot() { + if (!committed) { + Restore(); + } + } + }; // 核心构建主流程:根据 AST 和编译配置构建出最终的 C 语言源码字符串 GenResult Build(const ParseResult &pr, const CompileConfig &cfg); // 为一个 spec 类型发射 typedef + 特化 get/set 函数到 Headers section。 @@ -193,6 +228,8 @@ class CGen { // 表达式(每轮读取 C 变量/字面量即重新求值)。判定口径必须与 CompileNumericExp、 // CompileRawNativeArithBinop、CompileRawNativeUnop 的语句发射点严格一致。 [[nodiscard]] bool IsPureNativeNumericExp(const SyntaxTreeInterfacePtr &exp) const; + // 纯 AST 查询:判断布尔条件能否编译为无副作用、不抛错的纯原生比较/取反表达式(不向 Out() 写任何内容)。 + [[nodiscard]] bool IsPureNativeBoolExp(const SyntaxTreeInterfacePtr &exp) const; // 尝试对强类型数学特化库调用(如 math.sin, math.cos)进行原生直接映射优化 std::string TryCompileNativeSpecCallExpr(const SyntaxTreeInterfacePtr &functioncall_node); @@ -220,17 +257,23 @@ class CGen { // 检查变量是否为已知强类型的原生变量 [[nodiscard]] bool IsTypedNativeVar(const std::string &name, const SyntaxTreeInterface *var_node) const { if (const auto it = var_to_def_map_.find(var_node); it != var_to_def_map_.end()) { - if (it->second->is_captured) { + const VarDef *def = it->second; + if (def->is_captured) { return false; } - } - // 1. 检查是否为特化函数参数,且参数类型为原生数值类型 - if (cur_spec_ctx_) { - if (const auto it = cur_spec_ctx_->param_types.find(name); it != cur_spec_ctx_->param_types.end()) { - return it->second == T_INT || it->second == T_FLOAT; + if (def->defining_func == cur_func_info_ && def->def_node && def->def_node->Type() == SyntaxTreeType::ParList) { + if (cur_spec_ctx_) { + if (const auto pit = cur_spec_ctx_->param_types.find(name); pit != cur_spec_ctx_->param_types.end()) { + return pit->second == T_INT || pit->second == T_FLOAT; + } + } + return false; + } + } else if (cur_spec_ctx_) { + if (const auto pit = cur_spec_ctx_->param_types.find(name); pit != cur_spec_ctx_->param_types.end()) { + return pit->second == T_INT || pit->second == T_FLOAT; } } - // 2. 检查变量引用是否有定义节点映射,且该定义节点最终推断为原生数值类型 if (const auto it = ir().var_define_nodes.find(var_node); it != ir().var_define_nodes.end()) { const auto def_type = LookupNodeType(const_cast(it->second)); return def_type == T_INT || def_type == T_FLOAT; @@ -241,13 +284,21 @@ class CGen { // 获取原生强类型变量在作用域中的推断类型 [[nodiscard]] InferredType GetNativeVarType(const std::string &name, const SyntaxTreeInterface *var_node) const { if (const auto it = var_to_def_map_.find(var_node); it != var_to_def_map_.end()) { - if (it->second->is_captured) { + const VarDef *def = it->second; + if (def->is_captured) { return T_DYNAMIC; } - } - if (cur_spec_ctx_) { - if (const auto it = cur_spec_ctx_->param_types.find(name); it != cur_spec_ctx_->param_types.end()) { - return it->second; + if (def->defining_func == cur_func_info_ && def->def_node && def->def_node->Type() == SyntaxTreeType::ParList) { + if (cur_spec_ctx_) { + if (const auto pit = cur_spec_ctx_->param_types.find(name); pit != cur_spec_ctx_->param_types.end()) { + return pit->second; + } + } + return T_DYNAMIC; + } + } else if (cur_spec_ctx_) { + if (const auto pit = cur_spec_ctx_->param_types.find(name); pit != cur_spec_ctx_->param_types.end()) { + return pit->second; } } if (const auto it = ir().var_define_nodes.find(var_node); it != ir().var_define_nodes.end()) { @@ -329,6 +380,7 @@ class CGen { struct VarDef { std::string name; + std::string c_ident; const SyntaxTreeInterface *def_node = nullptr;// local stmt, parameter list, or loop stmt FuncInfo *defining_func = nullptr; bool is_captured = false; @@ -368,6 +420,7 @@ class CGen { }; std::unordered_map, VarDef *, PairHash> stmt_var_to_def_; + std::unordered_map> stmt_defs_; std::unordered_map var_to_def_map_; FuncInfo *cur_func_info_ = nullptr; // The function currently being compiled @@ -382,6 +435,10 @@ class CGen { std::unordered_set file_c_ident_used_; std::string CIdent(const std::string &lua_name); + std::string FileCIdent(const std::string &lua_name); + std::string AllocFuncVarCIdent(FuncInfo *func, const std::string &lua_name); + std::string DefSlotCIdent(const SyntaxTreeInterface *stmt_ptr, size_t slot, const std::string &fallback_name); + std::string VarCIdent(const SyntaxTreeVar *var_ptr); std::vector CIdents(const std::vector &names); void UniquifyFuncCNames(); [[nodiscard]] bool IsFuncLocalName(const std::string &lua_name) const; @@ -395,16 +452,17 @@ class CGen { // 查询 name 在 stmt_ptr 对应语句节点上是否被标记为 captured [[nodiscard]] bool IsCapturedInStmt(const SyntaxTreeInterface *stmt_ptr, const std::string &name) const; + [[nodiscard]] bool IsSlotCapturedInStmt(const SyntaxTreeInterface *stmt_ptr, size_t slot, const std::string &name) const; // 变量引用的是形参、局部变量或嵌套 local function。 // 文件级 local function 不算:它的 C 变量只存在于 init,其它函数仍按文件级符号调用。 [[nodiscard]] bool BindsLocalValue(const SyntaxTreeVar *var) const; // 发射 heap-boxed captured var 声明: - // CVar *__box_ = (CVar *)FakeluaAlloc(_S, sizeof(CVar), false); - // *__box_ = ; + // CVar *__box_ = (CVar *)FlFastAlloc(_S, sizeof(CVar), FL_IN_CONST_INIT); + // *__box_ = ; // init_expr 为空字符串时省略第二行(仅 alloc box) - void EmitCapturedBoxDecl(const std::string &name, const std::string &init_expr); + void EmitCapturedBoxDecl(const std::string &c_ident, const std::string &init_expr); // 向当前输出流发射特化函数的参数类型+名称列表。 // 遍历 params,对命中 math_params 的参数输出原生类型,其余输出 CVar。 @@ -423,6 +481,8 @@ class CGen { // - kInt: 十进制整数字符串 // - kFloat: 浮点数字符串 // - kBool: "true" 或 "false" + int64_t int_value = 0; + double float_value = 0.0; }; // 若 exp 是可静态分类的字面量 key,填充 out 并返回 true;否则返回 false。 diff --git a/src/compile/c_runtime_cov.h b/src/compile/c_runtime_cov.h index b4df548f..4ea985f4 100644 --- a/src/compile/c_runtime_cov.h +++ b/src/compile/c_runtime_cov.h @@ -110,16 +110,20 @@ enum { // __fakelua_init_flag__:false=仍在 __fakelua_init(可填充 const 表);true=init 已结束。 // init 期间 NEWTABLE/SET_TABLE 创建的表直接打 CONST_FLAG(整棵树,含嵌套); // SETTABLE 仅在 init 结束后才因 CONST_FLAG 抛错,以便构造器写字段。 +static const bool fl_const_alloc_false = false; +static const bool *fl_const_alloc = &fl_const_alloc_false; +#define FL_IN_CONST_INIT (!__fakelua_init_flag__ || *fl_const_alloc) + #define CONST_FLAG 0x1 #define FL_CHECK_CONST_TABLE(t) \ do { \ - if (UNLIKELY(((t).flag_ & CONST_FLAG) && __fakelua_init_flag__)) { \ + if (UNLIKELY(((t).flag_ & CONST_FLAG) && !FL_IN_CONST_INIT)) { \ FL_RAISE(_S, "attempt to modify a const table"); \ } \ } while (0) #define FL_CHECK_CONST_TABLE_HINT(t) \ do { \ - if (UNLIKELY(((t).flag_ & CONST_FLAG) && __fakelua_init_flag__)) { \ + if (UNLIKELY(((t).flag_ & CONST_FLAG) && !FL_IN_CONST_INIT)) { \ FL_RAISE_HINT(_S, "attempt to modify a const table"); \ } \ } while (0) @@ -243,11 +247,11 @@ typedef struct FlHeapSlot { extern void *FakeluaAlloc(State *s, size_t size, bool is_const); static inline void *FlFastAlloc(State *state, size_t size, bool is_const) { - FlHeapSlot *hs = (is_const || !__fakelua_init_flag__) ? (FlHeapSlot *) fl_const_heap : (FlHeapSlot *) fl_temp_heap; + FlHeapSlot *hs = (is_const || FL_IN_CONST_INIT) ? (FlHeapSlot *) fl_const_heap : (FlHeapSlot *) fl_temp_heap; if (LIKELY(hs != NULL)) { size_t aligned_size = (size + 15) & ~(size_t) 15; char *c = hs->curr; - if (LIKELY(c != NULL && aligned_size >= size && c + aligned_size > c && c + aligned_size <= hs->end)) { + if (LIKELY(c != NULL && aligned_size >= size && hs->end >= c && (size_t) (hs->end - c) >= aligned_size)) { hs->curr = c + aligned_size; return (void *) c; } @@ -256,7 +260,7 @@ static inline void *FlFastAlloc(State *state, size_t size, bool is_const) { } static inline CVar FlAllocMulti(State *state, uint32_t count) { - VarMulti *m = (VarMulti *) FlFastAlloc(state, sizeof(VarMulti) + count * sizeof(CVar), !__fakelua_init_flag__); + VarMulti *m = (VarMulti *) FlFastAlloc(state, sizeof(VarMulti) + count * sizeof(CVar), FL_IN_CONST_INIT); m->count = count; CVar res; res.type_ = VAR_MULTI; @@ -274,7 +278,7 @@ static inline void FlSetMultiCVarElement(CVar multi, int idx, CVar val) { } static inline CVar FlMakeMulti(State *state, uint32_t count, ...) { - VarMulti *m = (VarMulti *) FlFastAlloc(state, sizeof(VarMulti) + count * sizeof(CVar), !__fakelua_init_flag__); + VarMulti *m = (VarMulti *) FlFastAlloc(state, sizeof(VarMulti) + count * sizeof(CVar), FL_IN_CONST_INIT); m->count = count; va_list args_list; va_start(args_list, count); @@ -299,7 +303,7 @@ static inline CVar FlCombineMulti(State *state, uint32_t prefix_count, const CVa } uint32_t total_count = prefix_count + last_count; - VarMulti *m = (VarMulti *) FlFastAlloc(state, sizeof(VarMulti) + total_count * sizeof(CVar), !__fakelua_init_flag__); + VarMulti *m = (VarMulti *) FlFastAlloc(state, sizeof(VarMulti) + total_count * sizeof(CVar), FL_IN_CONST_INIT); m->count = total_count; for (uint32_t i = 0; i < prefix_count; ++i) { @@ -337,7 +341,7 @@ static inline CVar FlSliceMulti(State *state, CVar v, uint32_t start_idx) { return (CVar) {VAR_NIL}; } uint32_t count = m->count - start_idx; - VarMulti *nm = (VarMulti *) FlFastAlloc(state, sizeof(VarMulti) + count * sizeof(CVar), !__fakelua_init_flag__); + VarMulti *nm = (VarMulti *) FlFastAlloc(state, sizeof(VarMulti) + count * sizeof(CVar), FL_IN_CONST_INIT); nm->count = count; for (uint32_t i = 0; i < count; ++i) { nm->vars[i] = m->vars[start_idx + i]; @@ -475,6 +479,7 @@ extern CVar FakeluaAllocMultiCVar(State *s, int count); extern void FakeluaSetMultiCVarElement(CVar *multi, int idx, CVar val); extern CVar FlEvalLoadClosure(State *state, VarClosure *cl, int arg_num, const CVar *args); extern CVar FakeluaInterpCall(State *state, VarClosure *cl, int arg_num, const CVar *args); +extern CVar FakeluaPromoteConstBoxValue(State *state, CVar val); // 当前执行引擎上下文(供 JIT C 代码调用闭包前后维护):push 切到 jit 并返回上一个引擎, // pop 恢复。native 对象方法等在闭包内执行时据此登记派回本引擎的异步回调。 extern int FakeluaJitContextPush(State *s, int jit); @@ -551,16 +556,42 @@ static inline void FlLuaPop(const FlLuaFrame *saved) { #define kMaxFunctionInputParams 32 +#define FL_CONST_BOX_FLAG 0x2 + +static inline CVar *FlAllocUpvalueBox(State *state, bool is_const) { + CVar *box = (CVar *) FlFastAlloc(state, sizeof(CVar), is_const); + box->type_ = VAR_NIL; + box->flag_ = is_const ? FL_CONST_BOX_FLAG : 0; + box->data_.i = 0; + return box; +} + +static inline CVar FlLoadUpvalueBox(const CVar *box) { + CVar v = *box; + v.flag_ &= ~FL_CONST_BOX_FLAG; + return v; +} + +static inline void FlStoreUpvalueBox(State *state, CVar *box, CVar v) { + if (UNLIKELY((box->flag_ & FL_CONST_BOX_FLAG) != 0)) { + if (!FL_IN_CONST_INIT) { + v = FakeluaPromoteConstBoxValue(state, v); + } + v.flag_ |= FL_CONST_BOX_FLAG; + } + *box = v; +} + // 注意:is_vararg 必须声明为 int 而非 bool。C17 7.16.1.4 规定 va_start 的最后一个 // 具名形参若类型会受默认实参提升影响(bool/_Bool 会被提升为 int),行为未定义。 // 调用处传入的 true/false 会隐式转换为 int。 static inline CVar FlMakeClosure(State *state, void *func_ptr, int upvalue_count, int expected_arg_count, int is_vararg, ...) { - VarClosure *cl = (VarClosure *) FlFastAlloc(state, sizeof(VarClosure) + upvalue_count * sizeof(CVar *), !__fakelua_init_flag__); + VarClosure *cl = (VarClosure *) FlFastAlloc(state, sizeof(VarClosure) + upvalue_count * sizeof(CVar *), FL_IN_CONST_INIT); cl->func_ptr = func_ptr; cl->upvalue_count = upvalue_count; cl->expected_arg_count = expected_arg_count; cl->is_vararg = is_vararg; - cl->code_str = NULL; + cl->code_str = (FAKELUA_JIT_TYPE == 1) ? (const char *) 2 : NULL; va_list args_list; va_start(args_list, is_vararg); for (int i = 0; i < upvalue_count; ++i) { @@ -575,12 +606,12 @@ static inline CVar FlMakeClosure(State *state, void *func_ptr, int upvalue_count } static inline CVar FlMakeClosure0(State *state, void *func_ptr, int expected_arg_count, int is_vararg) { - VarClosure *cl = (VarClosure *) FlFastAlloc(state, sizeof(VarClosure), !__fakelua_init_flag__); + VarClosure *cl = (VarClosure *) FlFastAlloc(state, sizeof(VarClosure), FL_IN_CONST_INIT); cl->func_ptr = func_ptr; cl->upvalue_count = 0; cl->expected_arg_count = expected_arg_count; cl->is_vararg = is_vararg; - cl->code_str = NULL; + cl->code_str = (FAKELUA_JIT_TYPE == 1) ? (const char *) 2 : NULL; CVar res; res.type_ = VAR_CLOSURE; res.flag_ = 0; @@ -589,12 +620,12 @@ static inline CVar FlMakeClosure0(State *state, void *func_ptr, int expected_arg } static inline CVar FlMakeClosure1(State *state, void *func_ptr, int expected_arg_count, int is_vararg, CVar *up0) { - VarClosure *cl = (VarClosure *) FlFastAlloc(state, sizeof(VarClosure) + sizeof(CVar *), !__fakelua_init_flag__); + VarClosure *cl = (VarClosure *) FlFastAlloc(state, sizeof(VarClosure) + sizeof(CVar *), FL_IN_CONST_INIT); cl->func_ptr = func_ptr; cl->upvalue_count = 1; cl->expected_arg_count = expected_arg_count; cl->is_vararg = is_vararg; - cl->code_str = NULL; + cl->code_str = (FAKELUA_JIT_TYPE == 1) ? (const char *) 2 : NULL; cl->upvalues[0] = up0; CVar res; res.type_ = VAR_CLOSURE; @@ -612,28 +643,29 @@ static inline CVar FlCallClosureFn(FL_HINT_PARAMS_HEAD State *state, CVar cl_var if (UNLIKELY(arg_num < 0 || arg_num > (int) kMaxFunctionInputParams)) { FL_RAISE_HINT(state, "too many arguments"); } + + CVar raw_arg_arr[kMaxFunctionInputParams]; + va_list args_list; + va_start(args_list, arg_num); + for (int i = 0; i < arg_num; ++i) { + raw_arg_arr[i] = va_arg(args_list, CVar); + } + va_end(args_list); + VarClosure *cl = cl_var.data_.cl; void *addr = cl->func_ptr; if (UNLIKELY(addr == NULL)) { - return FlEvalLoadClosure(state, cl, arg_num, cl_var.type_ == VAR_CLOSURE ? (const CVar *) &cl_var : NULL); + return FlEvalLoadClosure(state, cl, arg_num, arg_num > 0 ? raw_arg_arr : NULL); } const bool is_vararg = cl->is_vararg; const int expected_arg_count = cl->expected_arg_count; - const int fixed_arg_count = is_vararg ? expected_arg_count - 1 : expected_arg_count; + const int fixed_arg_count = is_vararg ? (expected_arg_count > 0 ? expected_arg_count - 1 : 0) : expected_arg_count; // 形参个数也要限:下面按 expected_arg_count 往 temp_arg_arr(定长 32)里写, // 声明了超过上限的形参会栈缓冲溢出(与 vm.cpp 的 CallByNameImpl 一致)。 if (UNLIKELY(expected_arg_count < 0 || expected_arg_count > (int) kMaxFunctionInputParams)) { FL_RAISE_HINT(state, "too many arguments"); } - CVar raw_arg_arr[kMaxFunctionInputParams]; - va_list args_list; - va_start(args_list, arg_num); - for (int i = 0; i < arg_num; ++i) { - raw_arg_arr[i] = va_arg(args_list, CVar); - } - va_end(args_list); - const CVar *arg_arr = NULL; const bool last_is_multi = (arg_num > 0 && raw_arg_arr[arg_num - 1].type_ == VAR_MULTI); CVar temp_arg_arr[kMaxFunctionInputParams]; @@ -673,7 +705,7 @@ static inline CVar FlCallClosureFn(FL_HINT_PARAMS_HEAD State *state, CVar cl_var temp_arg_arr[i] = i < flat_count ? flat_args_buf[i] : (CVar) {VAR_NIL}; } const int vararg_count = flat_count - fixed_arg_count; - VarMulti *m = (VarMulti *) FlFastAlloc(state, sizeof(VarMulti) + (vararg_count > 0 ? vararg_count : 0) * sizeof(CVar), !__fakelua_init_flag__); + VarMulti *m = (VarMulti *) FlFastAlloc(state, sizeof(VarMulti) + (vararg_count > 0 ? vararg_count : 0) * sizeof(CVar), FL_IN_CONST_INIT); m->count = vararg_count > 0 ? vararg_count : 0; for (int i = 0; i < vararg_count; ++i) { m->vars[i] = flat_args_buf[fixed_arg_count + i]; @@ -771,7 +803,7 @@ static inline CVar FlCallClosureFn(FL_HINT_PARAMS_HEAD State *state, CVar cl_var #define FCCASE(N) \ case N: { \ FlLuaLoc __fl_saved_loc = *fl_active_loc; \ - int __fl_prev_jit = FakeluaJitContextPush(state, FAKELUA_JIT_TYPE); \ + int __fl_prev_jit = FakeluaJitContextPush(state, (cl->code_str == (const char *) 2 ? 1 : 0)); \ CVar __fl_ret = ((CVar (*)(VarClosure * FCCVAR_##N))(addr))(cl FCARG_##N); \ FakeluaJitContextPop(state, __fl_prev_jit); \ *fl_active_loc = __fl_saved_loc; \ @@ -881,7 +913,7 @@ static inline CVar FlCallClosure0Fn(State *state, CVar cl_var FL_HINT_PARAMS) { if (LIKELY(cl_var.type_ == VAR_CLOSURE)) { VarClosure *cl = cl_var.data_.cl; void *addr = cl->func_ptr; - if (LIKELY(addr != NULL && !cl->is_vararg && cl->expected_arg_count == 0 && cl->code_str != (const char *) 1)) { + if (LIKELY(addr != NULL && !cl->is_vararg && cl->expected_arg_count == 0 && cl->code_str == ((FAKELUA_JIT_TYPE == 1) ? (const char *) 2 : (const char *) 0))) { FlLuaLoc __fl_saved_loc = *fl_active_loc; CVar __fl_ret = ((CVar (*)(VarClosure *))(addr))(cl); *fl_active_loc = __fl_saved_loc; @@ -896,7 +928,7 @@ static inline CVar FlCallClosure1Fn(State *state, CVar cl_var, CVar a0 FL_HINT_P if (LIKELY(cl_var.type_ == VAR_CLOSURE)) { VarClosure *cl = cl_var.data_.cl; void *addr = cl->func_ptr; - if (LIKELY(addr != NULL && !cl->is_vararg && cl->expected_arg_count == 1 && a0.type_ != VAR_MULTI && cl->code_str != (const char *) 1)) { + if (LIKELY(addr != NULL && !cl->is_vararg && cl->expected_arg_count == 1 && a0.type_ != VAR_MULTI && cl->code_str == ((FAKELUA_JIT_TYPE == 1) ? (const char *) 2 : (const char *) 0))) { FlLuaLoc __fl_saved_loc = *fl_active_loc; CVar __fl_ret = ((CVar (*)(VarClosure *, CVar))(addr))(cl, a0); *fl_active_loc = __fl_saved_loc; @@ -911,7 +943,7 @@ static inline CVar FlCallClosure2Fn(State *state, CVar cl_var, CVar a0, CVar a1 if (LIKELY(cl_var.type_ == VAR_CLOSURE)) { VarClosure *cl = cl_var.data_.cl; void *addr = cl->func_ptr; - if (LIKELY(addr != NULL && !cl->is_vararg && cl->expected_arg_count == 2 && a0.type_ != VAR_MULTI && a1.type_ != VAR_MULTI && cl->code_str != (const char *) 1)) { + if (LIKELY(addr != NULL && !cl->is_vararg && cl->expected_arg_count == 2 && a0.type_ != VAR_MULTI && a1.type_ != VAR_MULTI && cl->code_str == ((FAKELUA_JIT_TYPE == 1) ? (const char *) 2 : (const char *) 0))) { FlLuaLoc __fl_saved_loc = *fl_active_loc; CVar __fl_ret = ((CVar (*)(VarClosure *, CVar, CVar))(addr))(cl, a0, a1); *fl_active_loc = __fl_saved_loc; @@ -926,7 +958,7 @@ static inline CVar FlCallClosure3Fn(State *state, CVar cl_var, CVar a0, CVar a1, if (LIKELY(cl_var.type_ == VAR_CLOSURE)) { VarClosure *cl = cl_var.data_.cl; void *addr = cl->func_ptr; - if (LIKELY(addr != NULL && !cl->is_vararg && cl->expected_arg_count == 3 && a0.type_ != VAR_MULTI && a1.type_ != VAR_MULTI && a2.type_ != VAR_MULTI && cl->code_str != (const char *) 1)) { + if (LIKELY(addr != NULL && !cl->is_vararg && cl->expected_arg_count == 3 && a0.type_ != VAR_MULTI && a1.type_ != VAR_MULTI && a2.type_ != VAR_MULTI && cl->code_str == ((FAKELUA_JIT_TYPE == 1) ? (const char *) 2 : (const char *) 0))) { FlLuaLoc __fl_saved_loc = *fl_active_loc; CVar __fl_ret = ((CVar (*)(VarClosure *, CVar, CVar, CVar))(addr))(cl, a0, a1, a2); *fl_active_loc = __fl_saved_loc; @@ -1108,7 +1140,7 @@ static inline uint32_t FlHashString(const char *str, int len) { do { \ int __len = (len); \ const char *__s_ptr = (str); \ - VarString *__vs = (VarString *) FlFastAlloc(_S, sizeof(VarString) + __len, !__fakelua_init_flag__); \ + VarString *__vs = (VarString *) FlFastAlloc(_S, sizeof(VarString) + __len, FL_IN_CONST_INIT); \ __vs->size_ = __len; \ __vs->hash_ = 0; \ memcpy(__vs->data_, __s_ptr, __len); \ @@ -1118,7 +1150,7 @@ static inline uint32_t FlHashString(const char *str, int len) { #define SET_TABLE(v) \ do { \ - VarTable *__t = (VarTable *) FlFastAlloc(_S, sizeof(VarTable), !__fakelua_init_flag__); \ + VarTable *__t = (VarTable *) FlFastAlloc(_S, sizeof(VarTable), FL_IN_CONST_INIT); \ __t->count_ = 0; \ __t->bucket_count_ = 0; \ __t->nodes_ = NULL; \ @@ -1146,19 +1178,19 @@ static inline uint32_t FlHashString(const char *str, int len) { } \ (v).type_ = VAR_TABLE; \ /* init 中创建 → CONST_FLAG(嵌套表同样走 SET_TABLE,整树只读);init 后创建 → 可变 */ \ - (v).flag_ = __fakelua_init_flag__ ? 0 : CONST_FLAG; \ + (v).flag_ = FL_IN_CONST_INIT ? CONST_FLAG : 0; \ (v).data_.t = __t; \ } while (0) #define SET_TABLE_SPEC(v, SpecType, get_fn, set_fn, field_count) \ do { \ SET_TABLE(v); \ - SpecType *__sp = (SpecType *) FlFastAlloc(_S, sizeof(SpecType), !__fakelua_init_flag__); \ + SpecType *__sp = (SpecType *) FlFastAlloc(_S, sizeof(SpecType), FL_IN_CONST_INIT); \ (v).data_.t->spec = __sp; \ (v).data_.t->spec_get = (get_fn); \ (v).data_.t->spec_set = (set_fn); \ - (v).data_.t->spec_keys = (CVar *) FlFastAlloc(_S, sizeof(CVar) * (field_count), !__fakelua_init_flag__); \ - (v).data_.t->spec_vals = (CVar *) FlFastAlloc(_S, sizeof(CVar) * (field_count), !__fakelua_init_flag__); \ + (v).data_.t->spec_keys = (CVar *) FlFastAlloc(_S, sizeof(CVar) * (field_count), FL_IN_CONST_INIT); \ + (v).data_.t->spec_vals = (CVar *) FlFastAlloc(_S, sizeof(CVar) * (field_count), FL_IN_CONST_INIT); \ (v).data_.t->spec_count = (field_count); \ assert(sizeof(SpecType) == (field_count) * sizeof(CVar)); \ } while (0) @@ -1476,7 +1508,7 @@ static inline void FlTableRehash(VarTable *tbl) { uint32_t total_nodes = new_bucket_count + overflow_count; size_t nodes_size = total_nodes * sizeof(TableNode); size_t active_list_size = total_nodes * sizeof(uint32_t); - char *buffer = (char *) FlFastAlloc(_S, nodes_size + active_list_size, !__fakelua_init_flag__); + char *buffer = (char *) FlFastAlloc(_S, nodes_size + active_list_size, FL_IN_CONST_INIT); TableNode *new_nodes = (TableNode *) buffer; uint32_t *new_active_list = (uint32_t *) (buffer + nodes_size); { @@ -1821,7 +1853,7 @@ static inline CVar FlHashGetInt(VarTable *tbl, int64_t k) { __attribute__((noinline)) static void FlArrGrow(VarTable *tbl) { uint32_t cap = tbl->arr_cap_ ? tbl->arr_cap_ * 2 : 4; - CVar *na = (CVar *) FlFastAlloc(_S, (size_t) cap * sizeof(CVar), !__fakelua_init_flag__); + CVar *na = (CVar *) FlFastAlloc(_S, (size_t) cap * sizeof(CVar), FL_IN_CONST_INIT); if (tbl->arr_size_ > 0) { memcpy(na, tbl->arr_, (size_t) tbl->arr_size_ * sizeof(CVar)); } @@ -1917,7 +1949,7 @@ __attribute__((noinline)) static bool FlArrTryResize(VarTable *tbl, int64_t nk) } { uint32_t old_size = tbl->arr_size_; - CVar *na = (CVar *) FlFastAlloc(_S, (size_t) optimal * sizeof(CVar), !__fakelua_init_flag__); + CVar *na = (CVar *) FlFastAlloc(_S, (size_t) optimal * sizeof(CVar), FL_IN_CONST_INIT); if (old_size > 0) { memcpy(na, tbl->arr_, (size_t) old_size * sizeof(CVar)); } @@ -2086,7 +2118,7 @@ static inline void FlSetTableIntImpl(CVar t, int64_t k, CVar v FL_HINT_PARAMS) { } static inline void FlSetTableIntFn(CVar t, int64_t k, CVar v FL_HINT_PARAMS) { - if (LIKELY(t.type_ == VAR_TABLE && (!(t.flag_ & CONST_FLAG) || !__fakelua_init_flag__))) { + if (LIKELY(t.type_ == VAR_TABLE && (!(t.flag_ & CONST_FLAG) || FL_IN_CONST_INIT))) { VarTable *tbl = t.data_.t; uint64_t idx = (uint64_t) k - 1; /* 新旧值都非 nil 时序列长度不变,可跳过缓存维护。*/ @@ -2103,7 +2135,7 @@ static inline void FlSetTableIntFn(CVar t, int64_t k, CVar v FL_HINT_PARAMS) { #define FlSetTableInt(...) FlSetTableIntFn(__VA_ARGS__ FL_HINT_ARGS) static inline void FlSetTableInt_IntFn(CVar t, int64_t k, int64_t v FL_HINT_PARAMS) { - if (LIKELY(t.type_ == VAR_TABLE && (!(t.flag_ & CONST_FLAG) || !__fakelua_init_flag__))) { + if (LIKELY(t.type_ == VAR_TABLE && (!(t.flag_ & CONST_FLAG) || FL_IN_CONST_INIT))) { VarTable *tbl = t.data_.t; uint64_t idx = (uint64_t) k - 1; if (LIKELY(idx < (uint64_t) tbl->arr_size_ && tbl->arr_[idx].type_ != VAR_NIL)) { @@ -2125,7 +2157,7 @@ static inline void FlSetTableInt_IntFn(CVar t, int64_t k, int64_t v FL_HINT_PARA #define FlSetTableInt_Int(...) FlSetTableInt_IntFn(__VA_ARGS__ FL_HINT_ARGS) static inline void FlSetTableInt_FloatFn(CVar t, int64_t k, double v FL_HINT_PARAMS) { - if (LIKELY(t.type_ == VAR_TABLE && (!(t.flag_ & CONST_FLAG) || !__fakelua_init_flag__))) { + if (LIKELY(t.type_ == VAR_TABLE && (!(t.flag_ & CONST_FLAG) || FL_IN_CONST_INIT))) { VarTable *tbl = t.data_.t; uint64_t idx = (uint64_t) k - 1; if (LIKELY(idx < (uint64_t) tbl->arr_size_ && tbl->arr_[idx].type_ != VAR_NIL)) { @@ -2147,7 +2179,7 @@ static inline void FlSetTableInt_FloatFn(CVar t, int64_t k, double v FL_HINT_PAR #define FlSetTableInt_Float(...) FlSetTableInt_FloatFn(__VA_ARGS__ FL_HINT_ARGS) static inline void FlSetTableInt_BoolFn(CVar t, int64_t k, bool b FL_HINT_PARAMS) { - if (LIKELY(t.type_ == VAR_TABLE && (!(t.flag_ & CONST_FLAG) || !__fakelua_init_flag__))) { + if (LIKELY(t.type_ == VAR_TABLE && (!(t.flag_ & CONST_FLAG) || FL_IN_CONST_INIT))) { VarTable *tbl = t.data_.t; uint64_t idx = (uint64_t) k - 1; if (LIKELY(idx < (uint64_t) tbl->arr_size_ && tbl->arr_[idx].type_ != VAR_NIL)) { @@ -2751,7 +2783,7 @@ static inline CVar FlConcatFn(CVar a, CVar b FL_HINT_PARAMS) { if (UNLIKELY(total < la || total < lb)) { FL_RAISE_HINT(_S, "string concatenation result too long"); } - VarString *vs = (VarString *) FlFastAlloc(_S, sizeof(VarString) + total, !__fakelua_init_flag__); + VarString *vs = (VarString *) FlFastAlloc(_S, sizeof(VarString) + total, FL_IN_CONST_INIT); vs->size_ = total; vs->hash_ = 0; memcpy(vs->data_, sa, la); @@ -2769,7 +2801,7 @@ static inline CVar FlStringChar1Fn(int64_t c FL_HINT_PARAMS) { if (UNLIKELY(c < 0 || c > 255)) { FL_RAISE_HINT(_S, "bad argument to string.char: value out of range"); } - VarString *vs = (VarString *) FlFastAlloc(_S, sizeof(VarString) + 1, !__fakelua_init_flag__); + VarString *vs = (VarString *) FlFastAlloc(_S, sizeof(VarString) + 1, FL_IN_CONST_INIT); vs->size_ = 1; vs->hash_ = 0; vs->data_[0] = (char) c; @@ -2795,7 +2827,7 @@ static inline CVar FlStringLower(CVar s) { } else { return FakeluaCallByName(_S, FAKELUA_JIT_TYPE, "string.lower", 1, s); } - VarString *out = (VarString *) FlFastAlloc(_S, sizeof(VarString) + len, !__fakelua_init_flag__); + VarString *out = (VarString *) FlFastAlloc(_S, sizeof(VarString) + len, FL_IN_CONST_INIT); out->size_ = len; out->hash_ = 0; for (int i = 0; i < len; ++i) { @@ -2822,7 +2854,7 @@ static inline CVar FlStringUpper(CVar s) { } else { return FakeluaCallByName(_S, FAKELUA_JIT_TYPE, "string.upper", 1, s); } - VarString *out = (VarString *) FlFastAlloc(_S, sizeof(VarString) + len, !__fakelua_init_flag__); + VarString *out = (VarString *) FlFastAlloc(_S, sizeof(VarString) + len, FL_IN_CONST_INIT); out->size_ = len; out->hash_ = 0; for (int i = 0; i < len; ++i) { @@ -2851,7 +2883,7 @@ static inline CVar FlStringByte1(CVar s, int64_t i) { return FakeluaCallByName(_S, FAKELUA_JIT_TYPE, "string.byte", 2, s, (CVar) {.type_ = VAR_INT, .data_.i = i}); } if (i < 0) i = len + i + 1; - if (i < 1 || i > len) return (CVar) {VAR_NIL}; + if (UNLIKELY(i < 1 || i > len)) return FlAllocMulti(_S, 0); return (CVar) {.type_ = VAR_INT, .data_.i = (unsigned char) src[i - 1]}; } @@ -2870,7 +2902,7 @@ static inline CVar FlStringRep(CVar s, int64_t n) { return FakeluaCallByName(_S, FAKELUA_JIT_TYPE, "string.rep", 2, s, (CVar) {.type_ = VAR_INT, .data_.i = n}); } if (n <= 0 || len == 0) { - VarString *vs = (VarString *) FlFastAlloc(_S, sizeof(VarString), !__fakelua_init_flag__); + VarString *vs = (VarString *) FlFastAlloc(_S, sizeof(VarString) + 1, FL_IN_CONST_INIT); vs->size_ = 0; vs->hash_ = 0; vs->data_[0] = '\0'; @@ -2885,7 +2917,7 @@ static inline CVar FlStringRep(CVar s, int64_t n) { return FakeluaCallByName(_S, FAKELUA_JIT_TYPE, "string.rep", 2, s, (CVar) {.type_ = VAR_INT, .data_.i = n}); } int64_t total = (int64_t) len * n; - VarString *out = (VarString *) FlFastAlloc(_S, sizeof(VarString) + total, !__fakelua_init_flag__); + VarString *out = (VarString *) FlFastAlloc(_S, sizeof(VarString) + total, FL_IN_CONST_INIT); out->size_ = total; out->hash_ = 0; char *dst = out->data_; @@ -2914,7 +2946,7 @@ static inline CVar FlStringReverse(CVar s) { } else { return FakeluaCallByName(_S, FAKELUA_JIT_TYPE, "string.reverse", 1, s); } - VarString *out = (VarString *) FlFastAlloc(_S, sizeof(VarString) + len, !__fakelua_init_flag__); + VarString *out = (VarString *) FlFastAlloc(_S, sizeof(VarString) + len, FL_IN_CONST_INIT); out->size_ = len; out->hash_ = 0; for (int i = 0; i < len; ++i) { @@ -2968,7 +3000,7 @@ static inline CVar FlStringFindPlain(CVar s, CVar pat) { static inline CVar FlFormatInt(int64_t v) { char buf[32]; int n = FlFastItoA(v, buf); - VarString *vs = (VarString *) FlFastAlloc(_S, sizeof(VarString) + n, !__fakelua_init_flag__); + VarString *vs = (VarString *) FlFastAlloc(_S, sizeof(VarString) + n, FL_IN_CONST_INIT); vs->size_ = n; vs->hash_ = 0; memcpy(vs->data_, buf, (size_t) n); @@ -3244,13 +3276,11 @@ static inline CVar FlTableUnpackFn(CVar tbl, int64_t start_i, int64_t end_j FL_H if (UNLIKELY(__fm_b == 0)) { \ FL_RAISE(_S, "modulo by zero"); \ } \ - if (UNLIKELY(__fm_b == (int64_t) -1)) { \ - (result) = 0; \ - } else { \ - int64_t __fm_q; \ - FlFloorDivQuotient(__fm_a, __fm_b, __fm_q); \ - (result) = __fm_a - __fm_b * __fm_q; \ + int64_t __fm_r = UNLIKELY(__fm_b == (int64_t) -1) ? 0 : (__fm_a % __fm_b); \ + if (__fm_r != 0 && ((__fm_r < 0) != (__fm_b < 0))) { \ + __fm_r += __fm_b; \ } \ + (result) = __fm_r; \ } while (0) #define FlModFloat(a, b, result) \ diff --git a/src/compile/c_runtime_header.h b/src/compile/c_runtime_header.h index 19405b9b..f137e541 100644 --- a/src/compile/c_runtime_header.h +++ b/src/compile/c_runtime_header.h @@ -132,16 +132,20 @@ enum { // __fakelua_init_flag__:false=仍在 __fakelua_init(可填充 const 表);true=init 已结束。 // init 期间 NEWTABLE/SET_TABLE 创建的表直接打 CONST_FLAG(整棵树,含嵌套); // SETTABLE 仅在 init 结束后才因 CONST_FLAG 抛错,以便构造器写字段。 +static const bool fl_const_alloc_false = false; +static const bool *fl_const_alloc = &fl_const_alloc_false; +#define FL_IN_CONST_INIT (!__fakelua_init_flag__ || *fl_const_alloc) + #define CONST_FLAG 0x1 #define FL_CHECK_CONST_TABLE(t) \ do { \ - if (UNLIKELY(((t).flag_ & CONST_FLAG) && __fakelua_init_flag__)) { \ + if (UNLIKELY(((t).flag_ & CONST_FLAG) && !FL_IN_CONST_INIT)) { \ FL_RAISE(_S, "attempt to modify a const table"); \ } \ } while (0) #define FL_CHECK_CONST_TABLE_HINT(t) \ do { \ - if (UNLIKELY(((t).flag_ & CONST_FLAG) && __fakelua_init_flag__)) { \ + if (UNLIKELY(((t).flag_ & CONST_FLAG) && !FL_IN_CONST_INIT)) { \ FL_RAISE_HINT(_S, "attempt to modify a const table"); \ } \ } while (0) @@ -265,11 +269,11 @@ typedef struct FlHeapSlot { extern void *FakeluaAlloc(State *s, size_t size, bool is_const); static inline void *FlFastAlloc(State *state, size_t size, bool is_const) { - FlHeapSlot *hs = (is_const || !__fakelua_init_flag__) ? (FlHeapSlot *) fl_const_heap : (FlHeapSlot *) fl_temp_heap; + FlHeapSlot *hs = (is_const || FL_IN_CONST_INIT) ? (FlHeapSlot *) fl_const_heap : (FlHeapSlot *) fl_temp_heap; if (LIKELY(hs != NULL)) { size_t aligned_size = (size + 15) & ~(size_t) 15; char *c = hs->curr; - if (LIKELY(c != NULL && aligned_size >= size && c + aligned_size > c && c + aligned_size <= hs->end)) { + if (LIKELY(c != NULL && aligned_size >= size && hs->end >= c && (size_t) (hs->end - c) >= aligned_size)) { hs->curr = c + aligned_size; return (void *) c; } @@ -278,7 +282,7 @@ static inline void *FlFastAlloc(State *state, size_t size, bool is_const) { } static inline CVar FlAllocMulti(State *state, uint32_t count) { - VarMulti *m = (VarMulti *) FlFastAlloc(state, sizeof(VarMulti) + count * sizeof(CVar), !__fakelua_init_flag__); + VarMulti *m = (VarMulti *) FlFastAlloc(state, sizeof(VarMulti) + count * sizeof(CVar), FL_IN_CONST_INIT); m->count = count; CVar res; res.type_ = VAR_MULTI; @@ -296,7 +300,7 @@ static inline void FlSetMultiCVarElement(CVar multi, int idx, CVar val) { } static inline CVar FlMakeMulti(State *state, uint32_t count, ...) { - VarMulti *m = (VarMulti *) FlFastAlloc(state, sizeof(VarMulti) + count * sizeof(CVar), !__fakelua_init_flag__); + VarMulti *m = (VarMulti *) FlFastAlloc(state, sizeof(VarMulti) + count * sizeof(CVar), FL_IN_CONST_INIT); m->count = count; va_list args_list; va_start(args_list, count); @@ -321,7 +325,7 @@ static inline CVar FlCombineMulti(State *state, uint32_t prefix_count, const CVa } uint32_t total_count = prefix_count + last_count; - VarMulti *m = (VarMulti *) FlFastAlloc(state, sizeof(VarMulti) + total_count * sizeof(CVar), !__fakelua_init_flag__); + VarMulti *m = (VarMulti *) FlFastAlloc(state, sizeof(VarMulti) + total_count * sizeof(CVar), FL_IN_CONST_INIT); m->count = total_count; for (uint32_t i = 0; i < prefix_count; ++i) { @@ -359,7 +363,7 @@ static inline CVar FlSliceMulti(State *state, CVar v, uint32_t start_idx) { return (CVar) {VAR_NIL}; } uint32_t count = m->count - start_idx; - VarMulti *nm = (VarMulti *) FlFastAlloc(state, sizeof(VarMulti) + count * sizeof(CVar), !__fakelua_init_flag__); + VarMulti *nm = (VarMulti *) FlFastAlloc(state, sizeof(VarMulti) + count * sizeof(CVar), FL_IN_CONST_INIT); nm->count = count; for (uint32_t i = 0; i < count; ++i) { nm->vars[i] = m->vars[start_idx + i]; @@ -497,6 +501,7 @@ extern CVar FakeluaAllocMultiCVar(State *s, int count); extern void FakeluaSetMultiCVarElement(CVar *multi, int idx, CVar val); extern CVar FlEvalLoadClosure(State *state, VarClosure *cl, int arg_num, const CVar *args); extern CVar FakeluaInterpCall(State *state, VarClosure *cl, int arg_num, const CVar *args); +extern CVar FakeluaPromoteConstBoxValue(State *state, CVar val); // 当前执行引擎上下文(供 JIT C 代码调用闭包前后维护):push 切到 jit 并返回上一个引擎, // pop 恢复。native 对象方法等在闭包内执行时据此登记派回本引擎的异步回调。 extern int FakeluaJitContextPush(State *s, int jit); @@ -573,16 +578,42 @@ static inline void FlLuaPop(const FlLuaFrame *saved) { #define kMaxFunctionInputParams 32 +#define FL_CONST_BOX_FLAG 0x2 + +static inline CVar *FlAllocUpvalueBox(State *state, bool is_const) { + CVar *box = (CVar *) FlFastAlloc(state, sizeof(CVar), is_const); + box->type_ = VAR_NIL; + box->flag_ = is_const ? FL_CONST_BOX_FLAG : 0; + box->data_.i = 0; + return box; +} + +static inline CVar FlLoadUpvalueBox(const CVar *box) { + CVar v = *box; + v.flag_ &= ~FL_CONST_BOX_FLAG; + return v; +} + +static inline void FlStoreUpvalueBox(State *state, CVar *box, CVar v) { + if (UNLIKELY((box->flag_ & FL_CONST_BOX_FLAG) != 0)) { + if (!FL_IN_CONST_INIT) { + v = FakeluaPromoteConstBoxValue(state, v); + } + v.flag_ |= FL_CONST_BOX_FLAG; + } + *box = v; +} + // 注意:is_vararg 必须声明为 int 而非 bool。C17 7.16.1.4 规定 va_start 的最后一个 // 具名形参若类型会受默认实参提升影响(bool/_Bool 会被提升为 int),行为未定义。 // 调用处传入的 true/false 会隐式转换为 int。 static inline CVar FlMakeClosure(State *state, void *func_ptr, int upvalue_count, int expected_arg_count, int is_vararg, ...) { - VarClosure *cl = (VarClosure *) FlFastAlloc(state, sizeof(VarClosure) + upvalue_count * sizeof(CVar *), !__fakelua_init_flag__); + VarClosure *cl = (VarClosure *) FlFastAlloc(state, sizeof(VarClosure) + upvalue_count * sizeof(CVar *), FL_IN_CONST_INIT); cl->func_ptr = func_ptr; cl->upvalue_count = upvalue_count; cl->expected_arg_count = expected_arg_count; cl->is_vararg = is_vararg; - cl->code_str = NULL; + cl->code_str = (FAKELUA_JIT_TYPE == 1) ? (const char *) 2 : NULL; va_list args_list; va_start(args_list, is_vararg); for (int i = 0; i < upvalue_count; ++i) { @@ -597,12 +628,12 @@ static inline CVar FlMakeClosure(State *state, void *func_ptr, int upvalue_count } static inline CVar FlMakeClosure0(State *state, void *func_ptr, int expected_arg_count, int is_vararg) { - VarClosure *cl = (VarClosure *) FlFastAlloc(state, sizeof(VarClosure), !__fakelua_init_flag__); + VarClosure *cl = (VarClosure *) FlFastAlloc(state, sizeof(VarClosure), FL_IN_CONST_INIT); cl->func_ptr = func_ptr; cl->upvalue_count = 0; cl->expected_arg_count = expected_arg_count; cl->is_vararg = is_vararg; - cl->code_str = NULL; + cl->code_str = (FAKELUA_JIT_TYPE == 1) ? (const char *) 2 : NULL; CVar res; res.type_ = VAR_CLOSURE; res.flag_ = 0; @@ -611,12 +642,12 @@ static inline CVar FlMakeClosure0(State *state, void *func_ptr, int expected_arg } static inline CVar FlMakeClosure1(State *state, void *func_ptr, int expected_arg_count, int is_vararg, CVar *up0) { - VarClosure *cl = (VarClosure *) FlFastAlloc(state, sizeof(VarClosure) + sizeof(CVar *), !__fakelua_init_flag__); + VarClosure *cl = (VarClosure *) FlFastAlloc(state, sizeof(VarClosure) + sizeof(CVar *), FL_IN_CONST_INIT); cl->func_ptr = func_ptr; cl->upvalue_count = 1; cl->expected_arg_count = expected_arg_count; cl->is_vararg = is_vararg; - cl->code_str = NULL; + cl->code_str = (FAKELUA_JIT_TYPE == 1) ? (const char *) 2 : NULL; cl->upvalues[0] = up0; CVar res; res.type_ = VAR_CLOSURE; @@ -634,28 +665,29 @@ static inline CVar FlCallClosureFn(FL_HINT_PARAMS_HEAD State *state, CVar cl_var if (UNLIKELY(arg_num < 0 || arg_num > (int) kMaxFunctionInputParams)) { FL_RAISE_HINT(state, "too many arguments"); } + + CVar raw_arg_arr[kMaxFunctionInputParams]; + va_list args_list; + va_start(args_list, arg_num); + for (int i = 0; i < arg_num; ++i) { + raw_arg_arr[i] = va_arg(args_list, CVar); + } + va_end(args_list); + VarClosure *cl = cl_var.data_.cl; void *addr = cl->func_ptr; if (UNLIKELY(addr == NULL)) { - return FlEvalLoadClosure(state, cl, arg_num, cl_var.type_ == VAR_CLOSURE ? (const CVar *) &cl_var : NULL); + return FlEvalLoadClosure(state, cl, arg_num, arg_num > 0 ? raw_arg_arr : NULL); } const bool is_vararg = cl->is_vararg; const int expected_arg_count = cl->expected_arg_count; - const int fixed_arg_count = is_vararg ? expected_arg_count - 1 : expected_arg_count; + const int fixed_arg_count = is_vararg ? (expected_arg_count > 0 ? expected_arg_count - 1 : 0) : expected_arg_count; // 形参个数也要限:下面按 expected_arg_count 往 temp_arg_arr(定长 32)里写, // 声明了超过上限的形参会栈缓冲溢出(与 vm.cpp 的 CallByNameImpl 一致)。 if (UNLIKELY(expected_arg_count < 0 || expected_arg_count > (int) kMaxFunctionInputParams)) { FL_RAISE_HINT(state, "too many arguments"); } - CVar raw_arg_arr[kMaxFunctionInputParams]; - va_list args_list; - va_start(args_list, arg_num); - for (int i = 0; i < arg_num; ++i) { - raw_arg_arr[i] = va_arg(args_list, CVar); - } - va_end(args_list); - const CVar *arg_arr = NULL; const bool last_is_multi = (arg_num > 0 && raw_arg_arr[arg_num - 1].type_ == VAR_MULTI); CVar temp_arg_arr[kMaxFunctionInputParams]; @@ -695,7 +727,7 @@ static inline CVar FlCallClosureFn(FL_HINT_PARAMS_HEAD State *state, CVar cl_var temp_arg_arr[i] = i < flat_count ? flat_args_buf[i] : (CVar) {VAR_NIL}; } const int vararg_count = flat_count - fixed_arg_count; - VarMulti *m = (VarMulti *) FlFastAlloc(state, sizeof(VarMulti) + (vararg_count > 0 ? vararg_count : 0) * sizeof(CVar), !__fakelua_init_flag__); + VarMulti *m = (VarMulti *) FlFastAlloc(state, sizeof(VarMulti) + (vararg_count > 0 ? vararg_count : 0) * sizeof(CVar), FL_IN_CONST_INIT); m->count = vararg_count > 0 ? vararg_count : 0; for (int i = 0; i < vararg_count; ++i) { m->vars[i] = flat_args_buf[fixed_arg_count + i]; @@ -793,7 +825,7 @@ static inline CVar FlCallClosureFn(FL_HINT_PARAMS_HEAD State *state, CVar cl_var #define FCCASE(N) \ case N: { \ FlLuaLoc __fl_saved_loc = *fl_active_loc; \ - int __fl_prev_jit = FakeluaJitContextPush(state, FAKELUA_JIT_TYPE); \ + int __fl_prev_jit = FakeluaJitContextPush(state, (cl->code_str == (const char *) 2 ? 1 : 0)); \ CVar __fl_ret = ((CVar (*)(VarClosure * FCCVAR_##N))(addr))(cl FCARG_##N); \ FakeluaJitContextPop(state, __fl_prev_jit); \ *fl_active_loc = __fl_saved_loc; \ @@ -903,7 +935,7 @@ static inline CVar FlCallClosure0Fn(State *state, CVar cl_var FL_HINT_PARAMS) { if (LIKELY(cl_var.type_ == VAR_CLOSURE)) { VarClosure *cl = cl_var.data_.cl; void *addr = cl->func_ptr; - if (LIKELY(addr != NULL && !cl->is_vararg && cl->expected_arg_count == 0 && cl->code_str != (const char *) 1)) { + if (LIKELY(addr != NULL && !cl->is_vararg && cl->expected_arg_count == 0 && cl->code_str == ((FAKELUA_JIT_TYPE == 1) ? (const char *) 2 : (const char *) 0))) { FlLuaLoc __fl_saved_loc = *fl_active_loc; CVar __fl_ret = ((CVar (*)(VarClosure *))(addr))(cl); *fl_active_loc = __fl_saved_loc; @@ -918,7 +950,7 @@ static inline CVar FlCallClosure1Fn(State *state, CVar cl_var, CVar a0 FL_HINT_P if (LIKELY(cl_var.type_ == VAR_CLOSURE)) { VarClosure *cl = cl_var.data_.cl; void *addr = cl->func_ptr; - if (LIKELY(addr != NULL && !cl->is_vararg && cl->expected_arg_count == 1 && a0.type_ != VAR_MULTI && cl->code_str != (const char *) 1)) { + if (LIKELY(addr != NULL && !cl->is_vararg && cl->expected_arg_count == 1 && a0.type_ != VAR_MULTI && cl->code_str == ((FAKELUA_JIT_TYPE == 1) ? (const char *) 2 : (const char *) 0))) { FlLuaLoc __fl_saved_loc = *fl_active_loc; CVar __fl_ret = ((CVar (*)(VarClosure *, CVar))(addr))(cl, a0); *fl_active_loc = __fl_saved_loc; @@ -933,7 +965,7 @@ static inline CVar FlCallClosure2Fn(State *state, CVar cl_var, CVar a0, CVar a1 if (LIKELY(cl_var.type_ == VAR_CLOSURE)) { VarClosure *cl = cl_var.data_.cl; void *addr = cl->func_ptr; - if (LIKELY(addr != NULL && !cl->is_vararg && cl->expected_arg_count == 2 && a0.type_ != VAR_MULTI && a1.type_ != VAR_MULTI && cl->code_str != (const char *) 1)) { + if (LIKELY(addr != NULL && !cl->is_vararg && cl->expected_arg_count == 2 && a0.type_ != VAR_MULTI && a1.type_ != VAR_MULTI && cl->code_str == ((FAKELUA_JIT_TYPE == 1) ? (const char *) 2 : (const char *) 0))) { FlLuaLoc __fl_saved_loc = *fl_active_loc; CVar __fl_ret = ((CVar (*)(VarClosure *, CVar, CVar))(addr))(cl, a0, a1); *fl_active_loc = __fl_saved_loc; @@ -948,7 +980,7 @@ static inline CVar FlCallClosure3Fn(State *state, CVar cl_var, CVar a0, CVar a1, if (LIKELY(cl_var.type_ == VAR_CLOSURE)) { VarClosure *cl = cl_var.data_.cl; void *addr = cl->func_ptr; - if (LIKELY(addr != NULL && !cl->is_vararg && cl->expected_arg_count == 3 && a0.type_ != VAR_MULTI && a1.type_ != VAR_MULTI && a2.type_ != VAR_MULTI && cl->code_str != (const char *) 1)) { + if (LIKELY(addr != NULL && !cl->is_vararg && cl->expected_arg_count == 3 && a0.type_ != VAR_MULTI && a1.type_ != VAR_MULTI && a2.type_ != VAR_MULTI && cl->code_str == ((FAKELUA_JIT_TYPE == 1) ? (const char *) 2 : (const char *) 0))) { FlLuaLoc __fl_saved_loc = *fl_active_loc; CVar __fl_ret = ((CVar (*)(VarClosure *, CVar, CVar, CVar))(addr))(cl, a0, a1, a2); *fl_active_loc = __fl_saved_loc; @@ -1130,7 +1162,7 @@ static inline uint32_t FlHashString(const char *str, int len) { do { \ int __len = (len); \ const char *__s_ptr = (str); \ - VarString *__vs = (VarString *) FlFastAlloc(_S, sizeof(VarString) + __len, !__fakelua_init_flag__); \ + VarString *__vs = (VarString *) FlFastAlloc(_S, sizeof(VarString) + __len, FL_IN_CONST_INIT); \ __vs->size_ = __len; \ __vs->hash_ = 0; \ memcpy(__vs->data_, __s_ptr, __len); \ @@ -1140,7 +1172,7 @@ static inline uint32_t FlHashString(const char *str, int len) { #define SET_TABLE(v) \ do { \ - VarTable *__t = (VarTable *) FlFastAlloc(_S, sizeof(VarTable), !__fakelua_init_flag__); \ + VarTable *__t = (VarTable *) FlFastAlloc(_S, sizeof(VarTable), FL_IN_CONST_INIT); \ __t->count_ = 0; \ __t->bucket_count_ = 0; \ __t->nodes_ = NULL; \ @@ -1168,19 +1200,19 @@ static inline uint32_t FlHashString(const char *str, int len) { } \ (v).type_ = VAR_TABLE; \ /* init 中创建 → CONST_FLAG(嵌套表同样走 SET_TABLE,整树只读);init 后创建 → 可变 */ \ - (v).flag_ = __fakelua_init_flag__ ? 0 : CONST_FLAG; \ + (v).flag_ = FL_IN_CONST_INIT ? CONST_FLAG : 0; \ (v).data_.t = __t; \ } while (0) #define SET_TABLE_SPEC(v, SpecType, get_fn, set_fn, field_count) \ do { \ SET_TABLE(v); \ - SpecType *__sp = (SpecType *) FlFastAlloc(_S, sizeof(SpecType), !__fakelua_init_flag__); \ + SpecType *__sp = (SpecType *) FlFastAlloc(_S, sizeof(SpecType), FL_IN_CONST_INIT); \ (v).data_.t->spec = __sp; \ (v).data_.t->spec_get = (get_fn); \ (v).data_.t->spec_set = (set_fn); \ - (v).data_.t->spec_keys = (CVar *) FlFastAlloc(_S, sizeof(CVar) * (field_count), !__fakelua_init_flag__); \ - (v).data_.t->spec_vals = (CVar *) FlFastAlloc(_S, sizeof(CVar) * (field_count), !__fakelua_init_flag__); \ + (v).data_.t->spec_keys = (CVar *) FlFastAlloc(_S, sizeof(CVar) * (field_count), FL_IN_CONST_INIT); \ + (v).data_.t->spec_vals = (CVar *) FlFastAlloc(_S, sizeof(CVar) * (field_count), FL_IN_CONST_INIT); \ (v).data_.t->spec_count = (field_count); \ assert(sizeof(SpecType) == (field_count) * sizeof(CVar)); \ } while (0) @@ -1498,7 +1530,7 @@ static inline void FlTableRehash(VarTable *tbl) { uint32_t total_nodes = new_bucket_count + overflow_count; size_t nodes_size = total_nodes * sizeof(TableNode); size_t active_list_size = total_nodes * sizeof(uint32_t); - char *buffer = (char *) FlFastAlloc(_S, nodes_size + active_list_size, !__fakelua_init_flag__); + char *buffer = (char *) FlFastAlloc(_S, nodes_size + active_list_size, FL_IN_CONST_INIT); TableNode *new_nodes = (TableNode *) buffer; uint32_t *new_active_list = (uint32_t *) (buffer + nodes_size); { @@ -1843,7 +1875,7 @@ static inline CVar FlHashGetInt(VarTable *tbl, int64_t k) { __attribute__((noinline)) static void FlArrGrow(VarTable *tbl) { uint32_t cap = tbl->arr_cap_ ? tbl->arr_cap_ * 2 : 4; - CVar *na = (CVar *) FlFastAlloc(_S, (size_t) cap * sizeof(CVar), !__fakelua_init_flag__); + CVar *na = (CVar *) FlFastAlloc(_S, (size_t) cap * sizeof(CVar), FL_IN_CONST_INIT); if (tbl->arr_size_ > 0) { memcpy(na, tbl->arr_, (size_t) tbl->arr_size_ * sizeof(CVar)); } @@ -1939,7 +1971,7 @@ __attribute__((noinline)) static bool FlArrTryResize(VarTable *tbl, int64_t nk) } { uint32_t old_size = tbl->arr_size_; - CVar *na = (CVar *) FlFastAlloc(_S, (size_t) optimal * sizeof(CVar), !__fakelua_init_flag__); + CVar *na = (CVar *) FlFastAlloc(_S, (size_t) optimal * sizeof(CVar), FL_IN_CONST_INIT); if (old_size > 0) { memcpy(na, tbl->arr_, (size_t) old_size * sizeof(CVar)); } @@ -2108,7 +2140,7 @@ static inline void FlSetTableIntImpl(CVar t, int64_t k, CVar v FL_HINT_PARAMS) { } static inline void FlSetTableIntFn(CVar t, int64_t k, CVar v FL_HINT_PARAMS) { - if (LIKELY(t.type_ == VAR_TABLE && (!(t.flag_ & CONST_FLAG) || !__fakelua_init_flag__))) { + if (LIKELY(t.type_ == VAR_TABLE && (!(t.flag_ & CONST_FLAG) || FL_IN_CONST_INIT))) { VarTable *tbl = t.data_.t; uint64_t idx = (uint64_t) k - 1; /* 新旧值都非 nil 时序列长度不变,可跳过缓存维护。*/ @@ -2125,7 +2157,7 @@ static inline void FlSetTableIntFn(CVar t, int64_t k, CVar v FL_HINT_PARAMS) { #define FlSetTableInt(...) FlSetTableIntFn(__VA_ARGS__ FL_HINT_ARGS) static inline void FlSetTableInt_IntFn(CVar t, int64_t k, int64_t v FL_HINT_PARAMS) { - if (LIKELY(t.type_ == VAR_TABLE && (!(t.flag_ & CONST_FLAG) || !__fakelua_init_flag__))) { + if (LIKELY(t.type_ == VAR_TABLE && (!(t.flag_ & CONST_FLAG) || FL_IN_CONST_INIT))) { VarTable *tbl = t.data_.t; uint64_t idx = (uint64_t) k - 1; if (LIKELY(idx < (uint64_t) tbl->arr_size_ && tbl->arr_[idx].type_ != VAR_NIL)) { @@ -2147,7 +2179,7 @@ static inline void FlSetTableInt_IntFn(CVar t, int64_t k, int64_t v FL_HINT_PARA #define FlSetTableInt_Int(...) FlSetTableInt_IntFn(__VA_ARGS__ FL_HINT_ARGS) static inline void FlSetTableInt_FloatFn(CVar t, int64_t k, double v FL_HINT_PARAMS) { - if (LIKELY(t.type_ == VAR_TABLE && (!(t.flag_ & CONST_FLAG) || !__fakelua_init_flag__))) { + if (LIKELY(t.type_ == VAR_TABLE && (!(t.flag_ & CONST_FLAG) || FL_IN_CONST_INIT))) { VarTable *tbl = t.data_.t; uint64_t idx = (uint64_t) k - 1; if (LIKELY(idx < (uint64_t) tbl->arr_size_ && tbl->arr_[idx].type_ != VAR_NIL)) { @@ -2169,7 +2201,7 @@ static inline void FlSetTableInt_FloatFn(CVar t, int64_t k, double v FL_HINT_PAR #define FlSetTableInt_Float(...) FlSetTableInt_FloatFn(__VA_ARGS__ FL_HINT_ARGS) static inline void FlSetTableInt_BoolFn(CVar t, int64_t k, bool b FL_HINT_PARAMS) { - if (LIKELY(t.type_ == VAR_TABLE && (!(t.flag_ & CONST_FLAG) || !__fakelua_init_flag__))) { + if (LIKELY(t.type_ == VAR_TABLE && (!(t.flag_ & CONST_FLAG) || FL_IN_CONST_INIT))) { VarTable *tbl = t.data_.t; uint64_t idx = (uint64_t) k - 1; if (LIKELY(idx < (uint64_t) tbl->arr_size_ && tbl->arr_[idx].type_ != VAR_NIL)) { @@ -2773,7 +2805,7 @@ static inline CVar FlConcatFn(CVar a, CVar b FL_HINT_PARAMS) { if (UNLIKELY(total < la || total < lb)) { FL_RAISE_HINT(_S, "string concatenation result too long"); } - VarString *vs = (VarString *) FlFastAlloc(_S, sizeof(VarString) + total, !__fakelua_init_flag__); + VarString *vs = (VarString *) FlFastAlloc(_S, sizeof(VarString) + total, FL_IN_CONST_INIT); vs->size_ = total; vs->hash_ = 0; memcpy(vs->data_, sa, la); @@ -2791,7 +2823,7 @@ static inline CVar FlStringChar1Fn(int64_t c FL_HINT_PARAMS) { if (UNLIKELY(c < 0 || c > 255)) { FL_RAISE_HINT(_S, "bad argument to string.char: value out of range"); } - VarString *vs = (VarString *) FlFastAlloc(_S, sizeof(VarString) + 1, !__fakelua_init_flag__); + VarString *vs = (VarString *) FlFastAlloc(_S, sizeof(VarString) + 1, FL_IN_CONST_INIT); vs->size_ = 1; vs->hash_ = 0; vs->data_[0] = (char) c; @@ -2817,7 +2849,7 @@ static inline CVar FlStringLower(CVar s) { } else { return FakeluaCallByName(_S, FAKELUA_JIT_TYPE, "string.lower", 1, s); } - VarString *out = (VarString *) FlFastAlloc(_S, sizeof(VarString) + len, !__fakelua_init_flag__); + VarString *out = (VarString *) FlFastAlloc(_S, sizeof(VarString) + len, FL_IN_CONST_INIT); out->size_ = len; out->hash_ = 0; for (int i = 0; i < len; ++i) { @@ -2844,7 +2876,7 @@ static inline CVar FlStringUpper(CVar s) { } else { return FakeluaCallByName(_S, FAKELUA_JIT_TYPE, "string.upper", 1, s); } - VarString *out = (VarString *) FlFastAlloc(_S, sizeof(VarString) + len, !__fakelua_init_flag__); + VarString *out = (VarString *) FlFastAlloc(_S, sizeof(VarString) + len, FL_IN_CONST_INIT); out->size_ = len; out->hash_ = 0; for (int i = 0; i < len; ++i) { @@ -2873,7 +2905,7 @@ static inline CVar FlStringByte1(CVar s, int64_t i) { return FakeluaCallByName(_S, FAKELUA_JIT_TYPE, "string.byte", 2, s, (CVar) {.type_ = VAR_INT, .data_.i = i}); } if (i < 0) i = len + i + 1; - if (i < 1 || i > len) return (CVar) {VAR_NIL}; + if (UNLIKELY(i < 1 || i > len)) return FlAllocMulti(_S, 0); return (CVar) {.type_ = VAR_INT, .data_.i = (unsigned char) src[i - 1]}; } @@ -2892,7 +2924,7 @@ static inline CVar FlStringRep(CVar s, int64_t n) { return FakeluaCallByName(_S, FAKELUA_JIT_TYPE, "string.rep", 2, s, (CVar) {.type_ = VAR_INT, .data_.i = n}); } if (n <= 0 || len == 0) { - VarString *vs = (VarString *) FlFastAlloc(_S, sizeof(VarString), !__fakelua_init_flag__); + VarString *vs = (VarString *) FlFastAlloc(_S, sizeof(VarString) + 1, FL_IN_CONST_INIT); vs->size_ = 0; vs->hash_ = 0; vs->data_[0] = '\0'; @@ -2907,7 +2939,7 @@ static inline CVar FlStringRep(CVar s, int64_t n) { return FakeluaCallByName(_S, FAKELUA_JIT_TYPE, "string.rep", 2, s, (CVar) {.type_ = VAR_INT, .data_.i = n}); } int64_t total = (int64_t) len * n; - VarString *out = (VarString *) FlFastAlloc(_S, sizeof(VarString) + total, !__fakelua_init_flag__); + VarString *out = (VarString *) FlFastAlloc(_S, sizeof(VarString) + total, FL_IN_CONST_INIT); out->size_ = total; out->hash_ = 0; char *dst = out->data_; @@ -2936,7 +2968,7 @@ static inline CVar FlStringReverse(CVar s) { } else { return FakeluaCallByName(_S, FAKELUA_JIT_TYPE, "string.reverse", 1, s); } - VarString *out = (VarString *) FlFastAlloc(_S, sizeof(VarString) + len, !__fakelua_init_flag__); + VarString *out = (VarString *) FlFastAlloc(_S, sizeof(VarString) + len, FL_IN_CONST_INIT); out->size_ = len; out->hash_ = 0; for (int i = 0; i < len; ++i) { @@ -2990,7 +3022,7 @@ static inline CVar FlStringFindPlain(CVar s, CVar pat) { static inline CVar FlFormatInt(int64_t v) { char buf[32]; int n = FlFastItoA(v, buf); - VarString *vs = (VarString *) FlFastAlloc(_S, sizeof(VarString) + n, !__fakelua_init_flag__); + VarString *vs = (VarString *) FlFastAlloc(_S, sizeof(VarString) + n, FL_IN_CONST_INIT); vs->size_ = n; vs->hash_ = 0; memcpy(vs->data_, buf, (size_t) n); @@ -3266,13 +3298,11 @@ static inline CVar FlTableUnpackFn(CVar tbl, int64_t start_i, int64_t end_j FL_H if (UNLIKELY(__fm_b == 0)) { \ FL_RAISE(_S, "modulo by zero"); \ } \ - if (UNLIKELY(__fm_b == (int64_t) -1)) { \ - (result) = 0; \ - } else { \ - int64_t __fm_q; \ - FlFloorDivQuotient(__fm_a, __fm_b, __fm_q); \ - (result) = __fm_a - __fm_b * __fm_q; \ + int64_t __fm_r = UNLIKELY(__fm_b == (int64_t) -1) ? 0 : (__fm_a % __fm_b); \ + if (__fm_r != 0 && ((__fm_r < 0) != (__fm_b < 0))) { \ + __fm_r += __fm_b; \ } \ + (result) = __fm_r; \ } while (0) #define FlModFloat(a, b, result) \ diff --git a/src/compile/compile_common.h b/src/compile/compile_common.h index 617c4a78..2e7cdc8f 100644 --- a/src/compile/compile_common.h +++ b/src/compile/compile_common.h @@ -341,7 +341,43 @@ struct AnalysisResult { // ---- 阶段四:类型推断结果 --------------------------------------------------- enum class TableKeyKind { kString, kInt, kBool, kFloat }; -// 把 Lua 数字字面量(含 0x10 / 1.0 / 0x1p4)分类成 table 键。 +inline bool TryParseLuaIntLiteral(std::string_view s, int64_t &out) { + if (!IsInteger(s)) { + return false; + } + try { + out = ToInteger(s); + return true; + } catch (...) { + return false; + } +} + +inline std::string FormatCInt64Literal(int64_t v) { + if (v == std::numeric_limits::min()) { + return "(-9223372036854775807LL - 1LL)"; + } + if (v > std::numeric_limits::max() || v < std::numeric_limits::min()) { + return std::format("{}LL", v); + } + return std::to_string(v); +} + +inline std::string FormatCDoubleLiteral(double d) { + if (std::isnan(d)) { + return "NAN"; + } + if (!std::isfinite(d)) { + return d < 0.0 ? "(-HUGE_VAL)" : "HUGE_VAL"; + } + std::string s = std::format("{:.17g}", d); + if (s.find('.') == std::string::npos && s.find('e') == std::string::npos && s.find('E') == std::string::npos) { + s += ".0"; + } + return s; +} + +// 把 Lua 数字字面量(含 0x10 / 1.0 / 0x1p4 / 0x1.8)分类成 table 键。 // 能无损落成 int64 的浮点(1.0)按整数键处理,与运行时 NORMALIZE_TABLE_KEY 一致。 inline bool ClassifyLuaNumberKey(const std::string &num_str, TableKeyKind &kind, std::string &canonical, int64_t &int_value, double &float_value) { if (num_str.empty()) return false; @@ -374,7 +410,7 @@ inline bool ClassifyLuaNumberKey(const std::string &num_str, TableKeyKind &kind, } kind = TableKeyKind::kFloat; float_value = d; - canonical = num_str; + canonical = FormatCDoubleLiteral(d); int_value = 0; return true; } catch (...) { @@ -405,7 +441,7 @@ inline bool ClassifyConstNumberExp(const SyntaxTreeInterfacePtr &node, TableKeyK if (int_value == std::numeric_limits::min()) { kind = TableKeyKind::kFloat; float_value = -static_cast(int_value); - canonical = std::format("{:.17g}", float_value); + canonical = FormatCDoubleLiteral(float_value); int_value = 0; } else { int_value = -int_value; @@ -421,10 +457,8 @@ inline bool ClassifyConstNumberExp(const SyntaxTreeInterfacePtr &node, TableKeyK int_value = std::numeric_limits::min(); canonical = std::to_string(int_value); float_value = 0.0; - } else if (!canonical.empty() && canonical.front() == '-') { - canonical = canonical.substr(1); } else { - canonical.insert(canonical.begin(), '-'); + canonical = FormatCDoubleLiteral(float_value); } } return true; @@ -450,7 +484,25 @@ inline bool ConstNumberExpHasFloatSyntax(const SyntaxTreeInterfacePtr &node) { } inline bool ConstNumberExpIsIntValue(TableKeyKind kind, const SyntaxTreeInterfacePtr &node) { - return kind == TableKeyKind::kInt && !ConstNumberExpHasFloatSyntax(node); + if (kind != TableKeyKind::kInt || ConstNumberExpHasFloatSyntax(node)) { + return false; + } + const auto exp = std::dynamic_pointer_cast(node); + if (!exp) { + return false; + } + int64_t dummy = 0; + if (exp->GetExpKind() == ExpKind::kNumber) { + return TryParseLuaIntLiteral(exp->ExpValue(), dummy); + } + if (exp->GetExpKind() == ExpKind::kUnop) { + if (const auto right_exp = std::dynamic_pointer_cast(exp->Right()); right_exp && right_exp->GetExpKind() == ExpKind::kNumber) { + return TryParseLuaIntLiteral("-" + right_exp->ExpValue(), dummy); + } + // Multiple unary minuses on a valid integer expression stay integer (two's-complement wrap in Lua 5.4). + return ConstNumberExpIsIntValue(TableKeyKind::kInt, exp->Right()); + } + return true; } // 值语境(区别于表键归一化)下,把 ClassifyConstNumberExp 的结果还原成 double。 @@ -478,14 +530,6 @@ inline double ConstNumberExpToDouble(TableKeyKind kind, int64_t int_value, doubl return d; } -inline std::string FormatCDoubleLiteral(double d) { - std::string s = std::format("{:.17g}", d); - if (s.find('.') == std::string::npos && s.find('e') == std::string::npos && s.find('E') == std::string::npos) { - s += ".0"; - } - return s; -} - inline std::string EscapeCStringLiteral(const std::string &s) { std::string out; out.reserve(s.size() + 8); diff --git a/src/compile/flex/scanner.cpp b/src/compile/flex/scanner.cpp index 46364095..d7a1c2d5 100644 --- a/src/compile/flex/scanner.cpp +++ b/src/compile/flex/scanner.cpp @@ -902,6 +902,103 @@ YY_DECL // Code run each time yylex is called. loc.step (); + auto scan_short_string = [&]() -> yy::parser::symbol_type { + const char quote = yytext[0]; + loc.end = loc.begin; + loc.columns(1); + const yy::location start_loc = loc; + yyless(1); + + auto peek_char = [&]() -> int { + if ((yy_hold_char) != YY_END_OF_BUFFER_CHAR || (yy_c_buf_p) < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)]) { + return static_cast(yy_hold_char); + } + *(yy_c_buf_p) = (yy_hold_char); + (yytext_ptr) = (yy_c_buf_p); + ++(yy_c_buf_p); + switch (yy_get_next_buffer()) { + case EOB_ACT_LAST_MATCH: + yyrestart(yyin); + [[fallthrough]]; + case EOB_ACT_END_OF_FILE: + return -1; + case EOB_ACT_CONTINUE_SCAN: + (yy_c_buf_p) = (yytext_ptr); + (yy_hold_char) = *(yy_c_buf_p); + *(yy_c_buf_p) = '\0'; + return static_cast(yy_hold_char); + } + return -1; + }; + + auto advance_char = [&]() -> int { + const int c = peek_char(); + if (c < 0) { + return -1; + } + *(yy_c_buf_p) = '\0'; + (yy_hold_char) = *++(yy_c_buf_p); + if (c == '\n') { + ++yylineno; + } + return c; + }; + + std::string raw; + raw.push_back(quote); + for (;;) { + const int c = advance_char(); + if (c < 0 || c == '\n' || c == '\r') { + throw yy::parser::syntax_error(start_loc, "unfinished string"); + } + if (c == static_cast(quote)) { + loc.columns(1); + raw.push_back(quote); + return yy::parser::make_STRING(raw, loc); + } + if (c == '\\') { + loc.columns(1); + const int esc = advance_char(); + if (esc < 0) { + throw yy::parser::syntax_error(start_loc, "unfinished string"); + } + if (esc == '\n' || esc == '\r') { + const int next_nl = peek_char(); + if ((next_nl == '\n' || next_nl == '\r') && next_nl != esc) { + advance_char(); + } + loc.lines(1); + raw += "\\n"; + } else if (esc == 'z') { + loc.columns(1); + for (;;) { + const int w = peek_char(); + if (w != ' ' && w != '\t' && w != '\f' && w != '\v' && w != '\n' && w != '\r') { + break; + } + advance_char(); + if (w == '\n' || w == '\r') { + const int w2 = peek_char(); + if ((w2 == '\n' || w2 == '\r') && w2 != w) { + advance_char(); + } + loc.lines(1); + } else { + loc.columns(1); + } + } + } else { + loc.columns(1); + raw.push_back('\\'); + raw.push_back(static_cast(esc)); + } + } else { + loc.columns(1); + raw.push_back(static_cast(c)); + } + } + }; + /* 长注释按 Lua 的长括号层级处理:--[[ 配 ]],--[==[ 配 ]==],层级不匹配的 ]] 只是普通内容。传统的 --]] 收尾依然有效,因为其中的 ]] 就是 0 级闭括号。 */ @@ -1344,13 +1441,19 @@ case 69: /* rule 69 can match eol */ YY_RULE_SETUP #line 162 "scanner.l" -{ TrackStringLocation(loc, std::string_view(yytext, static_cast(yyleng))); return yy::parser::make_STRING(yytext, loc); } +{ + if (yytext[0] == '"' || yytext[0] == '\'') { + return scan_short_string(); + } + TrackStringLocation(loc, std::string_view(yytext, static_cast(yyleng))); + return yy::parser::make_STRING(std::string(yytext, static_cast(yyleng)), loc); +} YY_BREAK -/* A quote reaches this fallback only when no complete short string matched. */ +/* A quote reaches this fallback when a short string contains escaped newlines or is unfinished. */ case 70: YY_RULE_SETUP #line 165 "scanner.l" -{ throw yy::parser::syntax_error(loc, "unfinished string"); } +{ return scan_short_string(); } YY_BREAK case 71: YY_RULE_SETUP diff --git a/src/compile/flex/scanner.l b/src/compile/flex/scanner.l index 23c3da28..2fae95e3 100644 --- a/src/compile/flex/scanner.l +++ b/src/compile/flex/scanner.l @@ -52,8 +52,8 @@ void TrackStringLocation(yy::location &loc, std::string_view text) { /* 短字符串里不能出现裸换行(\n 和 \r 都算),与 Lua 的 "unfinished string" 一致。 需要跨行的内容用 [[ ]] 长字符串或转义写法。 */ -string1 \"((?:\\\"|[^\"\n\r])*)\" -string2 \'((\\'|[^'\n\r])*)\' +string1 \"(\\.|[^\"\\\n\r])*\" +string2 \'(\\.|[^'\\\n\r])*\' string3 \[\[([^\]]|(\][^\]]))*\]\] string {string1}|{string2}|{string3} name [_a-zA-Z][_a-zA-Z0-9]* @@ -75,6 +75,103 @@ number {num1}|{num2} yy::location& loc = location_; // Code run each time yylex is called. loc.step (); + + auto scan_short_string = [&]() -> yy::parser::symbol_type { + const char quote = yytext[0]; + loc.end = loc.begin; + loc.columns(1); + const yy::location start_loc = loc; + yyless(1); + + auto peek_char = [&]() -> int { + if ((yy_hold_char) != YY_END_OF_BUFFER_CHAR || (yy_c_buf_p) < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)]) { + return static_cast(yy_hold_char); + } + *(yy_c_buf_p) = (yy_hold_char); + (yytext_ptr) = (yy_c_buf_p); + ++(yy_c_buf_p); + switch (yy_get_next_buffer()) { + case EOB_ACT_LAST_MATCH: + yyrestart(yyin); + [[fallthrough]]; + case EOB_ACT_END_OF_FILE: + return -1; + case EOB_ACT_CONTINUE_SCAN: + (yy_c_buf_p) = (yytext_ptr); + (yy_hold_char) = *(yy_c_buf_p); + *(yy_c_buf_p) = '\0'; + return static_cast(yy_hold_char); + } + return -1; + }; + + auto advance_char = [&]() -> int { + const int c = peek_char(); + if (c < 0) { + return -1; + } + *(yy_c_buf_p) = '\0'; + (yy_hold_char) = *++(yy_c_buf_p); + if (c == '\n') { + ++yylineno; + } + return c; + }; + + std::string raw; + raw.push_back(quote); + for (;;) { + const int c = advance_char(); + if (c < 0 || c == '\n' || c == '\r') { + throw yy::parser::syntax_error(start_loc, "unfinished string"); + } + if (c == static_cast(quote)) { + loc.columns(1); + raw.push_back(quote); + return yy::parser::make_STRING(raw, loc); + } + if (c == '\\') { + loc.columns(1); + const int esc = advance_char(); + if (esc < 0) { + throw yy::parser::syntax_error(start_loc, "unfinished string"); + } + if (esc == '\n' || esc == '\r') { + const int next_nl = peek_char(); + if ((next_nl == '\n' || next_nl == '\r') && next_nl != esc) { + advance_char(); + } + loc.lines(1); + raw += "\\n"; + } else if (esc == 'z') { + loc.columns(1); + for (;;) { + const int w = peek_char(); + if (w != ' ' && w != '\t' && w != '\f' && w != '\v' && w != '\n' && w != '\r') { + break; + } + advance_char(); + if (w == '\n' || w == '\r') { + const int w2 = peek_char(); + if ((w2 == '\n' || w2 == '\r') && w2 != w) { + advance_char(); + } + loc.lines(1); + } else { + loc.columns(1); + } + } + } else { + loc.columns(1); + raw.push_back('\\'); + raw.push_back(static_cast(esc)); + } + } else { + loc.columns(1); + raw.push_back(static_cast(c)); + } + } + }; %} /* 长注释按 Lua 的长括号层级处理:--[[ 配 ]],--[==[ 配 ]==],层级不匹配的 @@ -158,10 +255,16 @@ number {num1}|{num2} {name} return yy::parser::make_IDENTIFIER(yytext, loc); -{string} { TrackStringLocation(loc, std::string_view(yytext, static_cast(yyleng))); return yy::parser::make_STRING(yytext, loc); } +{string} { + if (yytext[0] == '"' || yytext[0] == '\'') { + return scan_short_string(); + } + TrackStringLocation(loc, std::string_view(yytext, static_cast(yyleng))); + return yy::parser::make_STRING(std::string(yytext, static_cast(yyleng)), loc); + } - /* A quote reaches this fallback only when no complete short string matched. */ -[\"'] { throw yy::parser::syntax_error(loc, "unfinished string"); } + /* A quote reaches this fallback when a short string contains escaped newlines or is unfinished. */ +[\"'] { return scan_short_string(); } . { throw yy::parser::syntax_error(loc, "invalid character: [" + std::string(yytext) + "]"); } diff --git a/src/compile/my_flexer.cpp b/src/compile/my_flexer.cpp index f7f17c14..710d5266 100644 --- a/src/compile/my_flexer.cpp +++ b/src/compile/my_flexer.cpp @@ -18,13 +18,13 @@ void MyFlexer::InputFile(const std::string &file) { switch_streams(&file_, nullptr); } -// 输入字符串进行解析,通过生成临时文件来实现 +// 输入字符串进行解析 void MyFlexer::InputString(const std::string &str) { is_string_ = true; filename_ = GenerateTmpFile(str); location_.initialize(&filename_); set_debug(0); - string_ = std::istringstream(str.data(), std::ios::binary); + string_ = std::istringstream(str, std::ios::binary); switch_streams(&string_, nullptr); } @@ -54,14 +54,10 @@ std::string MyFlexer::RemoveQuotes(const std::string &str) { } } -// 将输入的字符串写入系统临时文件,便于后续 Flex 读取 +// 为字符串输入分配唯一文件名标识(不在磁盘上创建空临时文件) std::string MyFlexer::GenerateTmpFile(const std::string &str) { - std::string fileName = GenerateTmpFilename("fakelua_myflexer_", ".lua"); - std::ofstream file(fileName); - DEBUG_ASSERT(file.is_open()); - file << str; - file.close(); - return fileName; + (void) str; + return GenerateTmpFilename("fakelua_myflexer_", ".lua"); } }// namespace fakelua diff --git a/src/compile/preprocessor.cpp b/src/compile/preprocessor.cpp index 65cddad9..702cf9fc 100644 --- a/src/compile/preprocessor.cpp +++ b/src/compile/preprocessor.cpp @@ -93,13 +93,13 @@ void PreProcessor::Process(const ParseResult &pr, const CompileConfig &cfg) { // 拆分多赋值语句 比如 'a, b = 1, 2' to 'a = 1; b = 2;' PreprocessSplitAssigns(chunk); - if (cfg.debug_mode) { + if (cfg.debug_mode && s_ && s_->GetLogLevel() <= LogLevel::Debug) { DumpDebugFile(chunk, debug_step++); } // 替换table赋值语句 比如 'a.b.c = 1' to 'FAKELUA_SET_TABLE(a.b, "c", 1)' PreprocessTableAssigns(chunk); - if (cfg.debug_mode) { + if (cfg.debug_mode && s_ && s_->GetLogLevel() <= LogLevel::Debug) { DumpDebugFile(chunk, debug_step); } diff --git a/src/compile/semantic_analysis.cpp b/src/compile/semantic_analysis.cpp index ce1eaedf..137aeecc 100644 --- a/src/compile/semantic_analysis.cpp +++ b/src/compile/semantic_analysis.cpp @@ -479,11 +479,11 @@ struct ReturnCountGraph { for (const auto &ff: file_funcs) { int value = eff.contains(ff.node) ? eff.at(ff.node) : kTainted; - if (value < 0) { + if (value < 0 || FileCount(ff.name) > 1) { value = -1; } ar.function_effective_returns[ff.name] = value; - ar.function_max_returns[ff.name] = ff.max_returns; + ar.function_max_returns[ff.name] = FileCount(ff.name) > 1 ? -1 : ff.max_returns; } for (const auto &[node, info]: funcs) { (void) node; @@ -726,9 +726,14 @@ void SemanticAnalysis::ValidateConstInExprs(const SyntaxTreeInterfacePtr &node, // Lua 在编译期就拒绝对 变量赋值,这里按块作用域收集 const 名字后做同样的检查。 // 嵌套函数(LocalFunction / FunctionDef / Function)继承外层词法 const(upvalue), // 形参与同名 local 可遮蔽;块内 do/for/if 等嵌套作用域同样尊重遮蔽。 -void SemanticAnalysis::ValidateConstAssignInBlock(const SyntaxTreeInterfacePtr &chunk, std::unordered_set const_names) { +void SemanticAnalysis::ValidateConstAssignInBlock(const SyntaxTreeInterfacePtr &chunk, std::unordered_set const_names, const SyntaxTreeInterfacePtr &trailing_until_exp) { const auto blk = std::dynamic_pointer_cast(chunk); - if (!blk) return; + if (!blk) { + if (trailing_until_exp) { + ValidateConstInExprs(trailing_until_exp, const_names); + } + return; + } for (const auto &stmt: blk->Stmts()) { switch (stmt->Type()) { @@ -781,8 +786,7 @@ void SemanticAnalysis::ValidateConstAssignInBlock(const SyntaxTreeInterfacePtr & } case SyntaxTreeType::Repeat: { const auto r = std::dynamic_pointer_cast(stmt); - ValidateConstAssignInBlock(r->Block(), const_names); - ValidateConstInExprs(r->Exp(), const_names); + ValidateConstAssignInBlock(r->Block(), const_names, r->Exp()); break; } case SyntaxTreeType::ForLoop: { @@ -842,6 +846,9 @@ void SemanticAnalysis::ValidateConstAssignInBlock(const SyntaxTreeInterfacePtr & break; } } + if (trailing_until_exp) { + ValidateConstInExprs(trailing_until_exp, const_names); + } } void SemanticAnalysis::CheckNode(const SyntaxTreeInterfacePtr &node, const AnalysisResult &ar) { @@ -995,12 +1002,51 @@ void SemanticAnalysis::CollectGotosInStmt(const SyntaxTreeInterfacePtr &stmt, st } } +void SemanticAnalysis::ValidateGotoInExprs(const SyntaxTreeInterfacePtr &node) { + if (!node) return; + WalkSyntaxTreePruned(node, [this](const SyntaxTreeInterfacePtr &n) -> bool { + if (!n) return false; + if (n->Type() == SyntaxTreeType::FunctionDef) { + std::unordered_map func_labels; + const auto fb = std::dynamic_pointer_cast(std::dynamic_pointer_cast(n)->Funcbody()); + if (fb) ValidateGotoInBlock(fb->Block(), func_labels, 0); + return false; + } + if (n->Type() == SyntaxTreeType::Function) { + std::unordered_map func_labels; + const auto fb = std::dynamic_pointer_cast(std::dynamic_pointer_cast(n)->Funcbody()); + if (fb) ValidateGotoInBlock(fb->Block(), func_labels, 0); + return false; + } + if (n->Type() == SyntaxTreeType::LocalFunction) { + std::unordered_map func_labels; + const auto fb = std::dynamic_pointer_cast(std::dynamic_pointer_cast(n)->Funcbody()); + if (fb) ValidateGotoInBlock(fb->Block(), func_labels, 0); + return false; + } + return true; + }); +} + void SemanticAnalysis::ValidateGotoInBlock(const SyntaxTreeInterfacePtr &chunk, std::unordered_map visible_labels, int loop_depth) { const auto blk = std::dynamic_pointer_cast(chunk); if (!blk) return; CollectBlockLabels(chunk, visible_labels); + auto is_synthetic_local_stmt = [](const SyntaxTreeInterfacePtr &s) -> bool { + if (!s || s->Type() != SyntaxTreeType::LocalVar) return false; + const auto lv = std::dynamic_pointer_cast(s); + const auto nl = lv ? std::dynamic_pointer_cast(lv->Namelist()) : nullptr; + if (!nl || nl->Names().empty()) return false; + for (const auto &n: nl->Names()) { + if (!n.starts_with("__fakelua_tmp_") && !n.starts_with("__fakelua_lhs_")) { + return false; + } + } + return true; + }; + std::unordered_map label_index; for (size_t i = 0; i < blk->Stmts().size(); ++i) { if (blk->Stmts()[i]->Type() == SyntaxTreeType::Label) { @@ -1011,7 +1057,7 @@ void SemanticAnalysis::ValidateGotoInBlock(const SyntaxTreeInterfacePtr &chunk, std::vector local_positions; for (size_t i = 0; i < blk->Stmts().size(); ++i) { const auto st = blk->Stmts()[i]->Type(); - if (st == SyntaxTreeType::LocalVar || st == SyntaxTreeType::LocalFunction) { + if ((st == SyntaxTreeType::LocalVar && !is_synthetic_local_stmt(blk->Stmts()[i])) || st == SyntaxTreeType::LocalFunction) { local_positions.push_back(i); } } @@ -1026,6 +1072,35 @@ void SemanticAnalysis::ValidateGotoInBlock(const SyntaxTreeInterfacePtr &chunk, } }; + auto collect_continues_for_current_loop = [](const SyntaxTreeInterfacePtr &root, std::vector &out) { + std::function rec = [&](const SyntaxTreeInterfacePtr &s) { + if (!s) return; + switch (s->Type()) { + case SyntaxTreeType::Continue: + out.push_back(s); + break; + case SyntaxTreeType::Block: { + if (const auto b = std::dynamic_pointer_cast(s)) { + for (const auto &child: b->Stmts()) rec(child); + } + break; + } + case SyntaxTreeType::If: { + const auto if_s = std::dynamic_pointer_cast(s); + rec(if_s->Block()); + if (const auto elseifs = std::dynamic_pointer_cast(if_s->ElseIfs())) { + for (const auto &eblk: elseifs->ElseifBlocks()) rec(eblk); + } + rec(if_s->ElseBlock()); + break; + } + default: + break; + } + }; + rec(root); + }; + for (size_t i = 0; i < blk->Stmts().size(); ++i) { const auto &stmt = blk->Stmts()[i]; if (stmt->Type() == SyntaxTreeType::Goto) { @@ -1071,25 +1146,85 @@ void SemanticAnalysis::ValidateGotoInBlock(const SyntaxTreeInterfacePtr &chunk, if (stmt->Type() == SyntaxTreeType::Block) { ValidateGotoInBlock(stmt, visible_labels, loop_depth); } else if (stmt->Type() == SyntaxTreeType::While) { - ValidateGotoInBlock(std::dynamic_pointer_cast(stmt)->Block(), visible_labels, loop_depth + 1); + const auto w = std::dynamic_pointer_cast(stmt); + ValidateGotoInExprs(w->Exp()); + ValidateGotoInBlock(w->Block(), visible_labels, loop_depth + 1); } else if (stmt->Type() == SyntaxTreeType::Repeat) { - ValidateGotoInBlock(std::dynamic_pointer_cast(stmt)->Block(), visible_labels, loop_depth + 1); + const auto rep = std::dynamic_pointer_cast(stmt); + if (const auto rep_blk = std::dynamic_pointer_cast(rep->Block())) { + std::unordered_set live_at_until; + WalkSyntaxTree(rep->Exp(), [&](const SyntaxTreeInterfacePtr &n) { + if (n && n->Type() == SyntaxTreeType::Var) { + const auto v = std::dynamic_pointer_cast(n); + if (v && v->GetVarKind() == VarKind::kSimple) { + live_at_until.insert(v->GetName()); + } + } + }); + WalkSyntaxTree(rep_blk, [&](const SyntaxTreeInterfacePtr &n) { + if (!n) return; + if (n->Type() == SyntaxTreeType::FunctionDef || n->Type() == SyntaxTreeType::LocalFunction || n->Type() == SyntaxTreeType::Function) { + WalkSyntaxTree(n, [&](const SyntaxTreeInterfacePtr &inner) { + if (inner && inner->Type() == SyntaxTreeType::Var) { + const auto v = std::dynamic_pointer_cast(inner); + if (v && v->GetVarKind() == VarKind::kSimple) { + live_at_until.insert(v->GetName()); + } + } + }); + } + }); + const auto &rep_stmts = rep_blk->Stmts(); + for (size_t si = 0; si < rep_stmts.size(); ++si) { + std::vector continues; + collect_continues_for_current_loop(rep_stmts[si], continues); + if (continues.empty()) continue; + for (size_t lp = si + 1; lp < rep_stmts.size(); ++lp) { + const auto &s_lp = rep_stmts[lp]; + if (s_lp->Type() == SyntaxTreeType::LocalVar && !is_synthetic_local_stmt(s_lp)) { + const auto lv = std::dynamic_pointer_cast(s_lp); + if (const auto nl = std::dynamic_pointer_cast(lv->Namelist())) { + for (const auto &lname: nl->Names()) { + if (live_at_until.contains(lname)) { + ThrowError("'continue' jumps over local variable declaration", continues.front()); + } + } + } + } else if (s_lp->Type() == SyntaxTreeType::LocalFunction) { + const auto lf = std::dynamic_pointer_cast(s_lp); + if (live_at_until.contains(lf->Name())) { + ThrowError("'continue' jumps over local variable declaration", continues.front()); + } + } + } + } + } + ValidateGotoInBlock(rep->Block(), visible_labels, loop_depth + 1); + ValidateGotoInExprs(rep->Exp()); } else if (stmt->Type() == SyntaxTreeType::If) { const auto if_stmt = std::dynamic_pointer_cast(stmt); + ValidateGotoInExprs(if_stmt->Exp()); ValidateGotoInBlock(if_stmt->Block(), visible_labels, loop_depth); if (if_stmt->ElseIfs()) { const auto elseif_list = std::dynamic_pointer_cast(if_stmt->ElseIfs()); if (elseif_list) { - for (const auto &elseif_blk: elseif_list->ElseifBlocks()) { - ValidateGotoInBlock(elseif_blk, visible_labels, loop_depth); + for (size_t ei = 0; ei < elseif_list->ElseifSize(); ++ei) { + ValidateGotoInExprs(elseif_list->ElseifExp(ei)); + ValidateGotoInBlock(elseif_list->ElseifBlock(ei), visible_labels, loop_depth); } } } if (if_stmt->ElseBlock()) ValidateGotoInBlock(if_stmt->ElseBlock(), visible_labels, loop_depth); } else if (stmt->Type() == SyntaxTreeType::ForLoop) { - ValidateGotoInBlock(std::dynamic_pointer_cast(stmt)->Block(), visible_labels, loop_depth + 1); + const auto fl = std::dynamic_pointer_cast(stmt); + ValidateGotoInExprs(fl->ExpBegin()); + ValidateGotoInExprs(fl->ExpEnd()); + ValidateGotoInExprs(fl->ExpStep()); + ValidateGotoInBlock(fl->Block(), visible_labels, loop_depth + 1); } else if (stmt->Type() == SyntaxTreeType::ForIn) { - ValidateGotoInBlock(std::dynamic_pointer_cast(stmt)->Block(), visible_labels, loop_depth + 1); + const auto fi = std::dynamic_pointer_cast(stmt); + ValidateGotoInExprs(fi->Explist()); + ValidateGotoInBlock(fi->Block(), visible_labels, loop_depth + 1); } else if (stmt->Type() == SyntaxTreeType::Function) { std::unordered_map func_labels; const auto fb = std::dynamic_pointer_cast(std::dynamic_pointer_cast(stmt)->Funcbody()); @@ -1098,6 +1233,16 @@ void SemanticAnalysis::ValidateGotoInBlock(const SyntaxTreeInterfacePtr &chunk, std::unordered_map func_labels; const auto fb = std::dynamic_pointer_cast(std::dynamic_pointer_cast(stmt)->Funcbody()); if (fb) ValidateGotoInBlock(fb->Block(), func_labels, 0); + } else if (stmt->Type() == SyntaxTreeType::LocalVar) { + ValidateGotoInExprs(std::dynamic_pointer_cast(stmt)->Explist()); + } else if (stmt->Type() == SyntaxTreeType::Assign) { + const auto assign = std::dynamic_pointer_cast(stmt); + ValidateGotoInExprs(assign->Varlist()); + ValidateGotoInExprs(assign->Explist()); + } else if (stmt->Type() == SyntaxTreeType::Return) { + ValidateGotoInExprs(std::dynamic_pointer_cast(stmt)->Explist()); + } else if (stmt->Type() == SyntaxTreeType::FunctionCall) { + ValidateGotoInExprs(stmt); } } } @@ -3556,6 +3701,29 @@ void RegisterPeakChecker::Walk(const ParseResult &pr, AnalysisResult &ar) { } } + // 形参、局部变量、循环变量或嵌套 local function 遮蔽了文件级同名函数时, + // 不能把该调用点当成已知返回数的文件级函数。 + for (const SyntaxTreeInterface *exp_ptr: ar.function_call_exps) { + const auto *exp = dynamic_cast(exp_ptr); + if (!exp || exp->GetExpKind() != ExpKind::kPrefixExp || !exp->Right()) continue; + const auto *pe = dynamic_cast(exp->Right().get()); + if (!pe || pe->GetPrefixKind() != PrefixExpKind::kFunctionCall || !pe->GetValue()) continue; + const auto *fc = dynamic_cast(pe->GetValue().get()); + if (!fc || !fc->Name().empty() || !fc->prefixexp()) continue; + const auto *callee_pe = dynamic_cast(fc->prefixexp().get()); + if (!callee_pe || callee_pe->GetPrefixKind() != PrefixExpKind::kVar || !callee_pe->GetValue()) continue; + const auto *callee_var = dynamic_cast(callee_pe->GetValue().get()); + if (!callee_var || callee_var->GetVarKind() != VarKind::kSimple) continue; + if (const auto it = var_to_def_map_.find(callee_var); it != var_to_def_map_.end()) { + const VarDef *def = it->second; + const bool is_file_local_func = def && def->defining_func == nullptr && def->def_node != nullptr && def->def_node->Type() == SyntaxTreeType::LocalFunction; + if (!is_file_local_func) { + ar.callee_names[exp_ptr] = ""; + ar.callee_names[fc] = ""; + } + } + } + // 先登记所有文件级函数的签名:调用点可能在函数定义之前,等 CompileFunction 再登记就漏了。 for (const auto &func: all_funcs_) { if (func->parent != nullptr) continue; diff --git a/src/compile/semantic_analysis.h b/src/compile/semantic_analysis.h index 171a29a1..5b771fb9 100644 --- a/src/compile/semantic_analysis.h +++ b/src/compile/semantic_analysis.h @@ -33,9 +33,10 @@ class SemanticAnalysis { void CheckNode(const SyntaxTreeInterfacePtr &node, const AnalysisResult &ar); void CheckGotoOrLabel(const SyntaxTreeInterfacePtr &node); void ValidateGotoInBlock(const SyntaxTreeInterfacePtr &chunk, std::unordered_map visible_labels, int loop_depth); + void ValidateGotoInExprs(const SyntaxTreeInterfacePtr &node); void CollectGotosInStmt(const SyntaxTreeInterfacePtr &stmt, std::vector> &out); void CollectGotosInBlock(const SyntaxTreeInterfacePtr &block, std::vector> &out); - void ValidateConstAssignInBlock(const SyntaxTreeInterfacePtr &chunk, std::unordered_set const_names); + void ValidateConstAssignInBlock(const SyntaxTreeInterfacePtr &chunk, std::unordered_set const_names, const SyntaxTreeInterfacePtr &trailing_until_exp = nullptr); // 在表达式树中查找匿名 FunctionDef,并按外层词法 const 集合校验其函数体。 void ValidateConstInExprs(const SyntaxTreeInterfacePtr &node, const std::unordered_set &const_names); // 进入函数体:继承外层 const,参数名 / extra_shadow 遮蔽同名 const。 diff --git a/src/compile/type_inferencer.cpp b/src/compile/type_inferencer.cpp index 6d2e7621..005d3a26 100644 --- a/src/compile/type_inferencer.cpp +++ b/src/compile/type_inferencer.cpp @@ -6,6 +6,7 @@ #include "compile/syntax_tree.h" #include "fakelua.h" +#include "state/state.h" #include "util/common.h" #include "util/file_util.h" @@ -340,21 +341,37 @@ void TypeInferencer::TypeEnvironment::ExitScope() { } } -void TypeInferencer::TypeEnvironment::Define(const std::string &name, const InferredType type, SyntaxTreeInterface *init_node) { - scopes_.back()[name] = EnvEntry{type, init_node}; +void TypeInferencer::TypeEnvironment::Define(const std::string &name, const InferredType type, SyntaxTreeInterface *init_node, const SyntaxTreeInterface *decl_node, const size_t decl_slot, + const bool is_param) { + scopes_.back()[name] = EnvEntry{type, init_node, decl_node, decl_slot, is_param}; } -InferredType TypeInferencer::TypeEnvironment::Update(const std::string &name, const InferredType type, EvalTypeSnapshot ¤t_map) { +InferredType TypeInferencer::TypeEnvironment::Update(const std::string &name, const InferredType type, EvalTypeSnapshot ¤t_map, const bool skip_post_processing, DeclOverrideMap *decl_overrides, + bool *any_widened, const bool loop_carried) { for (auto &scope: std::views::reverse(scopes_)) { if (const auto found = scope.find(name); found != scope.end()) { const InferredType old_type = found->second.type; const InferredType merged = MergeType(old_type, type); found->second.type = merged; - // 逆向传播:当变量类型退化为 T_DYNAMIC(如后续赋了非数值类型)时, - // 将初始声明/赋值表达式的类型也退化为 T_DYNAMIC,防止 CGen 将其声明为 C 的原生强类型。 - if (merged == T_DYNAMIC && old_type != T_DYNAMIC && found->second.init_node != nullptr) { - current_map[found->second.init_node] = T_DYNAMIC; + // 声明的 C 类型跟最终存储对齐(直线上 a = "hello" 也要把 a 收成 CVar)。 + // 不动点重跑只服务循环回边:直线上更早的表达式保持当时的类型。 + if (merged != old_type) { + if (!skip_post_processing && found->second.init_node != nullptr) { + current_map[found->second.init_node] = merged; + } + if (loop_carried && decl_overrides != nullptr && found->second.decl_node != nullptr) { + const DeclOverrideKey key{found->second.decl_node, name, found->second.decl_slot}; + const auto it = decl_overrides->find(key); + const InferredType prev_ov = (it != decl_overrides->end()) ? it->second : old_type; + const InferredType next_ov = MergeType(prev_ov, merged); + if (it == decl_overrides->end() || it->second != next_ov) { + (*decl_overrides)[key] = next_ov; + if (any_widened != nullptr) { + *any_widened = true; + } + } + } } return merged; } @@ -371,6 +388,15 @@ bool TypeInferencer::TypeEnvironment::Has(const std::string &name) const { return false; } +bool TypeInferencer::TypeEnvironment::IsParamBinding(const std::string &name) const { + for (const auto &scope: std::views::reverse(scopes_)) { + if (const auto found = scope.find(name); found != scope.end()) { + return found->second.is_param; + } + } + return false; +} + InferredType TypeInferencer::TypeEnvironment::Lookup(const std::string &name) const { for (const auto &scope: std::views::reverse(scopes_)) { if (const auto found = scope.find(name); found != scope.end()) { @@ -443,7 +469,7 @@ InferResult TypeInferencer::InferTypes(const ParseResult &pr, const AnalysisResu InferSpecializationReturnTypes(ir, math_func_info, func_ret_cache); } - if (cfg.debug_mode) { + if (cfg.debug_mode && s_ && s_->GetLogLevel() <= LogLevel::Debug) { DumpTypesToTmpFile(pr, ir); } @@ -534,16 +560,31 @@ InferredType TypeInferencer::InferNode(const SyntaxTreeInterfacePtr &node, Trave } case SyntaxTreeType::FuncBody: { const auto funcbody = std::dynamic_pointer_cast(node); - tctx.env.EnterScope(); - if (const auto parlist = std::dynamic_pointer_cast(funcbody->Parlist())) { - if (const auto namelist = std::dynamic_pointer_cast(parlist->Namelist())) { - for (const auto &name: namelist->Names()) { - tctx.env.Define(name, T_DYNAMIC); + const auto block_ptr = std::dynamic_pointer_cast(funcbody->Block()); + DeclOverrideMap local_overrides; + EvalTypeSnapshot func_map; + for (int round = 0; round < kMaxSpecIterations; ++round) { + func_map.clear(); + tctx.env.EnterScope(); + if (const auto parlist = std::dynamic_pointer_cast(funcbody->Parlist())) { + if (const auto namelist = std::dynamic_pointer_cast(parlist->Namelist())) { + const auto &pnames = namelist->Names(); + for (size_t pi = 0; pi < pnames.size(); ++pi) { + tctx.env.Define(pnames[pi], T_DYNAMIC, nullptr, parlist.get(), pi, true); + } } } + TraversalContext body_tctx{func_map, tctx.env, tctx.ctx, tctx.var_define_nodes, tctx.shadowed_decls, std::move(local_overrides), false}; + InferBlock(block_ptr, false, body_tctx); + local_overrides = std::move(body_tctx.decl_type_overrides); + tctx.env.ExitScope(); + if (!body_tctx.any_decl_widened) { + break; + } + } + for (const auto &[k, v]: func_map) { + current_map[k] = v; } - InferBlock(std::dynamic_pointer_cast(funcbody->Block()), false, tctx); - tctx.env.ExitScope(); return RecordType(current_map, node.get(), T_UNKNOWN); } case SyntaxTreeType::Return: { @@ -658,8 +699,11 @@ InferredType TypeInferencer::InferLocalVar(const std::shared_ptrcaptured_decl_vars.contains({local_var.get(), names[i]})) { type = T_DYNAMIC; } + if (const auto ov_it = tctx.decl_type_overrides.find({local_var.get(), names[i], i}); ov_it != tctx.decl_type_overrides.end()) { + type = TypeEnvironment::MergeType(type, ov_it->second); + } SyntaxTreeInterface *init_node = (i < exps.size()) ? exps[i].get() : nullptr; - tctx.env.Define(names[i], type, init_node); + tctx.env.Define(names[i], type, init_node, local_var.get(), i, false); // 文件顶层局部变量(非试推断且作用域深度 <= 2): // 数值类型记入 file_level_types_,供 RunTrialInference 重置 env 后重注入。 // 绑定语义等同 C++ const:字面量与复杂初值(预处理降为 nil,真值在 @@ -703,11 +747,11 @@ InferredType TypeInferencer::InferAssign(const std::shared_ptr const InferredType rhs_type = InferNode(explist->Exps()[0], tctx); if (ar_ && ar_->captured_var_nodes.contains(var.get())) { - current = tctx.env.Update(name, T_DYNAMIC, current_map); + current = tctx.env.Update(name, T_DYNAMIC, current_map, tctx.SkipPostProcessing(), &tctx.decl_type_overrides, &tctx.any_decl_widened, tctx.loop_depth > 0); } else if (tctx.IsPinnedVar(name)) { current = tctx.env.Lookup(name); } else { - current = tctx.env.Update(name, rhs_type, current_map); + current = tctx.env.Update(name, rhs_type, current_map, tctx.SkipPostProcessing(), &tctx.decl_type_overrides, &tctx.any_decl_widened, tctx.loop_depth > 0); } if (const auto *init = tctx.env.LookupInitNode(name)) { @@ -751,12 +795,17 @@ InferredType TypeInferencer::InferForLoop(const std::shared_ptrExpStep() || step_type == T_INT) && (end_type == T_INT || end_type == T_FLOAT); const bool is_captured_loop = ar_ && ar_->captured_decl_vars.contains({for_loop.get(), for_loop->Name()}); - const InferredType loop_var_type = is_captured_loop ? T_DYNAMIC : (lua_int_loop ? T_INT : (all_numeric_boundaries ? T_FLOAT : T_DYNAMIC)); + InferredType loop_var_type = is_captured_loop ? T_DYNAMIC : (lua_int_loop ? T_INT : (all_numeric_boundaries ? T_FLOAT : T_DYNAMIC)); + if (const auto ov_it = tctx.decl_type_overrides.find({for_loop.get(), for_loop->Name(), 0}); ov_it != tctx.decl_type_overrides.end()) { + loop_var_type = TypeEnvironment::MergeType(loop_var_type, ov_it->second); + } auto ¤t_map = tctx.current_map; tctx.env.EnterScope(); - tctx.env.Define(for_loop->Name(), loop_var_type, for_loop.get()); + tctx.env.Define(for_loop->Name(), loop_var_type, for_loop.get(), for_loop.get(), 0, false); + ++tctx.loop_depth; InferBlock(std::dynamic_pointer_cast(for_loop->Block()), false, tctx); + --tctx.loop_depth; // 循环体内可能对循环变量重新赋值(例如 `a = "test"`),导致其类型 // 从初始的 T_INT/T_FLOAT 拓宽为 T_DYNAMIC。此处重新查询循环变量的 // 最终类型,以便 CGen 决定生成原生整型/浮点快路径还是 CVar 动态路径。 @@ -776,14 +825,18 @@ InferredType TypeInferencer::InferForIn(const std::shared_ptr & for (const auto &name: namelist->Names()) { tctx.env.Define(name, T_DYNAMIC); } + ++tctx.loop_depth; InferBlock(std::dynamic_pointer_cast(for_in->Block()), false, tctx); + --tctx.loop_depth; tctx.env.ExitScope(); return RecordType(tctx.current_map, for_in.get(), T_UNKNOWN); } InferredType TypeInferencer::InferWhile(const std::shared_ptr &while_stmt, TraversalContext &tctx) { InferNode(while_stmt->Exp(), tctx); + ++tctx.loop_depth; InferBlock(std::dynamic_pointer_cast(while_stmt->Block()), true, tctx); + --tctx.loop_depth; return RecordType(tctx.current_map, while_stmt.get(), T_UNKNOWN); } @@ -791,8 +844,10 @@ InferredType TypeInferencer::InferRepeat(const std::shared_ptr // Lua 语义:until 条件可以访问 repeat 块内声明 of local 变量。 // 因此必须在 until 条件推断完成之后再退出作用域,而不能在块结束时立即退出。 tctx.env.EnterScope(); + ++tctx.loop_depth; InferBlock(std::dynamic_pointer_cast(repeat_stmt->Block()), false, tctx); InferNode(repeat_stmt->Exp(), tctx); + --tctx.loop_depth; tctx.env.ExitScope(); return RecordType(tctx.current_map, repeat_stmt.get(), T_UNKNOWN); } @@ -817,7 +872,8 @@ InferredType TypeInferencer::InferExp(const std::shared_ptr &exp, switch (exp_kind) { case ExpKind::kNumber: { const auto &value = exp->ExpValue(); - const auto ret = IsInteger(value) ? T_INT : T_FLOAT; + int64_t dummy = 0; + const auto ret = TryParseLuaIntLiteral(value, dummy) ? T_INT : T_FLOAT; return RecordType(current_map, exp.get(), ret); } case ExpKind::kPrefixExp: { @@ -841,10 +897,11 @@ InferredType TypeInferencer::InferExp(const std::shared_ptr &exp, if (const auto val1_type = (it != current_map.end()) ? it->second : T_DYNAMIC; IsNumericInferredType(val1_type) && IsNumericInferredType(right_type)) { return RecordType(current_map, exp.get(), (val1_type == right_type) ? val1_type : T_FLOAT); } + return RecordType(current_map, exp.get(), T_DYNAMIC); } } } - return RecordType(current_map, exp.get(), IsNumericInferredType(left_type) ? left_type : T_DYNAMIC); + return RecordType(current_map, exp.get(), (IsNumericInferredType(left_type) && IsNumericInferredType(right_type)) ? left_type : T_DYNAMIC); } if (left_type == T_DYNAMIC || right_type == T_DYNAMIC) { @@ -1219,6 +1276,191 @@ TypeInferencer::MathFuncInfoMap TypeInferencer::IdentifyMathParams(const ParseRe return math_func_info; } +namespace { + +bool IsStaticallyNonNumericExp(const SyntaxTreeInterfacePtr &node) { + if (!node || node->Type() != SyntaxTreeType::Exp) return false; + const auto exp = std::dynamic_pointer_cast(node); + if (!exp) return false; + switch (exp->GetExpKind()) { + case ExpKind::kNil: + case ExpKind::kTrue: + case ExpKind::kFalse: + case ExpKind::kString: + case ExpKind::kTableConstructor: + case ExpKind::kFunctionDef: + return true; + case ExpKind::kPrefixExp: { + const auto pe = std::dynamic_pointer_cast(exp->Right()); + if (pe && pe->GetPrefixKind() == PrefixExpKind::kExp) { + return IsStaticallyNonNumericExp(pe->GetValue()); + } + return false; + } + case ExpKind::kUnop: { + const auto op = std::dynamic_pointer_cast(exp->Op()); + return op && op->GetOpKind() == UnOpKind::kNot; + } + case ExpKind::kBinop: { + const auto op = std::dynamic_pointer_cast(exp->Op()); + if (!op) return false; + switch (op->GetOpKind()) { + case BinOpKind::kConcat: + case BinOpKind::kLess: + case BinOpKind::kLessEqual: + case BinOpKind::kMore: + case BinOpKind::kMoreEqual: + case BinOpKind::kEqual: + case BinOpKind::kNotEqual: + return true; + case BinOpKind::kAnd: + return IsStaticallyNonNumericExp(exp->Right()); + case BinOpKind::kOr: + return IsStaticallyNonNumericExp(exp->Left()) && IsStaticallyNonNumericExp(exp->Right()); + default: + return false; + } + } + default: + return false; + } +} + +bool IsParamCompatibleWithMathSpec(const SyntaxTreeInterfacePtr &func_block, const std::string ¶m_name, + const std::unordered_map &var_define_nodes) { + std::unordered_set non_numeric_inits; + std::unordered_set reassigned_locals; + WalkSyntaxTree(func_block, [&](const SyntaxTreeInterfacePtr &n) { + if (!n) return; + if (n->Type() == SyntaxTreeType::LocalVar) { + const auto lv = std::dynamic_pointer_cast(n); + const auto el = lv ? std::dynamic_pointer_cast(lv->Explist()) : nullptr; + if (el) { + for (const auto &e: el->Exps()) { + if (IsStaticallyNonNumericExp(e)) { + non_numeric_inits.insert(e.get()); + } + } + } + } else if (n->Type() == SyntaxTreeType::Assign) { + const auto assign = std::dynamic_pointer_cast(n); + const auto vl = assign ? std::dynamic_pointer_cast(assign->Varlist()) : nullptr; + const auto el = assign ? std::dynamic_pointer_cast(assign->Explist()) : nullptr; + if (vl && !vl->Vars().empty() && el && !el->Exps().empty()) { + const auto v = std::dynamic_pointer_cast(vl->Vars()[0]); + if (v && v->GetVarKind() == VarKind::kSimple && !IsStaticallyNonNumericExp(el->Exps()[0])) { + reassigned_locals.insert(v->GetName()); + } + } + } + }); + + std::function check_stmt = [&](const SyntaxTreeInterfacePtr &stmt, bool &shadowed) -> bool { + if (!stmt) return true; + switch (stmt->Type()) { + case SyntaxTreeType::Block: { + const auto blk = std::dynamic_pointer_cast(stmt); + if (!blk) return true; + bool inner_shadowed = shadowed; + for (const auto &s: blk->Stmts()) { + if (!check_stmt(s, inner_shadowed)) return false; + } + return true; + } + case SyntaxTreeType::LocalVar: { + const auto lv = std::dynamic_pointer_cast(stmt); + if (const auto nl = lv ? std::dynamic_pointer_cast(lv->Namelist()) : nullptr) { + for (const auto &n: nl->Names()) { + if (n == param_name) shadowed = true; + } + } + return true; + } + case SyntaxTreeType::LocalFunction: { + const auto lf = std::dynamic_pointer_cast(stmt); + if (lf && lf->Name() == param_name) shadowed = true; + return true; + } + case SyntaxTreeType::Assign: { + if (shadowed) return true; + const auto assign = std::dynamic_pointer_cast(stmt); + const auto vl = assign ? std::dynamic_pointer_cast(assign->Varlist()) : nullptr; + const auto el = assign ? std::dynamic_pointer_cast(assign->Explist()) : nullptr; + if (!vl || vl->Vars().empty() || !el || el->Exps().empty()) return true; + const auto v = std::dynamic_pointer_cast(vl->Vars()[0]); + if (!v || v->GetVarKind() != VarKind::kSimple || v->GetName() != param_name) return true; + const auto &rhs = el->Exps()[0]; + if (IsStaticallyNonNumericExp(rhs)) { + return false; + } + if (rhs && rhs->Type() == SyntaxTreeType::Exp) { + const auto rexp = std::dynamic_pointer_cast(rhs); + if (rexp && rexp->GetExpKind() == ExpKind::kPrefixExp) { + const auto rpe = std::dynamic_pointer_cast(rexp->Right()); + if (rpe && rpe->GetPrefixKind() == PrefixExpKind::kVar) { + const auto rvar = std::dynamic_pointer_cast(rpe->GetValue()); + if (rvar && rvar->GetVarKind() == VarKind::kSimple && !reassigned_locals.contains(rvar->GetName())) { + if (const auto dit = var_define_nodes.find(rvar.get()); dit != var_define_nodes.end() && non_numeric_inits.contains(dit->second)) { + return false; + } + } + } + } + } + return true; + } + case SyntaxTreeType::If: { + const auto if_node = std::dynamic_pointer_cast(stmt); + { + bool s = shadowed; + if (!check_stmt(if_node->Block(), s)) return false; + } + if (const auto elseifs = std::dynamic_pointer_cast(if_node->ElseIfs())) { + for (const auto &eblk: elseifs->ElseifBlocks()) { + bool s = shadowed; + if (!check_stmt(eblk, s)) return false; + } + } + if (if_node->ElseBlock()) { + bool s = shadowed; + if (!check_stmt(if_node->ElseBlock(), s)) return false; + } + return true; + } + case SyntaxTreeType::While: { + bool s = shadowed; + return check_stmt(std::dynamic_pointer_cast(stmt)->Block(), s); + } + case SyntaxTreeType::Repeat: { + bool s = shadowed; + return check_stmt(std::dynamic_pointer_cast(stmt)->Block(), s); + } + case SyntaxTreeType::ForLoop: { + const auto fl = std::dynamic_pointer_cast(stmt); + bool s = shadowed || (fl->Name() == param_name); + return check_stmt(fl->Block(), s); + } + case SyntaxTreeType::ForIn: { + const auto fi = std::dynamic_pointer_cast(stmt); + bool s = shadowed; + if (const auto nl = std::dynamic_pointer_cast(fi->Namelist())) { + for (const auto &n: nl->Names()) { + if (n == param_name) s = true; + } + } + return check_stmt(fi->Block(), s); + } + default: + return true; + } + }; + + bool root_shadowed = false; + return check_stmt(func_block, root_shadowed); +} + +}// namespace + std::vector TypeInferencer::FindMathParamIndices(const FunctionSpecInfo &info, const EvalTypeSnapshot &baseline, const EvalTypeSnapshot &all_int, const std::unordered_map> &known_math_positions, std::unordered_map &var_define_nodes) { @@ -1229,6 +1471,9 @@ std::vector TypeInferencer::FindMathParamIndices(const FunctionSpecInfo &in } for (int i = 0; i < static_cast(info.params.size()); ++i) { + if (!IsParamCompatibleWithMathSpec(info.block, info.params[i], var_define_nodes)) { + continue; + } // without_p:除 p_i 为 T_DYNAMIC 外,其余参数均为 T_INT。 const auto without_p_assumed = MakeAssumedParamTypes(info.params, info.params[i], T_DYNAMIC, T_INT); // 若去掉 p_i 后算术/比较/for-loop 退化,则 p_i 是数学参数。 @@ -1278,6 +1523,7 @@ EvalTypeSnapshot TypeInferencer::RunTrialInference(const SyntaxTreeInterfacePtr EvalTypeSnapshot prev_map; EvalTypeSnapshot current_map; + DeclOverrideMap decl_overrides; for (int round = 0; round < kMaxSpecIterations; ++round) { // 每轮清除 func_block 节点在 current_map 中的旧条目,保证推断从干净状态开始。 @@ -1289,18 +1535,20 @@ EvalTypeSnapshot TypeInferencer::RunTrialInference(const SyntaxTreeInterfacePtr for (const auto &[fname, ftype]: file_level_types_) { env.Define(fname, ftype); } - for (const auto &p: params) { + for (size_t pi = 0; pi < params.size(); ++pi) { + const auto &p = params[pi]; const bool is_cap = ar_ && ar_->captured_decl_vars.contains({func_block.get(), p}); const auto it = assumed_types.find(p); - env.Define(p, (!is_cap && it != assumed_types.end()) ? it->second : T_DYNAMIC); + env.Define(p, (!is_cap && it != assumed_types.end()) ? it->second : T_DYNAMIC, nullptr, func_block.get(), pi, !is_cap); } // 运行函数体类型推断(不新开作用域,参数已在当前作用域中定义)。 // Trial 推断不消费 shadow 信息(shadow 只与 AST 结构相关,主推断已覆盖), // 但 TraversalContext 需要一个引用,因此用丢弃式的容器占位。 std::set> dummy_shadowed_decls; - TraversalContext tctx{current_map, env, &ctx, var_define_nodes, dummy_shadowed_decls}; + TraversalContext tctx{current_map, env, &ctx, var_define_nodes, dummy_shadowed_decls, std::move(decl_overrides), false}; InferBlock(std::dynamic_pointer_cast(func_block), false, tctx); + decl_overrides = std::move(tctx.decl_type_overrides); // 快照本轮推断结果:为未被推断触及的节点补 T_UNKNOWN, // 使 curr_map 与 prev_map 具有相同的键集,从而能直接比较。 @@ -1311,7 +1559,7 @@ EvalTypeSnapshot TypeInferencer::RunTrialInference(const SyntaxTreeInterfacePtr curr_map[n.get()] = (it != current_map.end()) ? it->second : T_UNKNOWN; }); - if (curr_map == prev_map) { + if (curr_map == prev_map && !tctx.any_decl_widened) { // 已达到不动点,提前退出。 break; } @@ -1502,6 +1750,9 @@ bool TypeInferencer::CheckCallNodeChange(const SyntaxTreeInterfacePtr &node, con if (!callee_var || callee_var->GetVarKind() != VarKind::kSimple) { return false; } + if (ar_ && ar_->callee_names.contains(fc.get()) && ar_->callee_names.at(fc.get()).empty()) { + return false; + } const auto &callee_name = callee_var->GetName(); if (const auto math_it = math_param_positions.find(callee_name); math_it != math_param_positions.end()) { const auto args_ptr = std::dynamic_pointer_cast(fc->Args()); @@ -1696,6 +1947,7 @@ bool TypeInferencer::CollectReturnExps(const SyntaxTreeInterfacePtr &block_node, case SyntaxTreeType::Function: case SyntaxTreeType::FunctionCall: case SyntaxTreeType::Break: + case SyntaxTreeType::Continue: case SyntaxTreeType::Goto: case SyntaxTreeType::Label: case SyntaxTreeType::Empty: @@ -1726,7 +1978,13 @@ InferredType TypeInferencer::ResolveCallReturnType(const std::shared_ptrGetVarKind() != VarKind::kSimple) { return T_DYNAMIC; } + if (ar_ && ar_->callee_names.contains(fc.get()) && ar_->callee_names.at(fc.get()).empty()) { + return T_DYNAMIC; + } const auto &callee_name = callee_var->GetName(); + if (tctx.env.Has(callee_name)) { + return T_DYNAMIC; + } const auto math_it = tctx.ctx->math_positions->find(callee_name); if (math_it == tctx.ctx->math_positions->end()) { @@ -1964,10 +2222,17 @@ void TypeInferencer::AnalyzeTableShapes(const SyntaxTreeInterfacePtr &chunk, Inf }; std::vector> frames; - auto PushFrame = [&]() { frames.push_back(std::make_shared()); }; - // 注意:不 pop frame。所有 frame 保留到 stamping 阶段供查询, - // 因为 ctor_target_vars / var_fields 在函数退出后仍需被 stamp 循环访问。 - // 函数级隔离由 push_frame 实现(每个 function body 进入时新开 frame)。 + std::vector frame_stack; + auto PushFrame = [&]() { + const int idx = static_cast(frames.size()); + frames.push_back(std::make_shared()); + frame_stack.push_back(idx); + }; + auto PopFrame = [&]() { + if (frame_stack.size() > 1) { + frame_stack.pop_back(); + } + }; PushFrame();// 顶层 frame(文件级 / __fakelua_init) // 辅助:从 table constructor 节点构建 own_fields 并登记 @@ -1998,53 +2263,73 @@ void TypeInferencer::AnalyzeTableShapes(const SyntaxTreeInterfacePtr &chunk, Inf std::vector pending_var_ctors; - WalkSyntaxTree(chunk, [&](const SyntaxTreeInterfacePtr &node) { - if (!node) return; - switch (node->Type()) { - case SyntaxTreeType::TableConstructor: - RecordCtorNode(node); - break; - case SyntaxTreeType::Exp: { - auto exp = std::dynamic_pointer_cast(node); - if (exp->GetExpKind() == ExpKind::kTableConstructor) { - RecordCtorNode(exp->Right()); + std::function walk_shapes = [&](const SyntaxTreeInterfacePtr &sub_root) { + WalkSyntaxTreePruned(sub_root, [&](const SyntaxTreeInterfacePtr &node) -> bool { + if (!node) return false; + switch (node->Type()) { + case SyntaxTreeType::TableConstructor: + RecordCtorNode(node); + return true; + case SyntaxTreeType::Exp: { + auto exp = std::dynamic_pointer_cast(node); + if (exp->GetExpKind() == ExpKind::kTableConstructor) { + RecordCtorNode(exp->Right()); + } + return true; } - break; - } - case SyntaxTreeType::Function: - case SyntaxTreeType::LocalFunction: - PushFrame(); - break; - case SyntaxTreeType::LocalVar: { - auto lv = std::dynamic_pointer_cast(node); - const auto namelist = std::dynamic_pointer_cast(lv->Namelist()); - const auto explist = std::dynamic_pointer_cast(lv->Explist()); - if (namelist && explist) { - const auto &names = namelist->Names(); - const auto &exps = explist->Exps(); - const int frame_idx = static_cast(frames.size()) - 1; - for (size_t i = 0; i < names.size() && i < exps.size(); ++i) { - pending_var_ctors.push_back({names[i], exps[i], frame_idx}); + case SyntaxTreeType::Function: { + if (node.get() == sub_root.get()) return true; + PushFrame(); + walk_shapes(std::dynamic_pointer_cast(node)->Funcbody()); + PopFrame(); + return false; + } + case SyntaxTreeType::LocalFunction: { + if (node.get() == sub_root.get()) return true; + PushFrame(); + walk_shapes(std::dynamic_pointer_cast(node)->Funcbody()); + PopFrame(); + return false; + } + case SyntaxTreeType::FunctionDef: { + if (node.get() == sub_root.get()) return true; + PushFrame(); + walk_shapes(std::dynamic_pointer_cast(node)->Funcbody()); + PopFrame(); + return false; + } + case SyntaxTreeType::LocalVar: { + auto lv = std::dynamic_pointer_cast(node); + const auto namelist = std::dynamic_pointer_cast(lv->Namelist()); + const auto explist = std::dynamic_pointer_cast(lv->Explist()); + if (namelist && explist) { + const auto &names = namelist->Names(); + const auto &exps = explist->Exps(); + const int frame_idx = frame_stack.back(); + for (size_t i = 0; i < names.size() && i < exps.size(); ++i) { + pending_var_ctors.push_back({names[i], exps[i], frame_idx}); + } } + return true; } - break; - } - case SyntaxTreeType::Assign: { - auto assign = std::dynamic_pointer_cast(node); - const auto varlist = std::dynamic_pointer_cast(assign->Varlist()); - const auto explist = std::dynamic_pointer_cast(assign->Explist()); - if (varlist && explist && !explist->Exps().empty()) { - const auto v = varlist->Vars().empty() ? nullptr : std::dynamic_pointer_cast(varlist->Vars()[0]); - if (v && v->GetVarKind() == VarKind::kSimple) { - pending_var_ctors.push_back({v->GetName(), explist->Exps()[0], static_cast(frames.size()) - 1}); + case SyntaxTreeType::Assign: { + auto assign = std::dynamic_pointer_cast(node); + const auto varlist = std::dynamic_pointer_cast(assign->Varlist()); + const auto explist = std::dynamic_pointer_cast(assign->Explist()); + if (varlist && explist && !explist->Exps().empty()) { + const auto v = varlist->Vars().empty() ? nullptr : std::dynamic_pointer_cast(varlist->Vars()[0]); + if (v && v->GetVarKind() == VarKind::kSimple) { + pending_var_ctors.push_back({v->GetName(), explist->Exps()[0], frame_stack.back()}); + } } + return true; } - break; + default: + return true; } - default: - break; - } - }); + }); + }; + walk_shapes(chunk); // 后处理:此时所有子节点已遍历,ctor_own_fields 已填充完毕 for (const auto &pending: pending_var_ctors) { @@ -2151,8 +2436,8 @@ std::string TypeInferencer::SpecFromRhs(const SyntaxTreeInterfacePtr &exp, const return ""; } -void TypeInferencer::AnnotateExprs(const SyntaxTreeInterfacePtr &node, FlowState &st, InferResult &ir) { - if (!node) return; +void TypeInferencer::AnnotateExprs(const SyntaxTreeInterfacePtr &node, FlowState &st, InferResult &ir, const FlowContext &fctx) { + if (!fctx.emit || !node) return; switch (node->Type()) { case SyntaxTreeType::Var: { @@ -2170,12 +2455,12 @@ void TypeInferencer::AnnotateExprs(const SyntaxTreeInterfacePtr &node, FlowState } // CGen 会通过 CompileExp 继续编译 prefixexp 子表达式:若它本身是 Var 字段读, // 则会被单独再调一次 CompileVar + GetSpecTypeForVar,故这里也递归前缀以逐层标注。 - AnnotateExprs(receiver, st, ir); + AnnotateExprs(receiver, st, ir, fctx); } } if (var_kind == VarKind::kSquare) { // 下标表达式里可能含字段读。 - AnnotateExprs(var->GetExp(), st, ir); + AnnotateExprs(var->GetExp(), st, ir, fctx); } return; } @@ -2196,6 +2481,10 @@ void TypeInferencer::AnnotateExprs(const SyntaxTreeInterfacePtr &node, FlowState if (!spec.empty()) { ir.var_spec_annotations[first.get()] = spec; } + AnnotateExprs(first, st, ir, fctx); + for (size_t ai = 1; ai < explist->Exps().size(); ++ai) { + AnnotateExprs(explist->Exps()[ai], st, ir, fctx); + } } } return; @@ -2203,63 +2492,70 @@ void TypeInferencer::AnnotateExprs(const SyntaxTreeInterfacePtr &node, FlowState } } // 普通调用:遍历前缀与参数,捕获其内的字段读。 - AnnotateExprs(fc->prefixexp(), st, ir); - AnnotateExprs(fc->Args(), st, ir); + AnnotateExprs(fc->prefixexp(), st, ir, fctx); + AnnotateExprs(fc->Args(), st, ir, fctx); return; } case SyntaxTreeType::Args: { const auto args = std::dynamic_pointer_cast(node); - AnnotateExprs(args->Explist(), st, ir); - AnnotateExprs(args->Tableconstructor(), st, ir); - AnnotateExprs(args->String(), st, ir); + AnnotateExprs(args->Explist(), st, ir, fctx); + AnnotateExprs(args->Tableconstructor(), st, ir, fctx); + AnnotateExprs(args->String(), st, ir, fctx); return; } case SyntaxTreeType::ExpList: { const auto el = std::dynamic_pointer_cast(node); - for (const auto &exp: el->Exps()) AnnotateExprs(exp, st, ir); + for (const auto &exp: el->Exps()) AnnotateExprs(exp, st, ir, fctx); return; } case SyntaxTreeType::Exp: { const auto exp_node = std::dynamic_pointer_cast(node); const auto k = exp_node->GetExpKind(); if (k == ExpKind::kPrefixExp) { - AnnotateExprs(exp_node->Right(), st, ir); + AnnotateExprs(exp_node->Right(), st, ir, fctx); } else if (k == ExpKind::kBinop) { - AnnotateExprs(exp_node->Left(), st, ir); - AnnotateExprs(exp_node->Right(), st, ir); + AnnotateExprs(exp_node->Left(), st, ir, fctx); + AnnotateExprs(exp_node->Right(), st, ir, fctx); } else if (k == ExpKind::kUnop) { - AnnotateExprs(exp_node->Right(), st, ir); + AnnotateExprs(exp_node->Right(), st, ir, fctx); } else if (k == ExpKind::kTableConstructor) { // 构造器字段值里可能包含字段读。 const auto tc = std::dynamic_pointer_cast(exp_node->Right()); - if (tc) AnnotateExprs(tc->Fieldlist(), st, ir); + if (tc) AnnotateExprs(tc->Fieldlist(), st, ir, fctx); + } else if (k == ExpKind::kFunctionDef) { + const auto fdef = std::dynamic_pointer_cast(exp_node->Right()); + if (fdef && fdef->Funcbody() && fctx.mutated_captured_defs) { + std::unordered_set enclosing; + for (const auto &[lname, _]: st.local) enclosing.insert(lname); + FlowFuncBody(fdef->Funcbody(), st.global, enclosing, *fctx.mutated_captured_defs, ir); + } } return; } case SyntaxTreeType::FieldList: { const auto fl = std::dynamic_pointer_cast(node); - for (const auto &field: fl->Fields()) AnnotateExprs(field, st, ir); + for (const auto &field: fl->Fields()) AnnotateExprs(field, st, ir, fctx); return; } case SyntaxTreeType::Field: { const auto field_node = std::dynamic_pointer_cast(node); - AnnotateExprs(field_node->Key(), st, ir); - AnnotateExprs(field_node->Value(), st, ir); + AnnotateExprs(field_node->Key(), st, ir, fctx); + AnnotateExprs(field_node->Value(), st, ir, fctx); return; } case SyntaxTreeType::PrefixExp: { const auto pe = std::dynamic_pointer_cast(node); - AnnotateExprs(pe->GetValue(), st, ir); + AnnotateExprs(pe->GetValue(), st, ir, fctx); return; } case SyntaxTreeType::TableConstructor: { const auto tc = std::dynamic_pointer_cast(node); - AnnotateExprs(tc->Fieldlist(), st, ir); + AnnotateExprs(tc->Fieldlist(), st, ir, fctx); return; } case SyntaxTreeType::Return: { const auto ret = std::dynamic_pointer_cast(node); - AnnotateExprs(ret->Explist(), st, ir); + AnnotateExprs(ret->Explist(), st, ir, fctx); return; } default: @@ -2267,33 +2563,91 @@ void TypeInferencer::AnnotateExprs(const SyntaxTreeInterfacePtr &node, FlowState } } -void TypeInferencer::FlowBlock(const SyntaxTreeInterfacePtr &block, FlowState &st, InferResult &ir, const bool is_top_level) { - if (!block || block->Type() != SyntaxTreeType::Block) return; +namespace { + +void DeclareFlowLocal(const std::string &name, const std::string &spec, TypeInferencer::FlowState &st, TypeInferencer::FlowContext &fctx) { + if (!fctx.is_top_level && !fctx.scope_saved_locals.empty()) { + auto &saved = fctx.scope_saved_locals.back(); + if (!saved.contains(name)) { + if (const auto it = st.local.find(name); it != st.local.end()) { + saved[name] = it->second; + } else { + saved[name] = std::nullopt; + } + } + } + if (fctx.is_top_level) { + if (spec.empty()) { + st.local.erase(name); + st.global.erase(name); + } else { + st.local[name] = spec; + st.global[name] = spec; + } + } else { + // 函数局部始终保留 st.local[name](空串代表 dynamic),防止同名遮蔽回退到 st.global。 + st.local[name] = spec; + } +} + +void RestoreFlowScope(TypeInferencer::FlowState &st, const std::unordered_map> &saved) { + for (const auto &[name, prev]: saved) { + if (prev.has_value()) { + st.local[name] = *prev; + } else { + st.local.erase(name); + } + } +} + +TypeInferencer::FlowState UnwindFlowStateToLoopDepth(const TypeInferencer::FlowState &st, const TypeInferencer::FlowContext &fctx) { + TypeInferencer::FlowState copy = st; + for (size_t d = fctx.scope_saved_locals.size(); d > fctx.loop_scope_depth; --d) { + RestoreFlowScope(copy, fctx.scope_saved_locals[d - 1]); + } + return copy; +} + +}// namespace + +bool TypeInferencer::FlowBlock(const SyntaxTreeInterfacePtr &block, FlowState &st, InferResult &ir, FlowContext &fctx, const bool new_scope) { + if (!block || block->Type() != SyntaxTreeType::Block) return false; const auto block_ptr = std::dynamic_pointer_cast(block); + if (new_scope && !fctx.is_top_level) { + fctx.scope_saved_locals.emplace_back(); + } + bool terminated = false; for (const auto &stmt: block_ptr->Stmts()) { - FlowStmt(stmt, st, ir, is_top_level); + if (FlowStmt(stmt, st, ir, fctx) && !fctx.has_goto_or_label) { + terminated = true; + } + } + if (new_scope && !fctx.is_top_level) { + RestoreFlowScope(st, fctx.scope_saved_locals.back()); + fctx.scope_saved_locals.pop_back(); } + return terminated; } -void TypeInferencer::FlowStmt(const SyntaxTreeInterfacePtr &stmt, FlowState &st, InferResult &ir, const bool is_top_level) { - if (!stmt) return; +bool TypeInferencer::FlowStmt(const SyntaxTreeInterfacePtr &stmt, FlowState &st, InferResult &ir, FlowContext &fctx) { + if (!stmt) return false; switch (stmt->Type()) { + case SyntaxTreeType::Block: { + return FlowBlock(stmt, st, ir, fctx, true); + } case SyntaxTreeType::LocalVar: { - // 先标注所有读(右侧表达式里的字段引用)。 const auto lv = std::dynamic_pointer_cast(stmt); if (const auto explist = std::dynamic_pointer_cast(lv->Explist())) { - for (const auto &exp: explist->Exps()) AnnotateExprs(exp, st, ir); + for (const auto &exp: explist->Exps()) AnnotateExprs(exp, st, ir, fctx); } - // 再按语义更新 local / global。 const auto namelist = std::dynamic_pointer_cast(lv->Namelist()); - if (!namelist) return; + if (!namelist) return false; const auto exps = [&]() -> std::vector { if (const auto el = std::dynamic_pointer_cast(lv->Explist())) return el->Exps(); return {}; }(); const auto &names = namelist->Names(); - // 多返回值(函数调用 / varargs 最后一位 + 名字多于表达式):尾部全部降 dynamic。 const bool multi_return = names.size() > exps.size(); for (size_t i = 0; i < names.size(); ++i) { const auto &name = names[i]; @@ -2301,175 +2655,683 @@ void TypeInferencer::FlowStmt(const SyntaxTreeInterfacePtr &stmt, FlowState &st, if (i < exps.size()) { spec = SpecFromRhs(exps[i], st, ir); } - // 多返回:从 exps.size()-1 位起全部 dynamic (i >= exps.size()-1 即尾部)。 if (multi_return && static_cast(i) >= static_cast(exps.size()) - 1) { spec.clear(); } - if (spec.empty()) { - st.local.erase(name); - st.global.erase(name); - } else { - st.local[name] = spec; - if (is_top_level) st.global[name] = spec; + if (fctx.mutated_captured_defs && fctx.mutated_captured_defs->contains({lv.get(), name})) { + spec.clear(); } + if (fctx.goto_reassigned_names && fctx.goto_reassigned_names->contains(name)) { + spec.clear(); + } + DeclareFlowLocal(name, spec, st, fctx); } - return; + return false; + } + case SyntaxTreeType::LocalFunction: { + const auto lf = std::dynamic_pointer_cast(stmt); + DeclareFlowLocal(lf->Name(), "", st, fctx); + if (fctx.emit && lf->Funcbody() && fctx.mutated_captured_defs) { + std::unordered_set enclosing; + for (const auto &[lname, _]: st.local) enclosing.insert(lname); + FlowFuncBody(lf->Funcbody(), st.global, enclosing, *fctx.mutated_captured_defs, ir); + } + return false; } case SyntaxTreeType::Assign: { const auto assign = std::dynamic_pointer_cast(stmt); - // 标注右侧字段读。 - if (const auto explist = std::dynamic_pointer_cast(assign->Explist())) { - for (const auto &exp: explist->Exps()) AnnotateExprs(exp, st, ir); - } const auto varlist = std::dynamic_pointer_cast(assign->Varlist()); const auto explist = std::dynamic_pointer_cast(assign->Explist()); - // 预处理保证单变量、单表达式。 - if (!varlist || !explist || varlist->Vars().empty() || explist->Exps().empty()) return; + if (varlist) { + for (const auto &vnode: varlist->Vars()) { + if (const auto v = std::dynamic_pointer_cast(vnode)) { + AnnotateExprs(v->GetPrefixexp(), st, ir, fctx); + AnnotateExprs(v->GetExp(), st, ir, fctx); + } + } + } + if (explist) { + for (const auto &exp: explist->Exps()) AnnotateExprs(exp, st, ir, fctx); + } + if (!varlist || !explist || varlist->Vars().empty() || explist->Exps().empty()) return false; const auto var = std::dynamic_pointer_cast(varlist->Vars()[0]); - if (!var) return; + if (!var || var->GetVarKind() != VarKind::kSimple) return false; const auto name = var->GetName(); - const auto spec = SpecFromRhs(explist->Exps()[0], st, ir); - if (spec.empty()) { - st.local.erase(name); - st.global.erase(name); + std::string spec = SpecFromRhs(explist->Exps()[0], st, ir); + if ((ar_ && ar_->captured_var_nodes.contains(var.get())) || (fctx.goto_reassigned_names && fctx.goto_reassigned_names->contains(name))) { + spec.clear(); + } + if (fctx.is_top_level) { + if (spec.empty()) { + st.local.erase(name); + st.global.erase(name); + } else { + st.local[name] = spec; + st.global[name] = spec; + } } else { st.local[name] = spec; - if (is_top_level) st.global[name] = spec; } - return; + return false; } case SyntaxTreeType::If: { const auto if_node = std::dynamic_pointer_cast(stmt); - // 条件里的字段读在汇合前求值:用 if 之前的状态。 - AnnotateExprs(if_node->Exp(), st, ir); - - const auto snapshot_local = st.local; - const auto snapshot_global = st.global; + AnnotateExprs(if_node->Exp(), st, ir, fctx); + const FlowState snapshot = st; std::vector branch_states; - // then 分支 + bool all_terminated = true; + { - FlowState branch; - branch.local = st.local; - branch.global = st.global; - FlowBlock(if_node->Block(), branch, ir, is_top_level); - branch_states.push_back(std::move(branch)); + FlowState branch = snapshot; + const bool term = FlowBlock(if_node->Block(), branch, ir, fctx, true); + if (!term) { + all_terminated = false; + branch_states.push_back(std::move(branch)); + } } - // elseif 分支 if (const auto elseifs = std::dynamic_pointer_cast(if_node->ElseIfs())) { for (size_t i = 0; i < elseifs->ElseifSize(); ++i) { - // 条件读使用 if 前状态。 - AnnotateExprs(elseifs->ElseifExp(i), st, ir); - FlowState branch; - branch.local = snapshot_local; - branch.global = snapshot_global; - FlowBlock(elseifs->ElseifBlock(i), branch, ir, is_top_level); - branch_states.push_back(std::move(branch)); + AnnotateExprs(elseifs->ElseifExp(i), st, ir, fctx); + FlowState branch = snapshot; + const bool term = FlowBlock(elseifs->ElseifBlock(i), branch, ir, fctx, true); + if (!term) { + all_terminated = false; + branch_states.push_back(std::move(branch)); + } } } - // else 分支 if (const auto else_block = if_node->ElseBlock()) { - FlowState branch; - branch.local = snapshot_local; - branch.global = snapshot_global; - FlowBlock(else_block, branch, ir, is_top_level); - branch_states.push_back(std::move(branch)); + FlowState branch = snapshot; + const bool term = FlowBlock(else_block, branch, ir, fctx, true); + if (!term) { + all_terminated = false; + branch_states.push_back(std::move(branch)); + } } else { - // 无 else:隐式 else 路径保持 if 前状态(等同 s0),纳入汇合。 - FlowState branch; - branch.local = snapshot_local; - branch.global = snapshot_global; - branch_states.push_back(std::move(branch)); + all_terminated = false; + branch_states.push_back(snapshot); } - // 汇合:各分支同 key 值全一致才保留。 - JoinFlowStates(branch_states, st); - return; + if (!branch_states.empty()) { + JoinFlowStates(branch_states, st); + } + return all_terminated; } case SyntaxTreeType::While: { const auto while_node = std::dynamic_pointer_cast(stmt); - AnnotateExprs(while_node->Exp(), st, ir); - // CGen 不快照循环:精确复现直接贯穿(虽理论上多轮可能降级,但保持与原 emitter 行为一致)。 - FlowBlock(while_node->Block(), st, ir, is_top_level); - return; + FlowState head = st; + for (int iter = 0; iter < kMaxSpecIterations; ++iter) { + std::vector breaks; + std::vector continues; + FlowContext dry_ctx = fctx; + dry_ctx.emit = false; + dry_ctx.loop_breaks = &breaks; + dry_ctx.loop_continues = &continues; + dry_ctx.loop_scope_depth = dry_ctx.scope_saved_locals.size(); + FlowState body_end = head; + const bool body_term = FlowBlock(while_node->Block(), body_end, ir, dry_ctx, true); + std::vector back_states = {head}; + if (!body_term) back_states.push_back(std::move(body_end)); + for (auto &cs: continues) back_states.push_back(std::move(cs)); + FlowState next_head; + JoinFlowStates(back_states, next_head); + if (next_head == head) break; + head = std::move(next_head); + } + + st = head; + AnnotateExprs(while_node->Exp(), st, ir, fctx); + std::vector breaks; + std::vector continues; + auto *saved_breaks = fctx.loop_breaks; + auto *saved_continues = fctx.loop_continues; + const size_t saved_depth = fctx.loop_scope_depth; + fctx.loop_breaks = &breaks; + fctx.loop_continues = &continues; + fctx.loop_scope_depth = fctx.scope_saved_locals.size(); + FlowState body_end = head; + FlowBlock(while_node->Block(), body_end, ir, fctx, true); + fctx.loop_breaks = saved_breaks; + fctx.loop_continues = saved_continues; + fctx.loop_scope_depth = saved_depth; + + std::vector exit_states = {head}; + for (auto &bs: breaks) exit_states.push_back(std::move(bs)); + JoinFlowStates(exit_states, st); + return false; } case SyntaxTreeType::Repeat: { const auto rep = std::dynamic_pointer_cast(stmt); - FlowBlock(rep->Block(), st, ir, is_top_level); - AnnotateExprs(rep->Exp(), st, ir); - return; + FlowState head = st; + for (int iter = 0; iter < kMaxSpecIterations; ++iter) { + std::vector breaks; + std::vector continues; + FlowContext dry_ctx = fctx; + dry_ctx.emit = false; + if (!dry_ctx.is_top_level) { + dry_ctx.scope_saved_locals.emplace_back(); + } + dry_ctx.loop_breaks = &breaks; + dry_ctx.loop_continues = &continues; + dry_ctx.loop_scope_depth = dry_ctx.scope_saved_locals.size(); + FlowState body_end = head; + const bool body_term = FlowBlock(rep->Block(), body_end, ir, dry_ctx, false); + std::vector until_states; + if (!body_term) until_states.push_back(std::move(body_end)); + for (auto &cs: continues) until_states.push_back(std::move(cs)); + FlowState until_joined = head; + if (!until_states.empty()) { + JoinFlowStates(until_states, until_joined); + } + if (!dry_ctx.is_top_level) { + RestoreFlowScope(until_joined, dry_ctx.scope_saved_locals.back()); + dry_ctx.scope_saved_locals.pop_back(); + } + FlowState next_head; + std::vector back_states = {head}; + if (!until_states.empty()) back_states.push_back(std::move(until_joined)); + JoinFlowStates(back_states, next_head); + if (next_head == head) break; + head = std::move(next_head); + } + + std::vector breaks; + std::vector continues; + auto *saved_breaks = fctx.loop_breaks; + auto *saved_continues = fctx.loop_continues; + const size_t saved_depth = fctx.loop_scope_depth; + const size_t outer_scope_depth = fctx.scope_saved_locals.size(); + if (!fctx.is_top_level) { + fctx.scope_saved_locals.emplace_back(); + } + fctx.loop_breaks = &breaks; + fctx.loop_continues = &continues; + // continue 落在 flua_until_N(仍在 repeat body 作用域内),break 跳出整个 repeat + fctx.loop_scope_depth = fctx.scope_saved_locals.size(); + FlowState body_end = head; + const bool body_term = FlowBlock(rep->Block(), body_end, ir, fctx, false); + fctx.loop_breaks = saved_breaks; + fctx.loop_continues = saved_continues; + fctx.loop_scope_depth = saved_depth; + + std::vector until_states; + if (!body_term) until_states.push_back(std::move(body_end)); + for (auto &cs: continues) until_states.push_back(std::move(cs)); + FlowState until_state = head; + if (!until_states.empty()) { + JoinFlowStates(until_states, until_state); + } + AnnotateExprs(rep->Exp(), until_state, ir, fctx); + if (!fctx.is_top_level) { + RestoreFlowScope(until_state, fctx.scope_saved_locals.back()); + for (auto &bs: breaks) { + if (fctx.scope_saved_locals.size() > outer_scope_depth) { + RestoreFlowScope(bs, fctx.scope_saved_locals.back()); + } + } + fctx.scope_saved_locals.pop_back(); + } + + std::vector exit_states; + if (!until_states.empty()) exit_states.push_back(std::move(until_state)); + for (auto &bs: breaks) exit_states.push_back(std::move(bs)); + if (!exit_states.empty()) { + JoinFlowStates(exit_states, st); + } else { + st = head; + } + return false; } case SyntaxTreeType::ForLoop: { const auto for_node = std::dynamic_pointer_cast(stmt); - AnnotateExprs(for_node->ExpBegin(), st, ir); - AnnotateExprs(for_node->ExpEnd(), st, ir); - if (for_node->ExpStep()) AnnotateExprs(for_node->ExpStep(), st, ir); - FlowBlock(for_node->Block(), st, ir, is_top_level); - return; + AnnotateExprs(for_node->ExpBegin(), st, ir, fctx); + AnnotateExprs(for_node->ExpEnd(), st, ir, fctx); + if (for_node->ExpStep()) AnnotateExprs(for_node->ExpStep(), st, ir, fctx); + + FlowState head = st; + for (int iter = 0; iter < kMaxSpecIterations; ++iter) { + std::vector breaks; + std::vector continues; + FlowContext dry_ctx = fctx; + dry_ctx.emit = false; + if (!dry_ctx.is_top_level) { + dry_ctx.scope_saved_locals.emplace_back(); + } + FlowState body_end = head; + DeclareFlowLocal(for_node->Name(), "", body_end, dry_ctx); + dry_ctx.loop_breaks = &breaks; + dry_ctx.loop_continues = &continues; + dry_ctx.loop_scope_depth = dry_ctx.scope_saved_locals.size(); + const bool body_term = FlowBlock(for_node->Block(), body_end, ir, dry_ctx, true); + if (!dry_ctx.is_top_level) { + RestoreFlowScope(body_end, dry_ctx.scope_saved_locals.back()); + for (auto &cs: continues) RestoreFlowScope(cs, dry_ctx.scope_saved_locals.back()); + dry_ctx.scope_saved_locals.pop_back(); + } + std::vector back_states = {head}; + if (!body_term) back_states.push_back(std::move(body_end)); + for (auto &cs: continues) back_states.push_back(std::move(cs)); + FlowState next_head; + JoinFlowStates(back_states, next_head); + if (next_head == head) break; + head = std::move(next_head); + } + + std::vector breaks; + std::vector continues; + auto *saved_breaks = fctx.loop_breaks; + auto *saved_continues = fctx.loop_continues; + const size_t saved_depth = fctx.loop_scope_depth; + if (!fctx.is_top_level) { + fctx.scope_saved_locals.emplace_back(); + } + FlowState body_end = head; + DeclareFlowLocal(for_node->Name(), "", body_end, fctx); + fctx.loop_breaks = &breaks; + fctx.loop_continues = &continues; + fctx.loop_scope_depth = fctx.scope_saved_locals.size(); + FlowBlock(for_node->Block(), body_end, ir, fctx, true); + fctx.loop_breaks = saved_breaks; + fctx.loop_continues = saved_continues; + fctx.loop_scope_depth = saved_depth; + if (!fctx.is_top_level) { + RestoreFlowScope(body_end, fctx.scope_saved_locals.back()); + for (auto &bs: breaks) RestoreFlowScope(bs, fctx.scope_saved_locals.back()); + fctx.scope_saved_locals.pop_back(); + } + + std::vector exit_states = {head}; + for (auto &bs: breaks) exit_states.push_back(std::move(bs)); + JoinFlowStates(exit_states, st); + return false; } case SyntaxTreeType::ForIn: { const auto for_in = std::dynamic_pointer_cast(stmt); if (const auto explist = std::dynamic_pointer_cast(for_in->Explist())) { - for (const auto &exp: explist->Exps()) AnnotateExprs(exp, st, ir); + for (const auto &exp: explist->Exps()) AnnotateExprs(exp, st, ir, fctx); + } + const auto nl = std::dynamic_pointer_cast(for_in->Namelist()); + + FlowState head = st; + for (int iter = 0; iter < kMaxSpecIterations; ++iter) { + std::vector breaks; + std::vector continues; + FlowContext dry_ctx = fctx; + dry_ctx.emit = false; + if (!dry_ctx.is_top_level) { + dry_ctx.scope_saved_locals.emplace_back(); + } + FlowState body_end = head; + if (nl) { + for (const auto &vname: nl->Names()) DeclareFlowLocal(vname, "", body_end, dry_ctx); + } + dry_ctx.loop_breaks = &breaks; + dry_ctx.loop_continues = &continues; + dry_ctx.loop_scope_depth = dry_ctx.scope_saved_locals.size(); + const bool body_term = FlowBlock(for_in->Block(), body_end, ir, dry_ctx, true); + if (!dry_ctx.is_top_level) { + RestoreFlowScope(body_end, dry_ctx.scope_saved_locals.back()); + for (auto &cs: continues) RestoreFlowScope(cs, dry_ctx.scope_saved_locals.back()); + dry_ctx.scope_saved_locals.pop_back(); + } + std::vector back_states = {head}; + if (!body_term) back_states.push_back(std::move(body_end)); + for (auto &cs: continues) back_states.push_back(std::move(cs)); + FlowState next_head; + JoinFlowStates(back_states, next_head); + if (next_head == head) break; + head = std::move(next_head); + } + + std::vector breaks; + std::vector continues; + auto *saved_breaks = fctx.loop_breaks; + auto *saved_continues = fctx.loop_continues; + const size_t saved_depth = fctx.loop_scope_depth; + if (!fctx.is_top_level) { + fctx.scope_saved_locals.emplace_back(); + } + FlowState body_end = head; + if (nl) { + for (const auto &vname: nl->Names()) DeclareFlowLocal(vname, "", body_end, fctx); + } + fctx.loop_breaks = &breaks; + fctx.loop_continues = &continues; + fctx.loop_scope_depth = fctx.scope_saved_locals.size(); + FlowBlock(for_in->Block(), body_end, ir, fctx, true); + fctx.loop_breaks = saved_breaks; + fctx.loop_continues = saved_continues; + fctx.loop_scope_depth = saved_depth; + if (!fctx.is_top_level) { + RestoreFlowScope(body_end, fctx.scope_saved_locals.back()); + for (auto &bs: breaks) RestoreFlowScope(bs, fctx.scope_saved_locals.back()); + fctx.scope_saved_locals.pop_back(); + } + + std::vector exit_states = {head}; + for (auto &bs: breaks) exit_states.push_back(std::move(bs)); + JoinFlowStates(exit_states, st); + return false; + } + case SyntaxTreeType::Break: { + if (fctx.loop_breaks) { + fctx.loop_breaks->push_back(UnwindFlowStateToLoopDepth(st, fctx)); } - FlowBlock(for_in->Block(), st, ir, is_top_level); - return; + return true; + } + case SyntaxTreeType::Continue: { + if (fctx.loop_continues) { + fctx.loop_continues->push_back(UnwindFlowStateToLoopDepth(st, fctx)); + } + return true; + } + case SyntaxTreeType::Return: { + AnnotateExprs(stmt, st, ir, fctx); + return true; } default: - // Break / Label / Goto / Return / ExprStmt 等无赋值语义,仅标注可能含的字段读。 - AnnotateExprs(stmt, st, ir); - return; + AnnotateExprs(stmt, st, ir, fctx); + return false; } } void TypeInferencer::JoinFlowStates(const std::vector &branch_states, FlowState &out) { - // 分别汇合 local 与 global;任一分支缺失该 key 或不一致 → 不写入 out(即 dynamic)。 - auto JoinOne = [](const std::vector &branches, const auto &selector, auto &out_map) { - out_map.clear(); + // local:保留所有分支共有的局部键(防止同名局部遮蔽消失而回退到 st.global), + // 但仅当所有分支都含同一非空 spec 时保留该 spec,否则置为空串(dynamic)。 + { + std::unordered_map joined_local; std::unordered_set keys; - for (const auto &bs: branches) { - const auto &m = selector(bs); - for (const auto &[k, v]: m) keys.insert(k); + for (const auto &bs: branch_states) { + for (const auto &[k, _]: bs.local) keys.insert(k); } for (const auto &k: keys) { + bool first = true; std::string consistent; bool conflict = false; - for (const auto &bs: branches) { - const auto &m = selector(bs); - const auto it = m.find(k); - if (it == m.end()) { + for (const auto &bs: branch_states) { + const auto it = bs.local.find(k); + if (it == bs.local.end() || it->second.empty()) { conflict = true; break; } - if (consistent.empty()) { + if (first) { consistent = it->second; + first = false; } else if (consistent != it->second) { conflict = true; break; } } - if (!conflict) out_map[k] = consistent; + joined_local[k] = conflict ? "" : consistent; } - }; - JoinOne(branch_states, [](const FlowState &s) -> const auto & { return s.local; }, out.local); - JoinOne(branch_states, [](const FlowState &s) -> const auto & { return s.global; }, out.global); + out.local = std::move(joined_local); + } + + // global:任一分支缺失该 key 或为空或不一致 → 不写入 out.global(即 dynamic)。 + { + std::unordered_map joined_global; + std::unordered_set keys; + for (const auto &bs: branch_states) { + for (const auto &[k, _]: bs.global) keys.insert(k); + } + for (const auto &k: keys) { + bool first = true; + std::string consistent; + bool conflict = false; + for (const auto &bs: branch_states) { + const auto it = bs.global.find(k); + if (it == bs.global.end() || it->second.empty()) { + conflict = true; + break; + } + if (first) { + consistent = it->second; + first = false; + } else if (consistent != it->second) { + conflict = true; + break; + } + } + if (!conflict) joined_global[k] = consistent; + } + out.global = std::move(joined_global); + } } -void TypeInferencer::ComputeVarSpecAnnotations(const ParseResult &pr, InferResult &ir) { - FlowState st; +void TypeInferencer::FlowFuncBody(const SyntaxTreeInterfacePtr &funcbody, const std::unordered_map &global_specs, const std::unordered_set &enclosing_locals, + const std::set> &mutated_captured_defs, InferResult &ir) { + if (!funcbody || funcbody->Type() != SyntaxTreeType::FuncBody) return; + const auto fb = std::dynamic_pointer_cast(funcbody); + if (!fb || !fb->Block()) return; - // 顶层 chunk:CGen 把非函数语句塞进 __fakelua_init,先处理顶层(写 global),再处理各函数。 + bool has_goto_or_label = false; + std::unordered_set goto_reassigned_names; + WalkSyntaxTreePruned(fb->Block(), [&](const SyntaxTreeInterfacePtr &n) -> bool { + if (!n) return false; + if (n->Type() == SyntaxTreeType::Function || n->Type() == SyntaxTreeType::LocalFunction || n->Type() == SyntaxTreeType::FunctionDef) { + return false; + } + if (n->Type() == SyntaxTreeType::Goto || n->Type() == SyntaxTreeType::Label) { + has_goto_or_label = true; + } else if (n->Type() == SyntaxTreeType::Assign) { + const auto assign = std::dynamic_pointer_cast(n); + const auto vl = assign ? std::dynamic_pointer_cast(assign->Varlist()) : nullptr; + if (vl && !vl->Vars().empty()) { + const auto v = std::dynamic_pointer_cast(vl->Vars()[0]); + if (v && v->GetVarKind() == VarKind::kSimple) { + goto_reassigned_names.insert(v->GetName()); + } + } + } + return true; + }); + + FlowState func_state; + func_state.global = global_specs; + for (const auto &ename: enclosing_locals) { + func_state.local[ename] = ""; + } + if (const auto parlist = std::dynamic_pointer_cast(fb->Parlist())) { + if (const auto nl = std::dynamic_pointer_cast(parlist->Namelist())) { + for (const auto &pname: nl->Names()) { + func_state.local[pname] = ""; + } + } + } + + FlowContext fctx; + fctx.is_top_level = false; + fctx.emit = true; + fctx.has_goto_or_label = has_goto_or_label; + fctx.mutated_captured_defs = &mutated_captured_defs; + fctx.goto_reassigned_names = has_goto_or_label ? &goto_reassigned_names : nullptr; + FlowBlock(fb->Block(), func_state, ir, fctx, true); +} + +void TypeInferencer::ComputeVarSpecAnnotations(const ParseResult &pr, InferResult &ir) { if (!pr.chunk || pr.chunk->Type() != SyntaxTreeType::Block) return; const auto top_block = std::dynamic_pointer_cast(pr.chunk); - // 收集函数定义(顶层函数 + 嵌套函数均独立作用域)。 - // __fakelua_init 对应 CGen 里"优先编译"的顶层 chunk 初始化函数:其内赋值写 global, - // 必须先于其它函数处理,才能使全局特化状态在后续函数读引用中可见。 + // 预扫描:找出所有被内层闭包捕获且在声明之外发生过再赋值的变量声明 (def_node, name)。 + std::set> mutated_captured_defs; + if (ar_ && !ar_->captured_var_nodes.empty()) { + std::vector> def_scopes; + std::function scan_captured_assigns = [&](const SyntaxTreeInterfacePtr &node) { + if (!node) return; + switch (node->Type()) { + case SyntaxTreeType::Block: { + const auto blk = std::dynamic_pointer_cast(node); + def_scopes.emplace_back(); + for (const auto &s: blk->Stmts()) scan_captured_assigns(s); + def_scopes.pop_back(); + break; + } + case SyntaxTreeType::Repeat: { + const auto rep = std::dynamic_pointer_cast(node); + def_scopes.emplace_back(); + if (const auto blk = std::dynamic_pointer_cast(rep->Block())) { + for (const auto &s: blk->Stmts()) scan_captured_assigns(s); + } + scan_captured_assigns(rep->Exp()); + def_scopes.pop_back(); + break; + } + case SyntaxTreeType::LocalVar: { + const auto lv = std::dynamic_pointer_cast(node); + scan_captured_assigns(lv->Explist()); + if (const auto nl = std::dynamic_pointer_cast(lv->Namelist())) { + for (const auto &n: nl->Names()) def_scopes.back()[n] = lv.get(); + } + break; + } + case SyntaxTreeType::ForLoop: { + const auto fl = std::dynamic_pointer_cast(node); + scan_captured_assigns(fl->ExpBegin()); + scan_captured_assigns(fl->ExpEnd()); + scan_captured_assigns(fl->ExpStep()); + def_scopes.emplace_back(); + def_scopes.back()[fl->Name()] = fl.get(); + scan_captured_assigns(fl->Block()); + def_scopes.pop_back(); + break; + } + case SyntaxTreeType::ForIn: { + const auto fi = std::dynamic_pointer_cast(node); + scan_captured_assigns(fi->Explist()); + def_scopes.emplace_back(); + if (const auto nl = std::dynamic_pointer_cast(fi->Namelist())) { + for (const auto &n: nl->Names()) def_scopes.back()[n] = fi.get(); + } + scan_captured_assigns(fi->Block()); + def_scopes.pop_back(); + break; + } + case SyntaxTreeType::Function: + case SyntaxTreeType::LocalFunction: + case SyntaxTreeType::FunctionDef: { + SyntaxTreeInterfacePtr fb_node; + if (node->Type() == SyntaxTreeType::LocalFunction) { + const auto lf = std::dynamic_pointer_cast(node); + if (!def_scopes.empty()) def_scopes.back()[lf->Name()] = lf.get(); + fb_node = lf->Funcbody(); + } else if (node->Type() == SyntaxTreeType::Function) { + fb_node = std::dynamic_pointer_cast(node)->Funcbody(); + } else { + fb_node = std::dynamic_pointer_cast(node)->Funcbody(); + } + def_scopes.emplace_back(); + if (const auto fb = std::dynamic_pointer_cast(fb_node)) { + if (const auto pl = std::dynamic_pointer_cast(fb->Parlist())) { + if (const auto nl = std::dynamic_pointer_cast(pl->Namelist())) { + for (const auto &p: nl->Names()) def_scopes.back()[p] = pl.get(); + } + } + scan_captured_assigns(fb->Block()); + } + def_scopes.pop_back(); + break; + } + case SyntaxTreeType::Assign: { + const auto assign = std::dynamic_pointer_cast(node); + if (const auto vl = std::dynamic_pointer_cast(assign->Varlist())) { + for (const auto &vn: vl->Vars()) { + const auto v = std::dynamic_pointer_cast(vn); + if (v && v->GetVarKind() == VarKind::kSimple && ar_->captured_var_nodes.contains(v.get())) { + for (auto it = def_scopes.rbegin(); it != def_scopes.rend(); ++it) { + if (const auto dit = it->find(v->GetName()); dit != it->end()) { + mutated_captured_defs.insert({dit->second, v->GetName()}); + break; + } + } + } + scan_captured_assigns(vn); + } + } + scan_captured_assigns(assign->Explist()); + break; + } + case SyntaxTreeType::If: { + const auto if_s = std::dynamic_pointer_cast(node); + scan_captured_assigns(if_s->Exp()); + scan_captured_assigns(if_s->Block()); + if (const auto elseifs = std::dynamic_pointer_cast(if_s->ElseIfs())) { + for (size_t i = 0; i < elseifs->ElseifSize(); ++i) { + scan_captured_assigns(elseifs->ElseifExp(i)); + scan_captured_assigns(elseifs->ElseifBlock(i)); + } + } + scan_captured_assigns(if_s->ElseBlock()); + break; + } + case SyntaxTreeType::While: { + const auto w = std::dynamic_pointer_cast(node); + scan_captured_assigns(w->Exp()); + scan_captured_assigns(w->Block()); + break; + } + case SyntaxTreeType::Return: + scan_captured_assigns(std::dynamic_pointer_cast(node)->Explist()); + break; + case SyntaxTreeType::FunctionCall: { + const auto fc = std::dynamic_pointer_cast(node); + scan_captured_assigns(fc->prefixexp()); + scan_captured_assigns(fc->Args()); + break; + } + case SyntaxTreeType::Args: { + const auto args = std::dynamic_pointer_cast(node); + scan_captured_assigns(args->Explist()); + scan_captured_assigns(args->Tableconstructor()); + scan_captured_assigns(args->String()); + break; + } + case SyntaxTreeType::ExpList: { + const auto el = std::dynamic_pointer_cast(node); + for (const auto &e: el->Exps()) scan_captured_assigns(e); + break; + } + case SyntaxTreeType::Exp: { + const auto e = std::dynamic_pointer_cast(node); + scan_captured_assigns(e->Left()); + scan_captured_assigns(e->Right()); + break; + } + case SyntaxTreeType::PrefixExp: + scan_captured_assigns(std::dynamic_pointer_cast(node)->GetValue()); + break; + case SyntaxTreeType::Var: { + const auto v = std::dynamic_pointer_cast(node); + scan_captured_assigns(v->GetPrefixexp()); + scan_captured_assigns(v->GetExp()); + break; + } + case SyntaxTreeType::TableConstructor: + scan_captured_assigns(std::dynamic_pointer_cast(node)->Fieldlist()); + break; + case SyntaxTreeType::FieldList: { + const auto fl = std::dynamic_pointer_cast(node); + for (const auto &f: fl->Fields()) scan_captured_assigns(f); + break; + } + case SyntaxTreeType::Field: { + const auto f = std::dynamic_pointer_cast(node); + scan_captured_assigns(f->Key()); + scan_captured_assigns(f->Value()); + break; + } + default: + break; + } + }; + scan_captured_assigns(pr.chunk); + } + + FlowState st; std::vector funcs; std::vector top_stmts; SyntaxTreeInterfacePtr init_func_stmt; const auto is_init = [](const SyntaxTreeInterfacePtr &stmt) -> bool { - // 与 CGen::CompileFuncName 等价:取函数名链表的唯一定段。 if (stmt->Type() == SyntaxTreeType::Function) { const auto f = std::dynamic_pointer_cast(stmt); const auto fn = std::dynamic_pointer_cast(f->Funcname()); @@ -2493,29 +3355,30 @@ void TypeInferencer::ComputeVarSpecAnnotations(const ParseResult &pr, InferResul } } - // 顶层语句(top_level=true → 赋值写 global)。 + FlowContext top_ctx; + top_ctx.is_top_level = true; + top_ctx.emit = true; + top_ctx.mutated_captured_defs = &mutated_captured_defs; for (const auto &stmt: top_stmts) { - FlowStmt(stmt, st, ir, true); + FlowStmt(stmt, st, ir, top_ctx); } - // 先处理 __fakelua_init,使其对全局变量的 spec 赋值流入后续函数。 if (init_func_stmt) { FlowState init_state; init_state.global = st.global; - if (auto bb = FuncBodyBlock(init_func_stmt)) FlowBlock(bb, init_state, ir, true); - // init 内的赋值写入 global(is_top_level=true),但本身也是函数作用域: - // 将 init 执行结束后的 global 作为后续函数的 global 基线。 + if (auto bb = FuncBodyBlock(init_func_stmt)) FlowBlock(bb, init_state, ir, top_ctx, false); st.global = std::move(init_state.global); } - // 各函数体:每函数清空 local(global 保持顶层/init 写入)。 + const std::unordered_set empty_enclosing; for (const auto &func: funcs) { - auto body_block = FuncBodyBlock(func); - if (!body_block) continue; - // 函数入口清空 local 作用域(对应 CGen 每函数清空 table_spec_types_)。 - FlowState func_state; - func_state.global = st.global; - FlowBlock(body_block, func_state, ir, false); + SyntaxTreeInterfacePtr funcbody; + if (func->Type() == SyntaxTreeType::Function) { + funcbody = std::dynamic_pointer_cast(func)->Funcbody(); + } else if (func->Type() == SyntaxTreeType::LocalFunction) { + funcbody = std::dynamic_pointer_cast(func)->Funcbody(); + } + FlowFuncBody(funcbody, st.global, empty_enclosing, mutated_captured_defs, ir); } } diff --git a/src/compile/type_inferencer.h b/src/compile/type_inferencer.h index 68d21a50..391f7c3c 100644 --- a/src/compile/type_inferencer.h +++ b/src/compile/type_inferencer.h @@ -1,6 +1,9 @@ #pragma once #include "compile/compile_common.h" +#include +#include +#include #include namespace fakelua { @@ -17,11 +20,17 @@ class TypeInferencer { private: struct TraversalContext; + using DeclOverrideKey = std::tuple; + using DeclOverrideMap = std::map; + class TypeEnvironment { public: struct EnvEntry { InferredType type; SyntaxTreeInterface *init_node = nullptr;// 变量声明时的 initializer node (如 local x = 1 中的 '1' 表达式) + const SyntaxTreeInterface *decl_node = nullptr; + size_t decl_slot = 0; + bool is_param = false; }; TypeEnvironment(); @@ -30,12 +39,15 @@ class TypeInferencer { void ExitScope(); - void Define(const std::string &name, InferredType type, SyntaxTreeInterface *init_node = nullptr); + void Define(const std::string &name, InferredType type, SyntaxTreeInterface *init_node = nullptr, const SyntaxTreeInterface *decl_node = nullptr, size_t decl_slot = 0, bool is_param = false); - InferredType Update(const std::string &name, InferredType type, EvalTypeSnapshot ¤t_map); + InferredType Update(const std::string &name, InferredType type, EvalTypeSnapshot ¤t_map, bool skip_post_processing = false, DeclOverrideMap *decl_overrides = nullptr, + bool *any_widened = nullptr, bool loop_carried = false); [[nodiscard]] bool Has(const std::string &name) const; + [[nodiscard]] bool IsParamBinding(const std::string &name) const; + [[nodiscard]] InferredType Lookup(const std::string &name) const; [[nodiscard]] const SyntaxTreeInterface *LookupInitNode(const std::string &name) const; @@ -44,7 +56,6 @@ class TypeInferencer { return scopes_.size() <= 2; } - private: static InferredType MergeType(InferredType old_type, InferredType new_type); private: @@ -95,13 +106,17 @@ class TypeInferencer { const TrialInferenceContext *ctx = nullptr; std::unordered_map &var_define_nodes; std::set> &shadowed_decls; + DeclOverrideMap decl_type_overrides{}; + bool any_decl_widened = false; + // 仅循环(含 repeat)体内的拓宽才触发不动点重跑。直线上后一次赋值不能把前面已经算完的表达式改成最终类型。 + int loop_depth = 0; [[nodiscard]] bool IsTrialInference() const { return ctx != nullptr; } [[nodiscard]] bool IsPinnedVar(const std::string &name) const { - return ctx && ctx->pinned_vars && ctx->pinned_vars->contains(name); + return ctx && ctx->pinned_vars && ctx->pinned_vars->contains(name) && env.IsParamBinding(name); } [[nodiscard]] bool SkipPostProcessing() const { @@ -229,6 +244,7 @@ class TypeInferencer { // 将 src 的字段并集到 dst(按 key 描述符去重,已存在则保留 dst 中的条目)。 static void MergeFieldsInto(std::vector &dst, const std::vector &src); +public: // 流敏感 table 特化前向分析 // 为每个 Var 引用节点(kDot/kSquare 的 prefixexp 所指简单变量)标注 // 「在该程序点,该变量的 spec 类型名是什么(空串 = dynamic)」。 @@ -242,8 +258,23 @@ class TypeInferencer { struct FlowState { std::unordered_map local; std::unordered_map global; + + bool operator==(const FlowState &other) const = default; }; + struct FlowContext { + bool is_top_level = false; + bool emit = true; + bool has_goto_or_label = false; + const std::set> *mutated_captured_defs = nullptr; + const std::unordered_set *goto_reassigned_names = nullptr; + std::vector *loop_breaks = nullptr; + std::vector *loop_continues = nullptr; + size_t loop_scope_depth = 0; + std::vector>> scope_saved_locals; + }; + +private: // 在流状态中查找某变量名的 spec 类型名(local 优先,fallback 到 global;都无 = 空串)。 static std::string LookupSpec(const FlowState &st, const std::string &name); @@ -254,13 +285,17 @@ class TypeInferencer { // 对一棵表达式子树里所有被读取的 Var(kDot/kSquare) 引用节点做标注: // 把 receiver 指代变量在当前流状态下的 spec 类型名写入 ir.var_spec_annotations[node]。 // FAKELUA_SET_TABLE(args[0]) 走独立分支,receiver 为 args[0] 那段 Exp。 - void AnnotateExprs(const SyntaxTreeInterfacePtr &node, FlowState &st, InferResult &ir); + void AnnotateExprs(const SyntaxTreeInterfacePtr &node, FlowState &st, InferResult &ir, const FlowContext &fctx); + + // 顺序处理一条语句:先标注该语句中所有 Var 引用再按语义更新流状态。返回是否无条件跳转离开当前块。 + bool FlowStmt(const SyntaxTreeInterfacePtr &stmt, FlowState &st, InferResult &ir, FlowContext &fctx); - // 顺序处理一条语句:先标注该语句中所有 Var 引用再按语义更新流状态。 - void FlowStmt(const SyntaxTreeInterfacePtr &stmt, FlowState &st, InferResult &ir, bool is_top_level); + // 顺序处理一个语句块(可选开启独立词法作用域并在退出时还原遮蔽局部)。 + bool FlowBlock(const SyntaxTreeInterfacePtr &block, FlowState &st, InferResult &ir, FlowContext &fctx, bool new_scope = false); - // 顺序处理一个语句块。 - void FlowBlock(const SyntaxTreeInterfacePtr &block, FlowState &st, InferResult &ir, bool is_top_level); + // 对单个函数体(顶层或嵌套函数/匿名闭包)运行前向流分析。 + void FlowFuncBody(const SyntaxTreeInterfacePtr &funcbody, const std::unordered_map &global_specs, const std::unordered_set &enclosing_locals, + const std::set> &mutated_captured_defs, InferResult &ir); // 入口:对整个模块(顶层 chunk + 所有函数体)跑前向流分析,填充 ir.var_spec_annotations。 void ComputeVarSpecAnnotations(const ParseResult &pr, InferResult &ir); diff --git a/src/interp/codegen.cpp b/src/interp/codegen.cpp index 8ad0981f..777450f2 100644 --- a/src/interp/codegen.cpp +++ b/src/interp/codegen.cpp @@ -231,6 +231,10 @@ bool InterpCodegen::IsPackageHeaderStmt(const SyntaxTreeInterfacePtr &stmt) cons return ExtractPackageName(stmt, ignored); } +bool InterpCodegen::IsLocalVarAssigned(const VarDef *def) const { + return def != nullptr && def->is_assigned; +} + CVar InterpCodegen::LiteralFromExp(const SyntaxTreeInterfacePtr &exp) { CVar v = interp_rt::Nil(); if (!exp || exp->Type() != SyntaxTreeType::Exp) return v; @@ -286,9 +290,20 @@ int InterpCodegen::ResolveSimpleName(const SyntaxTreeVar *var, const std::string if (def->defining_func == cur_func_ || def->defining_func != nullptr) { return LoadLocal(def); } - // 文件级 local function:没有函数内局部槽,按注册原型构造闭包(对齐 CGen FlMakeClosure)。 - } - if (const auto nit = named_protos_.find(name); nit != named_protos_.end()) { + // 文件级 local function:没有函数内局部槽,按绑定定义节点的原型构造闭包(对齐 CGen FlMakeClosure)。 + if (def->def_node && def->def_node->Type() == SyntaxTreeType::LocalFunction) { + if (const auto fit = func_map_.find(def->def_node); fit != func_map_.end() && (check_only_ || fit->second->proto)) { + const int r = AllocReg(); + int idx = 0; + if (!check_only_) { + idx = static_cast(cur_proto_->child_protos.size()); + cur_proto_->child_protos.push_back(fit->second->proto); + } + Emit(Op::CLOSURE, r, 0, 0, idx); + return r; + } + } + } else if (const auto nit = named_protos_.find(name); nit != named_protos_.end()) { const int r = AllocReg(); int idx = 0; if (!check_only_) { @@ -534,6 +549,16 @@ void InterpCodegen::ResolveScopes(const SyntaxTreeInterfacePtr &node, std::vecto const auto assign = std::dynamic_pointer_cast(node); ResolveScopes(assign->Varlist(), scopes, func_stack, cur_func); ResolveScopes(assign->Explist(), scopes, func_stack, cur_func); + if (const auto vl = std::dynamic_pointer_cast(assign->Varlist())) { + for (const auto &v: vl->Vars()) { + const auto var = std::dynamic_pointer_cast(v); + if (var && var->GetVarKind() == VarKind::kSimple) { + if (const auto it = var_to_def_map_.find(var.get()); it != var_to_def_map_.end()) { + it->second->is_assigned = true; + } + } + } + } break; } case SyntaxTreeType::FunctionCall: { @@ -671,7 +696,7 @@ void InterpCodegen::CompileFunction(FuncInfo *func) { func->compiled = true; const int prev_check_ip = check_ip_; check_ip_ = 0; - if (!check_only_) { + if (!check_only_ && !func->proto) { auto proto = std::make_unique(); proto->unit = unit_; proto->name = LuaCallFrameName(func->name, func->parent == nullptr, cur_package_name_); @@ -682,10 +707,17 @@ void InterpCodegen::CompileFunction(FuncInfo *func) { unit_->protos.push_back(std::move(proto)); } - if (func->parent == nullptr && !func->unique_c_name.empty()) { - named_protos_[func->unique_c_name] = func->proto; - if (!func->name.empty() && func->name != func->unique_c_name) { - named_protos_[func->name] = func->proto; + if (func->parent == nullptr) { + const bool is_local_fn = func->node && func->node->Type() == SyntaxTreeType::LocalFunction; + if (is_local_fn) { + if (!check_only_ && !func->name.empty()) { + unit_->local_funcs[func->name] = func->proto; + } + } else if (!func->unique_c_name.empty()) { + named_protos_[func->unique_c_name] = func->proto; + if (!func->name.empty() && func->name != func->unique_c_name) { + named_protos_[func->name] = func->proto; + } } } @@ -1205,6 +1237,12 @@ void InterpCodegen::CompileStmtForIn(const SyntaxTreeInterfacePtr &stmt) { } StoreLocal(defs[1]->reg, vreg); } + for (size_t i = 2; i < defs.size(); ++i) { + if (defs[i]->is_captured) { + Emit(Op::NEWBOX, defs[i]->reg); + } + Emit(Op::LOADNIL, defs[i]->reg); + } }; if (kind == PairsIpairsKind::kIpairs) { const int tbl = CompileExp(tbl_exp_node, false); @@ -1463,7 +1501,8 @@ int InterpCodegen::CompilePrefixexp(const SyntaxTreeInterfacePtr &pe, bool prese if (pe_ptr->GetPrefixKind() == PrefixExpKind::kFunctionCall) { return CommitDest(dest, CompileFunctioncall(pe_ptr->GetValue(), preserve_multi)); } - return CompileExp(pe_ptr->GetValue(), preserve_multi, dest); + // Lua 语义:括号表达式 `(exp)` 强制把多返回值与 `...` 截断成单个标量值。 + return CompileExp(pe_ptr->GetValue(), false, dest); } int InterpCodegen::CompileVar(const SyntaxTreeInterfacePtr &v) { @@ -1589,7 +1628,7 @@ int InterpCodegen::CompileFunctioncall(const SyntaxTreeInterfacePtr &functioncal std::vector arg_regs; bool last_expand = false; - auto self_tail_c = [&](int n, bool named, const std::string &name, bool self_closure) -> int { + auto self_tail_c = [&](int n, bool named, const std::string &name, bool self_closure, bool local_unit_func = false, const SyntaxTreeInterface *local_def_node = nullptr) -> int { if (!is_tail || last_expand || !cur_func_ || cur_func_->is_vararg || !cur_func_->proto) { return 0; } @@ -1599,17 +1638,22 @@ int InterpCodegen::CompileFunctioncall(const SyntaxTreeInterfacePtr &functioncal if (self_closure) { return kTailSelfExact; } - if (named && !name.empty()) { - if (name == cur_func_->name || name == cur_func_->unique_c_name) { - return kTailSelfExact; + if (named && cur_func_->parent == nullptr && !name.empty()) { + if (cur_func_->node && cur_func_->node->Type() == SyntaxTreeType::LocalFunction) { + return (local_unit_func && local_def_node == cur_func_->node) ? kTailSelfExact : 0; } - if (!cur_package_name_.empty() && !cur_func_->name.empty() && name == cur_package_name_ + "." + cur_func_->name) { - return kTailSelfExact; + if (!local_unit_func) { + if (name == cur_func_->name || name == cur_func_->unique_c_name) { + return kTailSelfExact; + } + if (!cur_package_name_.empty() && !cur_func_->name.empty() && name == cur_package_name_ + "." + cur_func_->name) { + return kTailSelfExact; + } } } return 0; }; - auto place_callname = [&](const std::string &name, const std::vector &args) { + auto place_callname = [&](const std::string &name, const std::vector &args, bool local_unit_func = false, const SyntaxTreeInterface *local_def_node = nullptr) { const int n = static_cast(args.size()); // 末尾是 f() / ... 这类展开时实参个数运行期才知道,检查不了。 if (!last_expand) { @@ -1631,7 +1675,10 @@ int InterpCodegen::CompileFunctioncall(const SyntaxTreeInterfacePtr &functioncal } stack_top_ = base + n; } - const int c = is_tail ? self_tail_c(n, true, name, false) : unbox; + int c = is_tail ? self_tail_c(n, true, name, false, local_unit_func, local_def_node) : unbox; + if (local_unit_func) { + c |= kCallLocalUnit; + } Emit(is_tail ? Op::TAILNAME : Op::CALLNAME, base, n, c, AddStringConst(name)); stack_top_ = base + 1; return base; @@ -1685,7 +1732,18 @@ int InterpCodegen::CompileFunctioncall(const SyntaxTreeInterfacePtr &functioncal final_args.push_back(method_obj); for (int a: arg_regs) final_args.push_back(a); if (kStringLibraryMethods.contains(fc->Name())) { - return place_callname("string." + fc->Name(), final_args); + const int n = static_cast(final_args.size()); + const int base = stack_top_; + EnsureStack(base + n); + for (int i = 0; i < n; ++i) { + MoveTo(base + i, final_args[i]); + } + stack_top_ = base + n; + const int k = AddStringConst(fc->Name()); + (void) AddStringConst("string." + fc->Name()); + Emit(Op::STRMETHOD, base, n, is_tail ? kStrMethodTail : unbox, k); + stack_top_ = base + 1; + return base; } const int k = AllocReg(); CVar key{}; @@ -1699,6 +1757,7 @@ int InterpCodegen::CompileFunctioncall(const SyntaxTreeInterfacePtr &functioncal std::string func_name; const SyntaxTreeVar *var_ptr = nullptr; + const SyntaxTreeInterface *local_def_node = nullptr; bool is_local_callee = false; bool file_level_func = false; if (pe_pre_ptr->GetPrefixKind() == PrefixExpKind::kVar) { @@ -1708,11 +1767,14 @@ int InterpCodegen::CompileFunctioncall(const SyntaxTreeInterfacePtr &functioncal var_ptr = var.get(); if (const auto it = var_to_def_map_.find(var_ptr); it != var_to_def_map_.end()) { is_local_callee = true; - // 只有文件级 local function 才能走 CALLNAME:named_protos_ 只登记 - // 函数定义。文件级 local 变量(如 local gv = f)即使 defining_func - // 为 nullptr 也不在 named_protos_ 里,必须按闭包调用,否则运行时报 - // "function 'gv' not found"(C 后端此处按闭包处理,行为一致)。 + local_def_node = it->second->def_node; + // 只有文件级 local function 才能走 CALLNAME:local_funcs 只登记 + // 文件级 local function。文件级 local 变量(如 local gv = f)即使 defining_func + // 为 nullptr 也必须按闭包调用(与 C 后端一致)。 file_level_func = it->second->defining_func == nullptr && it->second->def_node != nullptr && it->second->def_node->Type() == SyntaxTreeType::LocalFunction; + } else if (!cur_package_name_.empty() && pkg_func_names_.contains(func_name)) { + // 本 package 内导出的同名函数走包限定名,既与其他 package 的同名函数隔离,又保留本包热更新语义。 + func_name = cur_package_name_ + "." + func_name; } } else if (var && var->GetVarKind() == VarKind::kDot) { const auto base_pe = var->GetPrefixexp(); @@ -1729,9 +1791,8 @@ int InterpCodegen::CompileFunctioncall(const SyntaxTreeInterfacePtr &functioncal } // 形参、局部变量、嵌套 local function 即使与文件级函数同名,也必须调用这个绑定。 - // named_protos_ 只登记文件级函数,不能拿来覆盖局部值。 if (!func_name.empty() && (!is_local_callee || file_level_func)) { - return place_callname(func_name, arg_regs); + return place_callname(func_name, arg_regs, file_level_func, local_def_node); } int fn; @@ -1742,7 +1803,7 @@ int InterpCodegen::CompileFunctioncall(const SyntaxTreeInterfacePtr &functioncal } bool self_closure = false; if (is_tail && is_local_callee && var_ptr && cur_func_ && cur_func_->node) { - if (const auto it = var_to_def_map_.find(var_ptr); it != var_to_def_map_.end() && it->second->def_node == cur_func_->node) { + if (const auto it = var_to_def_map_.find(var_ptr); it != var_to_def_map_.end() && it->second->def_node == cur_func_->node && !IsLocalVarAssigned(it->second)) { self_closure = true; } } @@ -1909,6 +1970,7 @@ void InterpCodegen::Walk(const ParseResult &pr, const AnalysisResult &ar) { ar_ = &ar; cur_package_name_.clear(); + pkg_func_names_.clear(); if (pr.chunk && pr.chunk->Type() == SyntaxTreeType::Block) { const auto blk = std::dynamic_pointer_cast(pr.chunk); const std::vector *stmts_to_check = &blk->Stmts(); @@ -1949,6 +2011,10 @@ void InterpCodegen::Walk(const ParseResult &pr, const AnalysisResult &ar) { const std::pair sig(static_cast(func->params.size()), func->is_vararg); if (!func->name.empty()) file_func_sigs_[func->name] = sig; if (!func->unique_c_name.empty()) file_func_sigs_[func->unique_c_name] = sig; + if (!cur_package_name_.empty() && func->node && func->node->Type() == SyntaxTreeType::Function && func->unique_c_name != kInitFunctionName && !func->name.empty()) { + pkg_func_names_.insert(func->name); + file_func_sigs_[cur_package_name_ + "." + func->name] = sig; + } } if (!check_only_) { @@ -1956,6 +2022,31 @@ void InterpCodegen::Walk(const ParseResult &pr, const AnalysisResult &ar) { unit_hold_->state = s_; unit_hold_->file_name = pr.file_name; unit_ = unit_hold_.get(); + + // 预先创建所有文件级函数原型并登记到 local_funcs / named_protos_,支持文件级函数前向值引用。 + for (const auto &func: all_funcs_) { + if (func->parent != nullptr) continue; + auto proto = std::make_unique(); + proto->unit = unit_; + proto->name = LuaCallFrameName(func->name, true, cur_package_name_); + proto->param_count = static_cast(func->params.size()); + proto->is_vararg = func->is_vararg; + proto->max_stack = proto->param_count; + func->proto = proto.get(); + unit_->protos.push_back(std::move(proto)); + + const bool is_local_fn = func->node && func->node->Type() == SyntaxTreeType::LocalFunction; + if (is_local_fn) { + if (!func->name.empty()) { + unit_->local_funcs[func->name] = func->proto; + } + } else if (!func->unique_c_name.empty()) { + named_protos_[func->unique_c_name] = func->proto; + if (!func->name.empty() && func->name != func->unique_c_name) { + named_protos_[func->name] = func->proto; + } + } + } } if (pr.chunk && pr.chunk->Type() == SyntaxTreeType::Block) { @@ -1991,6 +2082,8 @@ void InterpCodegen::RegisterAndInit() { } const auto handle = std::static_pointer_cast(unit_hold_); + s_->RetainJitHandle(handle); + for (const auto &func: all_funcs_) { if (func->parent != nullptr || !func->proto) continue; const std::string &c_name = func->unique_c_name; @@ -2006,10 +2099,20 @@ void InterpCodegen::RegisterAndInit() { } } + auto sync_vm_version = [&]() { + const uint64_t vm_ver = *s_->GetVM().VersionPtr(); + unit_->vm_version = vm_ver; + for (auto &p: unit_->protos) { + p->self_tail_vm_version = vm_ver; + } + }; + sync_vm_version(); + if (unit_->init_proto) { // ConstAllocScope:init 期间 NewTable 创建即带 CONST_FLAG(与 JIT SET_TABLE 对齐)。 State::ConstAllocScope const_alloc(s_); InterpreterExecute(s_, unit_->init_proto, nullptr, 0, nullptr); + sync_vm_version(); } } diff --git a/src/interp/codegen.h b/src/interp/codegen.h index bee9d587..769743b2 100644 --- a/src/interp/codegen.h +++ b/src/interp/codegen.h @@ -44,6 +44,7 @@ class InterpCodegen { const SyntaxTreeInterface *def_node = nullptr; FuncInfo *defining_func = nullptr; bool is_captured = false; + bool is_assigned = false; int reg = -1; }; @@ -131,6 +132,7 @@ class InterpCodegen { int EmitThrow(const std::string &msg); bool LastPreservesMulti(const SyntaxTreeInterfacePtr &exp) const; bool IsPackageHeaderStmt(const SyntaxTreeInterfacePtr &stmt) const; + bool IsLocalVarAssigned(const VarDef *def) const; CVar LiteralFromExp(const SyntaxTreeInterfacePtr &exp); [[noreturn]] void ThrowError(const std::string &msg, const SyntaxTreeInterfacePtr &ptr); @@ -160,6 +162,7 @@ class InterpCodegen { // 静默补 nil,三个后端语义就不一致了。 std::unordered_map> file_func_sigs_; std::string cur_package_name_; + std::unordered_set pkg_func_names_; std::unordered_set file_level_names_; FuncInfo *cur_func_ = nullptr; diff --git a/src/interp/func_proto.h b/src/interp/func_proto.h index c689336f..9c5c16e6 100644 --- a/src/interp/func_proto.h +++ b/src/interp/func_proto.h @@ -32,9 +32,11 @@ struct TransparentStringHash { struct InterpUnit final : JITHandle { std::vector> protos; std::unordered_map> globals; + std::unordered_map> local_funcs; std::unordered_set const_global_names; FuncProto *init_proto = nullptr; State *state = nullptr; + uint64_t vm_version = 0; // 运行期报错时附带的源文件名,随 FuncProto::lineinfo 一起定位到语句。 std::string file_name; }; @@ -47,6 +49,8 @@ struct FuncProto { int max_stack = 0; // 本函数有被捕获的局部(NEWBOX / CLOSURE in_stack)。无捕获时解释器走纯栈寄存器路径。 bool uses_boxes = false; + // 自尾调用热更新校验缓存的 VM 版本号:版本一致时跳过查表,版本变化后校验一次并刷新。 + uint64_t self_tail_vm_version = 0; std::vector code; std::vector constants; std::vector upvalues; diff --git a/src/interp/interpreter.cpp b/src/interp/interpreter.cpp index 37d13a5d..0b569ba8 100644 --- a/src/interp/interpreter.cpp +++ b/src/interp/interpreter.cpp @@ -227,6 +227,18 @@ int PackNamedCallArgs(State *s, std::string_view name, bool is_vararg, int expec return expected; } +CVar CallUnitLocalProto(State *s, std::string_view name, FuncProto *callee, const CVar *raw, int nargs) { + const bool last_is_multi = (nargs > 0 && raw[nargs - 1].type_ == static_cast(VarType::Multi)); + if (FL_VM_LIKELY(!callee->is_vararg && !last_is_multi && nargs == callee->param_count)) { + return InterpExecuteInContext(s, callee, raw, nargs, nullptr); + } + CVar flat[kMaxFunctionInputParams]; + const int nflat = FlattenByNameArgs(raw, nargs, flat); + CVar packed[kMaxFunctionInputParams]; + const int n_dispatch = PackNamedCallArgs(s, name, callee->is_vararg, callee->param_count, raw, nargs, flat, nflat, packed); + return InterpExecuteInContext(s, callee, packed, n_dispatch, nullptr); +} + // 在本 InterpreterExecuteT 帧内切到新的 INTERP 原型;需要换 HasBoxes 模板或扩容时走 trampoline。 // 成功且应继续分发返回 true(已更新 proto/cl/ip/stk);应 return ret 则返回 false。 template @@ -361,7 +373,7 @@ bool InterpDoTail(State *s, FuncProto *&proto, VarClosure *&cl, CVar *const stk, } VarClosure *callee = fn.data_.cl; if (!IsInterpClosure(callee)) { - ret = inter::DispatchCallClosure(s, callee, call_args, nflat, JIT_INTERP); + ret = inter::DispatchCallClosure(s, callee, call_args, nflat, IsGccClosure(callee) ? JIT_GCC : JIT_INTERP); return false; } CVar packed[kMaxFunctionInputParams]; @@ -383,6 +395,16 @@ bool InterpDoTailName(State *s, FuncProto *&proto, VarClosure *&cl, CVar *const for (int i = 0; i < nargs; ++i) { raw[i] = interp_rt::VmSlot(stk, boxp, inst.a + i); } + if ((inst.c & kCallLocalUnit) != 0 && proto->unit) { + if (const auto it = proto->unit->local_funcs.find(name); it != proto->unit->local_funcs.end() && it->second) { + FuncProto *callee = it->second; + CVar flat[kMaxFunctionInputParams]; + const int nflat = FlattenByNameArgs(raw, nargs, flat); + CVar packed[kMaxFunctionInputParams]; + const int n_dispatch = PackNamedCallArgs(s, name, callee->is_vararg, callee->param_count, raw, nargs, flat, nflat, packed); + return ApplyInterpTail(s, proto, cl, stk, boxp, saved, ip, callee, nullptr, packed, n_dispatch, ret); + } + } const VmFunction *fn = s->GetVM().FindFunction(name); if (fn) { void *addr = fn->GetAddr(JIT_INTERP); @@ -405,6 +427,91 @@ bool InterpDoTailName(State *s, FuncProto *&proto, VarClosure *&cl, CVar *const return false; } +template +#if defined(__GNUC__) +__attribute__((noinline)) +#endif +bool InterpDoStrMethod(State *s, FuncProto *&proto, VarClosure *&cl, CVar *const stk, CVar **const boxp, size_t saved, const Inst *&ip, const Inst &inst, CVar &ret) { + const size_t kidx = static_cast(inst.sbx); + const std::string_view full_name = ConstToName(proto->constants[kidx + 1]); + const int nargs = inst.b; + if (nargs < 1 || nargs > static_cast(kMaxFunctionInputParams)) { + ThrowFakeluaException(std::format("interpreter: too many arguments ({}) passed for function '{}', max is {}", nargs, full_name, kMaxFunctionInputParams)); + } + const CVar self = interp_rt::VmSlot(stk, boxp, inst.a); + if (self.type_ == interp_rt::kTable) { + const CVar key = proto->constants[kidx]; + const CVar fn = table::TableHelper::GetTable(s, self, key); + if (fn.type_ != static_cast(VarType::Closure) || !fn.data_.cl) { + ThrowFakeluaException("attempt to call a non-function value"); + } + CVar call_args[kMaxFunctionInputParams]; + int nflat = 0; + call_args[nflat++] = interp_rt::UnboxMulti(self, 0); + for (int i = 1; i < nargs; ++i) { + CVar av = interp_rt::VmSlot(stk, boxp, inst.a + i); + if (i == nargs - 1 && av.type_ == static_cast(VarType::Multi)) { + VarMulti *m = av.data_.m; + const int extra = m ? static_cast(m->GetCount()) : 0; + if (nflat + extra > static_cast(kMaxFunctionInputParams)) { + ThrowFakeluaException(std::format("interpreter: too many arguments ({}), max is {}", nflat + extra, kMaxFunctionInputParams)); + } + if (m) { + for (uint32_t j = 0; j < m->GetCount(); ++j) { + call_args[nflat++] = m->GetVars()[j]; + } + } + } else { + call_args[nflat++] = interp_rt::UnboxMulti(av, 0); + } + } + VarClosure *callee = fn.data_.cl; + if (inst.c == kStrMethodTail) { + if (!IsInterpClosure(callee)) { + ret = inter::DispatchCallClosure(s, callee, call_args, nflat, IsGccClosure(callee) ? JIT_GCC : JIT_INTERP); + return false; + } + CVar packed[kMaxFunctionInputParams]; + const int n_dispatch = PackClosureCallArgs(s, callee, call_args, nflat, packed); + return ApplyInterpTail(s, proto, cl, stk, boxp, saved, ip, AsInterpProto(callee->func_ptr), callee, packed, n_dispatch, ret); + } + CVar mret; + if (IsInterpClosure(callee) && !callee->is_vararg && callee->expected_arg_count == nflat && nflat <= static_cast(kMaxFunctionInputParams)) { + mret = InterpExecuteInContext(s, AsInterpProto(callee->func_ptr), call_args, nflat, callee); + } else { + mret = inter::DispatchCallClosure(s, callee, call_args, nflat, IsGccClosure(callee) ? JIT_GCC : JIT_INTERP); + } + interp_rt::VmWrite(stk, boxp, inst.a, inst.c == 0 ? mret : interp_rt::UnboxMulti(mret, 0)); + return true; + } + + CVar raw[kMaxFunctionInputParams]; + for (int i = 0; i < nargs; ++i) { + raw[i] = interp_rt::VmSlot(stk, boxp, inst.a + i); + } + if (inst.c == kStrMethodTail) { + const VmFunction *fn = s->GetVM().FindFunction(full_name); + if (fn) { + void *addr = fn->GetAddr(JIT_INTERP); + if (addr) { + CVar flat[kMaxFunctionInputParams]; + const int nflat = FlattenByNameArgs(raw, nargs, flat); + CVar packed[kMaxFunctionInputParams]; + const int n_dispatch = PackNamedCallArgs(s, full_name, fn->IsVararg(), fn->GetArgCount(), raw, nargs, flat, nflat, packed); + return ApplyInterpTail(s, proto, cl, stk, boxp, saved, ip, AsInterpProto(addr), nullptr, packed, n_dispatch, ret); + } + } + ret = CallByNameArgs(s, JIT_INTERP, full_name, nargs, raw); + return false; + } + CVar sret; + if (!TryInterpNamedCall(s, full_name, raw, nargs, sret)) { + sret = CallByNameArgs(s, JIT_INTERP, full_name, nargs, raw); + } + interp_rt::VmWrite(stk, boxp, inst.a, inst.c == 0 ? sret : interp_rt::UnboxMulti(sret, 0)); + return true; +} + constexpr size_t kInterpStackReserve = 262144;// 4 MiB of CVar; nested realloc would invalidate parent pointers struct InterpFrame { @@ -535,13 +642,23 @@ CVar InterpreterExecuteT(State *s, FuncProto *proto, const CVar *args, int arg_c if (!cl || inst.b >= static_cast(cl->upvalue_count) || !cl->upvalues[inst.b]) { VM_W(inst.a, interp_rt::Nil()); } else { - VM_W(inst.a, *cl->upvalues[inst.b]); + CVar uv = *cl->upvalues[inst.b]; + uv.flag_ &= ~interp_rt::kConstBoxFlag; + VM_W(inst.a, uv); } VM_DISPATCH_NEXT(); } VM_CASE(SETUPVAL) { if (cl && inst.b < static_cast(cl->upvalue_count) && cl->upvalues[inst.b]) { - *cl->upvalues[inst.b] = VM_R(inst.a); + CVar *const box = cl->upvalues[inst.b]; + CVar v = VM_R(inst.a); + if (FL_VM_UNLIKELY((box->flag_ & interp_rt::kConstBoxFlag) != 0)) { + if (!s->InterpConstAlloc()) { + v = PromoteConstBoxValue(s, v); + } + v.flag_ |= interp_rt::kConstBoxFlag; + } + *box = v; } VM_DISPATCH_NEXT(); } @@ -575,6 +692,11 @@ CVar InterpreterExecuteT(State *s, FuncProto *proto, const CVar *args, int arg_c } else { auto *box = static_cast(interp_rt::Alloc(s, sizeof(CVar))); *box = VM_R(inst.a); + if (s->InterpConstAlloc()) { + box->flag_ |= interp_rt::kConstBoxFlag; + } else { + box->flag_ &= ~interp_rt::kConstBoxFlag; + } boxp[inst.a] = box; } VM_DISPATCH_NEXT(); @@ -710,7 +832,7 @@ CVar InterpreterExecuteT(State *s, FuncProto *proto, const CVar *args, int arg_c if (IsInterpClosure(callee) && !callee->is_vararg && callee->expected_arg_count == nflat && nflat <= static_cast(kMaxFunctionInputParams)) { ret = InterpExecuteInContext(s, AsInterpProto(callee->func_ptr), call_args, nflat, callee); } else { - ret = inter::DispatchCallClosure(s, callee, call_args, nflat, JIT_INTERP); + ret = inter::DispatchCallClosure(s, callee, call_args, nflat, IsGccClosure(callee) ? JIT_GCC : JIT_INTERP); } VM_W(inst.a, inst.c == 0 ? ret : interp_rt::UnboxMulti(ret, 0)); VM_DISPATCH_NEXT(); @@ -731,10 +853,17 @@ CVar InterpreterExecuteT(State *s, FuncProto *proto, const CVar *args, int arg_c call_args[i] = VM_R(inst.a + i); } CVar ret; - if (!TryInterpNamedCall(s, name, call_args, nargs, ret)) { + bool handled = false; + if ((inst.c & kCallLocalUnit) != 0 && proto->unit) { + if (const auto it = proto->unit->local_funcs.find(name); it != proto->unit->local_funcs.end() && it->second) { + ret = CallUnitLocalProto(s, name, it->second, call_args, nargs); + handled = true; + } + } + if (!handled && !TryInterpNamedCall(s, name, call_args, nargs, ret)) { ret = CallByNameArgs(s, JIT_INTERP, name, nargs, call_args); } - VM_W(inst.a, inst.c == 0 ? ret : interp_rt::UnboxMulti(ret, 0)); + VM_W(inst.a, (inst.c & 1) == 0 ? ret : interp_rt::UnboxMulti(ret, 0)); } VM_DISPATCH_NEXT(); } @@ -756,11 +885,27 @@ CVar InterpreterExecuteT(State *s, FuncProto *proto, const CVar *args, int arg_c } VM_CASE(TAILNAME) { NoteInterpCallLine(s, proto, ip); - if (inst.c == kTailSelfExact) { - if (ReuseFrameSelfTail(s, proto, stk, boxp, ip, inst.a, inst.b)) { - VM_DISPATCH_NEXT(); + if ((inst.c & kTailSelfExact) != 0) { + bool self_ok = (inst.c & kCallLocalUnit) != 0; + if (!self_ok) { + const uint64_t cur_ver = *s->GetVM().VersionPtr(); + if (FL_VM_LIKELY(cur_ver == proto->self_tail_vm_version)) { + self_ok = true; + } else { + const std::string_view name = ConstToName(proto->constants[static_cast(inst.sbx)]); + const VmFunction *fn = s->GetVM().FindFunction(name); + if (fn && fn->GetAddr(JIT_INTERP) == TagInterpProto(proto)) { + proto->self_tail_vm_version = cur_ver; + self_ok = true; + } + } + } + if (FL_VM_LIKELY(self_ok)) { + if (ReuseFrameSelfTail(s, proto, stk, boxp, ip, inst.a, inst.b)) { + VM_DISPATCH_NEXT(); + } + return interp_rt::Nil(); } - return interp_rt::Nil(); } CVar ret{}; const bool cont = InterpDoTailName(s, proto, cl, stk, boxp, frame.saved, ip, inst, ret); @@ -787,6 +932,11 @@ CVar InterpreterExecuteT(State *s, FuncProto *proto, const CVar *args, int arg_c if (!boxp[uv.idx]) { auto *box = static_cast(interp_rt::Alloc(s, sizeof(CVar))); *box = VM_R(uv.idx); + if (s->InterpConstAlloc()) { + box->flag_ |= interp_rt::kConstBoxFlag; + } else { + box->flag_ &= ~interp_rt::kConstBoxFlag; + } boxp[uv.idx] = box; } upbufs[i] = boxp[uv.idx]; @@ -896,6 +1046,14 @@ CVar InterpreterExecuteT(State *s, FuncProto *proto, const CVar *args, int arg_c } VM_DISPATCH_NEXT(); } + VM_CASE(STRMETHOD) { + NoteInterpCallLine(s, proto, ip); + CVar ret{}; + if (InterpDoStrMethod(s, proto, cl, stk, boxp, frame.saved, ip, inst, ret)) { + VM_DISPATCH_NEXT(); + } + return ret; + } #if !defined(__GNUC__) default: diff --git a/src/interp/opcode.h b/src/interp/opcode.h index d3bb66b1..7fcd98ae 100644 --- a/src/interp/opcode.h +++ b/src/interp/opcode.h @@ -63,11 +63,16 @@ inline constexpr int kMaxFunctionRegisters = kMaxFunctionRegisterIndex + 1; X(COMBINE) /* R(A) = CombineMulti(prefix R(A)..R(A+B-1), last R(A+B)) */ \ X(THROW) /* throw string constant K(sbx) */ \ X(FORPREP) /* int: R(A+1)=count; float: keep limit; skip if empty (pc+=sbx); R(A+3)=R(A) */ \ - X(FORLOOP) /* int: if --count>=0: R(A)+=step, R(A+3)=R(A), pc+=sbx; float: add+compare */ + X(FORLOOP) /* int: if --count>=0: R(A)+=step, R(A+3)=R(A), pc+=sbx; float: add+compare */ \ + X(STRMETHOD) /* R(A) = method Kstr(Bx)/Kstr(Bx+1) on B args at R(A)..; C: 0=multi, 1=unbox, 2=tail */ // TAIL/TAILNAME 的 C 操作数:精确自尾调用(非变参、编译期已知实参个数、无末参展开)。 // 文件级函数不可再赋,因此解释器可跳过查表,原地复用当前 proto/cl。 constexpr uint8_t kTailSelfExact = 2; +// CALLNAME/TAILNAME 的 C 操作数位标记:目标是本编译单元私有的文件级 local function。 +constexpr uint8_t kCallLocalUnit = 4; +// STRMETHOD 的 C 操作数:尾调用形式。 +constexpr uint8_t kStrMethodTail = 2; enum class Op : uint8_t { #define FAKELUA_OP_ENUM(name) name, diff --git a/src/interp/vm_ops.h b/src/interp/vm_ops.h index 7dd15e42..06d03c6b 100644 --- a/src/interp/vm_ops.h +++ b/src/interp/vm_ops.h @@ -34,6 +34,7 @@ inline constexpr int kTable = static_cast(::fakelua::VarType::Table); inline constexpr int kMulti = static_cast(::fakelua::VarType::Multi); inline constexpr int kClosure = static_cast(::fakelua::VarType::Closure); inline constexpr int kConstFlag = 0x1; +inline constexpr int kConstBoxFlag = 0x2; // HasBoxes=false:寄存器就是 stk[r],无 boxes[] 检查、无 16 字节中转拷贝。 // HasBoxes=true:被捕获的局部在 heap box 上,读写走 box,并镜像回 stk。 @@ -53,8 +54,10 @@ FL_VM_INLINE void VmWrite(CVar *stk, CVar **box, int r, const CVar &v) { const size_t i = static_cast(r); stk[i] = v; if constexpr (HasBoxes) { - if (box[i]) { - *box[i] = v; + if (CVar *b = box[i]) { + const int keep = b->flag_ & kConstBoxFlag; + *b = v; + b->flag_ |= keep; } } } @@ -69,7 +72,7 @@ FL_VM_INLINE void VmWriteInt(CVar *stk, CVar **box, int r, int64_t n) { if constexpr (HasBoxes) { if (CVar *b = box[i]) { b->type_ = kInt; - b->flag_ = 0; + b->flag_ &= kConstBoxFlag; b->data_.i = n; } } diff --git a/src/jit/code_binding.h b/src/jit/code_binding.h index a3427705..3af64422 100644 --- a/src/jit/code_binding.h +++ b/src/jit/code_binding.h @@ -7,13 +7,13 @@ namespace fakelua { inline LuaLoc *BindGeneratedCode(void *symbol, State *s, JITType jit_type, const std::string &filename) { if (!symbol) ThrowFakeluaException("JIT image has no binding entry point"); using Intern = int64_t (*)(void *, const char *, size_t); - using Bind = void *(*) (void *, void *, void *, const char *, Intern, void *, const void *, void *, int *); + using Bind = void *(*) (void *, void *, void *, const char *, Intern, void *, const void *, void *, int *, const bool *); // Host-owned bytes survive unloading/recompilation of another image. auto *file = static_cast(s->GetHeap().GetAllocator(true).Alloc(filename.size() + 1)); std::memcpy(file, filename.c_str(), filename.size() + 1); return static_cast(reinterpret_cast(symbol)( s, &s->GetTempHeapSlot(), &s->GetConstHeapSlot(), file, +[](void *state, const char *data, size_t size) -> int64_t { return static_cast(state)->GetConstString().Alloc(std::string_view(data, size)); }, - &s->GetActiveLuaLoc(jit_type), s->GetVM().VersionPtr(), s->LuaFrames(), s->LuaDepthPtr())); + &s->GetActiveLuaLoc(jit_type), s->GetVM().VersionPtr(), s->LuaFrames(), s->LuaDepthPtr(), s->InterpConstAllocPtr())); } }// namespace fakelua diff --git a/src/jit/gcc_jit.cpp b/src/jit/gcc_jit.cpp index 0b22a45e..364a3090 100644 --- a/src/jit/gcc_jit.cpp +++ b/src/jit/gcc_jit.cpp @@ -286,7 +286,11 @@ void GccJitter::Compile(const ParseResult &pr, const GenResult &gr, const Compil close(log_fd); int status = 0; - if (waitpid(pid, &status, 0) < 0) { + pid_t waited = -1; + do { + waited = waitpid(pid, &status, 0); + } while (waited < 0 && errno == EINTR); + if (waited < 0) { pthread_sigmask(SIG_SETMASK, &old_mask, nullptr); CleanupOnError(); ThrowFakeluaException(std::format("GCC compile failed, waitpid failed for {}", pr.file_name)); @@ -471,14 +475,16 @@ void GccJitter::Compile(const ParseResult &pr, const GenResult &gr, const Compil // ---- Common post-load: register compiled functions + call init ---- LOG_DEBUG(s_, "engine", "GCC: registering {} functions from {}", gr.function_names.size(), so_file); + const uint64_t anon_seq = s_->NextAnonFnSeq(); for (const auto &[name, info]: gr.function_names) { const std::string &sym = info.c_symbol_name.empty() ? name : info.c_symbol_name; void *func_ptr = dlsym_lambda(sym); if (!func_ptr) { ThrowFakeluaException(std::format("GCC compile failed, symbol resolution failed for {} in {}", name, so_file)); } - s_->GetVM().RegisterFunction(VmFunction(name, info.params_count, JIT_GCC, func_ptr, handle, info.is_vararg)); - LOG_DEBUG(s_, "engine", "Registered gcc function {} with {} params (vararg: {}) at address {}", name, info.params_count, info.is_vararg, func_ptr); + const std::string vm_name = name.starts_with("__fl_func_") ? std::format("{}#{}", name, anon_seq) : name; + s_->GetVM().RegisterFunction(VmFunction(vm_name, info.params_count, JIT_GCC, func_ptr, handle, info.is_vararg)); + LOG_DEBUG(s_, "engine", "Registered gcc function {} with {} params (vararg: {}) at address {}", vm_name, info.params_count, info.is_vararg, func_ptr); } void *init_ptr = dlsym_lambda(kInitFunctionName); diff --git a/src/jit/tcc_handle.cpp b/src/jit/tcc_handle.cpp index 6383ab21..d31c0163 100644 --- a/src/jit/tcc_handle.cpp +++ b/src/jit/tcc_handle.cpp @@ -57,6 +57,7 @@ TCCHandle::TCCHandle(State *s, const CompileConfig &cfg) : s_(s) { tcc_add_symbol(tcc_state_, "FlEnsureNativeSpecSnapshot", reinterpret_cast(FlEnsureNativeSpecSnapshot)); tcc_add_symbol(tcc_state_, "FakeluaRegisterLuaLoc", reinterpret_cast(FakeluaRegisterLuaLoc)); tcc_add_symbol(tcc_state_, "FakeluaRegisterFnMap", reinterpret_cast(FakeluaRegisterFnMap)); + tcc_add_symbol(tcc_state_, "FakeluaPromoteConstBoxValue", reinterpret_cast(FakeluaPromoteConstBoxValue)); tcc_define_symbol(tcc_state_, "FAKELUA_JIT_TYPE", std::to_string(static_cast(JIT_TCC)).c_str()); } diff --git a/src/jit/tcc_jit.cpp b/src/jit/tcc_jit.cpp index a5dc61bd..6649e92b 100644 --- a/src/jit/tcc_jit.cpp +++ b/src/jit/tcc_jit.cpp @@ -27,6 +27,7 @@ void TccJitter::Compile(const ParseResult &pr, const GenResult &gr, const Compil handle->SetLuaLoc(BindGeneratedCode(tcc_get_symbol(s, "__fakelua_bind"), s_, JIT_TCC, pr.file_name)); LOG_DEBUG(s_, "engine", "TCC: registering {} functions", gr.function_names.size()); + const uint64_t anon_seq = s_->NextAnonFnSeq(); for (const auto &[name, info]: gr.function_names) { const std::string &sym = info.c_symbol_name.empty() ? name : info.c_symbol_name; void *func_ptr = tcc_get_symbol(s, sym.c_str()); @@ -37,8 +38,9 @@ void TccJitter::Compile(const ParseResult &pr, const GenResult &gr, const Compil // 这里把 handle (shared_ptr) 一并交给 VmFunction 持有,VmFunction 又 // 被存放到 State 的 Vm 中(见 src/jit/vm_function.h 的 handle_ 成员)。 // 因此只要 VmFunction 还活着,func_ptr 就保证可用;State 析构才会一并释放。 - s_->GetVM().RegisterFunction(VmFunction(name, info.params_count, JIT_TCC, func_ptr, handle, info.is_vararg)); - LOG_DEBUG(s_, "engine", "Registered function {} with {} params (vararg: {}) at address {}", name, info.params_count, info.is_vararg, func_ptr); + const std::string vm_name = name.starts_with("__fl_func_") ? std::format("{}#{}", name, anon_seq) : name; + s_->GetVM().RegisterFunction(VmFunction(vm_name, info.params_count, JIT_TCC, func_ptr, handle, info.is_vararg)); + LOG_DEBUG(s_, "engine", "Registered function {} with {} params (vararg: {}) at address {}", vm_name, info.params_count, info.is_vararg, func_ptr); } void *init_ptr = tcc_get_symbol(s, kInitFunctionName); diff --git a/src/jit/vm.cpp b/src/jit/vm.cpp index 993cf288..be5c7dc7 100644 --- a/src/jit/vm.cpp +++ b/src/jit/vm.cpp @@ -10,6 +10,43 @@ namespace fakelua { +void Vm::RegisterFunction(const VmFunction &func) { + const auto &name = func.GetName(); + if (const auto iter = vm_functions_.find(name); iter == vm_functions_.end()) { + vm_functions_.emplace(name, func); + } else { + if (owner_ && owner_->InActiveDispatch()) { + for (int i = 0; i < JIT_MAX; ++i) { + const auto jt = static_cast(i); + if (!func.GetAddr(jt)) { + continue; + } + if (auto old_handle = iter->second.GetHandle(jt); old_handle && old_handle != func.GetHandle(jt)) { + owner_->DeferJitHandleUnload(std::move(old_handle)); + } + } + } + iter->second.Merge(func); + } + version_ = NextVersion(); +} + +void Vm::RetainHandleForCodeAddr(const void *func_ptr) { + if (!owner_ || !func_ptr) { + return; + } + for (const auto &[name, fn]: vm_functions_) { + for (int i = 0; i < JIT_MAX; ++i) { + const auto jt = static_cast(i); + if (fn.GetAddr(jt) == func_ptr) { + if (auto h = fn.GetHandle(jt)) { + owner_->RetainJitHandle(std::move(h)); + } + } + } + } +} + [[noreturn]] void JumpToJitErrorBoundary(State *s, std::string msg, std::string loc, std::string stack, std::string lua_stack) { JitErrorBoundary *boundary = s->GetJitErrorBoundary(); boundary->msg = std::move(msg); diff --git a/src/jit/vm.h b/src/jit/vm.h index 7682399c..b11b7221 100644 --- a/src/jit/vm.h +++ b/src/jit/vm.h @@ -26,18 +26,13 @@ struct NativeFuncEntry { class Vm { public: - Vm() = default; + explicit Vm(State *owner = nullptr) : owner_(owner) {} // 注册 JIT 编译的 fakelua 函数(单线程调用,见类注释) - void RegisterFunction(const VmFunction &func) { - const auto &name = func.GetName(); - if (const auto iter = vm_functions_.find(name); iter == vm_functions_.end()) { - vm_functions_.emplace(name, func); - } else { - iter->second.Merge(func); - } - version_ = NextVersion(); - } + void RegisterFunction(const VmFunction &func); + + // 将包含指定函数代码地址的 JIT 产物句柄钉死在所属 State 上(冷路径:闭包跨帧提升时调用) + void RetainHandleForCodeAddr(const void *func_ptr); // 获取 JIT 函数(拷贝 VmFunction,含 name 与各后端 handle 的 shared_ptr) [[nodiscard]] VmFunction GetFunction(std::string_view name) const { @@ -118,6 +113,7 @@ class Vm { std::unordered_map vm_functions_; std::unordered_map native_functions_; + State *owner_ = nullptr; uint64_t global_name_ = 0; uint64_t version_ = NextVersion(); }; @@ -146,6 +142,10 @@ extern "C" int FakeluaJitContextPush(State *s, int jit); extern "C" void FakeluaJitContextPop(State *s, int prev); +extern "C" CVar FakeluaPromoteConstBoxValue(State *state, CVar val); + +CVar PromoteConstBoxValue(State *state, CVar val); + // 数组版 FakeluaCallByName,供解释器使用 CVar CallByNameArgs(State *state, int jit_type, std::string_view name, int arg_num, const CVar *args); diff --git a/src/jit/vm_function.h b/src/jit/vm_function.h index f2cccd83..fc7ab02a 100644 --- a/src/jit/vm_function.h +++ b/src/jit/vm_function.h @@ -34,12 +34,16 @@ class VmFunction { } [[nodiscard]] void *GetAddr(JITType type) const { - DEBUG_ASSERT(type >= 0 && type < JIT_MAX); + if (static_cast(type) >= static_cast(JIT_MAX)) { + return nullptr; + } return func_addr_[type]; } [[nodiscard]] JITHandlePtr GetHandle(JITType type) const { - DEBUG_ASSERT(type >= 0 && type < JIT_MAX); + if (static_cast(type) >= static_cast(JIT_MAX)) { + return {}; + } return handle_[type]; } diff --git a/src/native/basic/native_basic.cpp b/src/native/basic/native_basic.cpp index 2548cc65..4f1ca7a5 100644 --- a/src/native/basic/native_basic.cpp +++ b/src/native/basic/native_basic.cpp @@ -1,5 +1,6 @@ #include "native/basic/native_basic.h" #include "compile/c_runtime_header.h" +#include "jit/jit_error_boundary.h" #include "native/native_common.h" #include "native/object/native_object.h" #include "native/string/native_string.h" @@ -66,7 +67,7 @@ static bool CallClosure(State *state, VarClosure *cl, CVar *args, int n, CVar &r void *addr = cl->func_ptr; if (addr != nullptr) { result = inter::DispatchCallClosure(state, cl, args, n, state->CurrentJit()); - } else if (cl->code_str) { + } else if (IsSourceLoadClosure(cl)) { result = FlEvalLoadClosure(state, cl, n, args); } else { ThrowFakeluaException("closure has no code"); @@ -151,40 +152,42 @@ extern "C" CVar BasicPairsIterator(VarClosure *cl, CVar /*s*/, CVar /*var*/) { return CVar{static_cast(VarType::Nil)}; } - CVar tbl = st->table; - CVar last = st->last_key; + return GuardJitEntry(state, [&]() -> CVar { + CVar tbl = st->table; + CVar last = st->last_key; - if (tbl.type_ != static_cast(VarType::Table) || !tbl.data_.t) { - return inter::NativeToFakeluaNil(state); - } + if (tbl.type_ != static_cast(VarType::Table) || !tbl.data_.t) { + return inter::NativeToFakeluaNil(state); + } - // 遍历查找 last_key 的下一个(与 GET_TABLE_ENTRY 一致:spec + quick XOR buckets) - bool found_last = (last.type_ == static_cast(VarType::Nil));// nil 表示刚开始 - CVar next_key{static_cast(VarType::Nil)}; - CVar next_val{static_cast(VarType::Nil)}; - bool has_next = false; + // 遍历查找 last_key 的下一个(与 GET_TABLE_ENTRY 一致:spec + quick XOR buckets) + bool found_last = (last.type_ == static_cast(VarType::Nil));// nil 表示刚开始 + CVar next_key{static_cast(VarType::Nil)}; + CVar next_val{static_cast(VarType::Nil)}; + bool has_next = false; - TableHelper::ForEachKV(tbl, [&](CVar k, CVar v) { - if (has_next) return; - if (found_last) { - next_key = k; - next_val = v; - has_next = true; - return; - } - if (KeysEqual(k, last)) { - found_last = true; - } - }); + TableHelper::ForEachKV(tbl, [&](CVar k, CVar v) { + if (has_next) return; + if (found_last) { + next_key = k; + next_val = v; + has_next = true; + return; + } + if (KeysEqual(k, last)) { + found_last = true; + } + }); - if (!has_next) return inter::NativeToFakeluaNil(state); + if (!has_next) return inter::NativeToFakeluaNil(state); - st->last_key = next_key; + st->last_key = next_key; - CVar multi = inter::AllocMultiCVar(state, 2); - inter::SetMultiCVarElement(multi, 0, next_key); - inter::SetMultiCVarElement(multi, 1, next_val); - return multi; + CVar multi = inter::AllocMultiCVar(state, 2); + inter::SetMultiCVarElement(multi, 0, next_key); + inter::SetMultiCVarElement(multi, 1, next_val); + return multi; + }); } // ipairs 迭代器原生函数 @@ -198,24 +201,26 @@ extern "C" CVar BasicIpairsIterator(VarClosure *cl, CVar /*s*/, CVar /*var*/) { return CVar{static_cast(VarType::Nil)}; } - CVar tbl = st->table; - int64_t idx = st->next_idx; + return GuardJitEntry(state, [&]() -> CVar { + CVar tbl = st->table; + int64_t idx = st->next_idx; - if (tbl.type_ != static_cast(VarType::Table) || !tbl.data_.t) { - return inter::NativeToFakeluaNil(state); - } + if (tbl.type_ != static_cast(VarType::Table) || !tbl.data_.t) { + return inter::NativeToFakeluaNil(state); + } - CVar val = TableHelper::GetTableInt(state, tbl, idx); - if (val.type_ == static_cast(VarType::Nil)) { - return inter::NativeToFakeluaNil(state); - } + CVar val = TableHelper::GetTableInt(state, tbl, idx); + if (val.type_ == static_cast(VarType::Nil)) { + return inter::NativeToFakeluaNil(state); + } - st->next_idx = idx + 1; + st->next_idx = idx + 1; - CVar multi = inter::AllocMultiCVar(state, 2); - inter::SetMultiCVarElement(multi, 0, inter::NativeToFakeluaInt(state, idx)); - inter::SetMultiCVarElement(multi, 1, val); - return multi; + CVar multi = inter::AllocMultiCVar(state, 2); + inter::SetMultiCVarElement(multi, 0, inter::NativeToFakeluaInt(state, idx)); + inter::SetMultiCVarElement(multi, 1, val); + return multi; + }); } void RegisterBasicLibraryApi(State *s) { @@ -558,7 +563,7 @@ void RegisterBasicLibraryApi(State *s) { CVar err_result{static_cast(VarType::Nil)}; if (addr != nullptr) { err_result = inter::DispatchCallClosure(state, err_cl, &err_arg, 1, JIT_TCC); - } else if (err_cl->code_str) { + } else if (IsSourceLoadClosure(err_cl)) { err_result = FlEvalLoadClosure(state, err_cl, 1, &err_arg); } else { err_result = inter::NativeToFakeluaString(state, err_msg); diff --git a/src/native/compress/compress_lz4.cpp b/src/native/compress/compress_lz4.cpp index c1bb98f6..0525b0e7 100644 --- a/src/native/compress/compress_lz4.cpp +++ b/src/native/compress/compress_lz4.cpp @@ -2,15 +2,33 @@ #include "util/exception.h" #include +#include namespace fakelua::compress { +namespace { + +struct Lz4CCtxDeleter { + void operator()(LZ4F_compressionContext_t p) const noexcept { + LZ4F_freeCompressionContext(p); + } +}; + +struct Lz4DCtxDeleter { + void operator()(LZ4F_decompressionContext_t p) const noexcept { + LZ4F_freeDecompressionContext(p); + } +}; + +}// namespace + static constexpr uint64_t kMaxDecompressBytes = 64ull * 1024 * 1024; std::vector Lz4Compress(const uint8_t *data, size_t len) { - LZ4F_cctx *cctx = nullptr; - LZ4F_errorCode_t err = LZ4F_createCompressionContext(&cctx, LZ4F_VERSION); - if (LZ4F_isError(err) || !cctx) return {}; + LZ4F_cctx *raw_cctx = nullptr; + LZ4F_errorCode_t err = LZ4F_createCompressionContext(&raw_cctx, LZ4F_VERSION); + if (LZ4F_isError(err) || !raw_cctx) return {}; + std::unique_ptr cctx(raw_cctx); LZ4F_preferences_t prefs{}; prefs.frameInfo.contentSize = len; @@ -19,26 +37,22 @@ std::vector Lz4Compress(const uint8_t *data, size_t len) { size_t dst_capacity = LZ4F_compressBound(len, &prefs); std::vector out(dst_capacity); - size_t written = LZ4F_compressBegin(cctx, out.data(), out.size(), &prefs); + size_t written = LZ4F_compressBegin(cctx.get(), out.data(), out.size(), &prefs); if (LZ4F_isError(written)) { - LZ4F_freeCompressionContext(cctx); return {}; } - size_t compressed = LZ4F_compressUpdate(cctx, out.data() + written, out.size() - written, data, len, nullptr); + size_t compressed = LZ4F_compressUpdate(cctx.get(), out.data() + written, out.size() - written, data, len, nullptr); if (LZ4F_isError(compressed)) { - LZ4F_freeCompressionContext(cctx); return {}; } written += compressed; - size_t end_written = LZ4F_compressEnd(cctx, out.data() + written, out.size() - written, nullptr); + size_t end_written = LZ4F_compressEnd(cctx.get(), out.data() + written, out.size() - written, nullptr); if (LZ4F_isError(end_written)) { - LZ4F_freeCompressionContext(cctx); return {}; } - LZ4F_freeCompressionContext(cctx); out.resize(written + end_written); return out; } @@ -46,24 +60,23 @@ std::vector Lz4Compress(const uint8_t *data, size_t len) { std::vector Lz4Decompress(const uint8_t *data, size_t len) { if (len == 0) return {}; - LZ4F_dctx *dctx = nullptr; - LZ4F_errorCode_t err = LZ4F_createDecompressionContext(&dctx, LZ4F_VERSION); - if (LZ4F_isError(err) || !dctx) { + LZ4F_dctx *raw_dctx = nullptr; + LZ4F_errorCode_t err = LZ4F_createDecompressionContext(&raw_dctx, LZ4F_VERSION); + if (LZ4F_isError(err) || !raw_dctx) { ThrowFakeluaException("lz4_decompress: failed to create context"); } + std::unique_ptr dctx(raw_dctx); // First pass: get frame info to determine content size LZ4F_frameInfo_t frameInfo{}; size_t src_consumed = len;// INPUT: size of buffer; OUTPUT: bytes consumed - size_t fi_ret = LZ4F_getFrameInfo(dctx, &frameInfo, data, &src_consumed); + size_t fi_ret = LZ4F_getFrameInfo(dctx.get(), &frameInfo, data, &src_consumed); if (LZ4F_isError(fi_ret)) { - LZ4F_freeDecompressionContext(dctx); ThrowFakeluaException("lz4_decompress: invalid frame"); } uint64_t content_size = frameInfo.contentSize; if (content_size > kMaxDecompressBytes) { - LZ4F_freeDecompressionContext(dctx); ThrowFakeluaException("lz4_decompress: payload too large"); } if (content_size == 0) { @@ -83,7 +96,6 @@ std::vector Lz4Decompress(const uint8_t *data, size_t len) { size_t dst_capacity = out.size() - dst_pos; if (dst_capacity == 0) { if (out.size() >= kMaxDecompressBytes) { - LZ4F_freeDecompressionContext(dctx); ThrowFakeluaException("lz4_decompress: payload too large"); } uint64_t next = out.size() * 2; @@ -92,9 +104,8 @@ std::vector Lz4Decompress(const uint8_t *data, size_t len) { dst_capacity = out.size() - dst_pos; } - last_ret = LZ4F_decompress(dctx, out.data() + dst_pos, &dst_capacity, src, &src_size, nullptr); + last_ret = LZ4F_decompress(dctx.get(), out.data() + dst_pos, &dst_capacity, src, &src_size, nullptr); if (LZ4F_isError(last_ret)) { - LZ4F_freeDecompressionContext(dctx); ThrowFakeluaException("lz4_decompress: failed"); } @@ -104,7 +115,6 @@ std::vector Lz4Decompress(const uint8_t *data, size_t len) { if (last_ret == 0) { if (src_remaining > 0) { - LZ4F_freeDecompressionContext(dctx); ThrowFakeluaException("lz4_decompress: trailing garbage"); } break;// frame fully decoded @@ -112,11 +122,9 @@ std::vector Lz4Decompress(const uint8_t *data, size_t len) { } if (last_ret != 0) { - LZ4F_freeDecompressionContext(dctx); ThrowFakeluaException("lz4_decompress: truncated frame"); } - LZ4F_freeDecompressionContext(dctx); out.resize(dst_pos); return out; } diff --git a/src/native/compress/compress_zlib.cpp b/src/native/compress/compress_zlib.cpp index 39a25bf4..664d64f0 100644 --- a/src/native/compress/compress_zlib.cpp +++ b/src/native/compress/compress_zlib.cpp @@ -71,10 +71,15 @@ std::vector GzipCompress(const uint8_t *data, size_t len, int level) { // windowBits = 15 + 16 = 31 → gzip format int ret = deflateInit2(&zs, level, Z_DEFLATED, 15 + 16, 8, Z_DEFAULT_STRATEGY); if (ret != Z_OK) return {}; + struct DeflateGuard { + z_stream *s; + ~DeflateGuard() noexcept { + if (s) deflateEnd(s); + } + } guard{&zs}; uLongf dst_capacity = deflateBound(&zs, static_cast(len)); if (dst_capacity > std::numeric_limits::max()) { - deflateEnd(&zs); ThrowFakeluaException("gzip_compress: payload too large"); } std::vector out(dst_capacity); @@ -85,8 +90,6 @@ std::vector GzipCompress(const uint8_t *data, size_t len, int level) { zs.avail_out = static_cast(dst_capacity); ret = deflate(&zs, Z_FINISH); - deflateEnd(&zs); - if (ret != Z_STREAM_END) return {}; out.resize(zs.total_out); @@ -111,24 +114,25 @@ std::vector GzipDecompress(const uint8_t *data, size_t len) { if (ret != Z_OK) { ThrowFakeluaException("gzip_decompress: inflateInit2 failed"); } - - auto fail = [&](const char *msg) { - inflateEnd(&zs); - ThrowFakeluaException(msg); - }; + struct InflateGuard { + z_stream *s; + ~InflateGuard() noexcept { + if (s) inflateEnd(s); + } + } guard{&zs}; std::vector out; auto inflate_one_member = [&]() { for (;;) { if (out.size() >= kMaxDecompressBytes) { - fail("gzip_decompress: payload too large"); + ThrowFakeluaException("gzip_decompress: payload too large"); } size_t old_size = out.size(); size_t next = old_size < 4096 ? 4096 : old_size * 2; if (next > kMaxDecompressBytes || next < old_size) next = kMaxDecompressBytes; if (next <= old_size) { - fail("gzip_decompress: payload too large"); + ThrowFakeluaException("gzip_decompress: payload too large"); } out.resize(next); zs.next_out = out.data() + old_size; @@ -137,7 +141,7 @@ std::vector GzipDecompress(const uint8_t *data, size_t len) { out.resize(out.size() - zs.avail_out); if (ret == Z_STREAM_END) return; if (ret != Z_OK) { - fail("gzip_decompress: failed"); + ThrowFakeluaException("gzip_decompress: failed"); } } }; @@ -146,12 +150,11 @@ std::vector GzipDecompress(const uint8_t *data, size_t len) { while (zs.avail_in > 0) { ret = inflateReset2(&zs, 15 + 16); if (ret != Z_OK) { - fail("gzip_decompress: failed"); + ThrowFakeluaException("gzip_decompress: failed"); } inflate_one_member(); } - inflateEnd(&zs); return out; } diff --git a/src/native/crypto/crypto_aes.cpp b/src/native/crypto/crypto_aes.cpp index e4431985..44435e91 100644 --- a/src/native/crypto/crypto_aes.cpp +++ b/src/native/crypto/crypto_aes.cpp @@ -1,14 +1,28 @@ #include "native/crypto/crypto_aes.h" #include "util/exception.h" +#include #include +#include #include namespace fakelua::crypto { +namespace { + +struct EvpCipherCtxDeleter { + void operator()(EVP_CIPHER_CTX *p) const noexcept { + EVP_CIPHER_CTX_free(p); + } +}; + +using EvpCipherCtxPtr = std::unique_ptr; + +}// namespace + // Internal helper: select cipher by key size -static const EVP_CIPHER *SelectEcbCipher(AesKeySize key_size, EVP_CIPHER_CTX *ctx) { +static const EVP_CIPHER *SelectEcbCipher(AesKeySize key_size) { switch (key_size) { case AesKeySize::AES_128: return EVP_aes_128_ecb(); @@ -17,11 +31,10 @@ static const EVP_CIPHER *SelectEcbCipher(AesKeySize key_size, EVP_CIPHER_CTX *ct case AesKeySize::AES_256: return EVP_aes_256_ecb(); } - EVP_CIPHER_CTX_free(ctx); ThrowFakeluaException("aes: unsupported key size"); } -static const EVP_CIPHER *SelectCtrCipher(AesKeySize key_size, EVP_CIPHER_CTX *ctx) { +static const EVP_CIPHER *SelectCtrCipher(AesKeySize key_size) { switch (key_size) { case AesKeySize::AES_128: return EVP_aes_128_ctr(); @@ -30,11 +43,10 @@ static const EVP_CIPHER *SelectCtrCipher(AesKeySize key_size, EVP_CIPHER_CTX *ct case AesKeySize::AES_256: return EVP_aes_256_ctr(); } - EVP_CIPHER_CTX_free(ctx); ThrowFakeluaException("aes: unsupported key size"); } -static const EVP_CIPHER *SelectCbcCipher(AesKeySize key_size, EVP_CIPHER_CTX *ctx) { +static const EVP_CIPHER *SelectCbcCipher(AesKeySize key_size) { switch (key_size) { case AesKeySize::AES_128: return EVP_aes_128_cbc(); @@ -43,7 +55,6 @@ static const EVP_CIPHER *SelectCbcCipher(AesKeySize key_size, EVP_CIPHER_CTX *ct case AesKeySize::AES_256: return EVP_aes_256_cbc(); } - EVP_CIPHER_CTX_free(ctx); ThrowFakeluaException("aes: unsupported key size"); } @@ -52,97 +63,85 @@ static const EVP_CIPHER *SelectCbcCipher(AesKeySize key_size, EVP_CIPHER_CTX *ct // EVP_EncryptFinal_ex / EVP_DecryptFinal_ex write nothing beyond the block. void AesEncryptEcb(const uint8_t in[16], uint8_t out[16], const uint8_t *key, AesKeySize key_size) { - EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); + EvpCipherCtxPtr ctx(EVP_CIPHER_CTX_new()); if (!ctx) ThrowFakeluaException("aes_encrypt_ecb: failed to create EVP_CIPHER_CTX"); - const EVP_CIPHER *cipher = SelectEcbCipher(key_size, ctx); + const EVP_CIPHER *cipher = SelectEcbCipher(key_size); - if (EVP_EncryptInit_ex(ctx, cipher, nullptr, key, nullptr) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_EncryptInit_ex(ctx.get(), cipher, nullptr, key, nullptr) != 1) { ThrowFakeluaException("aes_encrypt_ecb: failed to initialize"); } // Disable padding: we handle one exact block; enabling padding would cause // EVP_EncryptFinal_ex to write a 17th byte past the 16-byte out[] buffer. - if (EVP_CIPHER_CTX_set_padding(ctx, 0) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_CIPHER_CTX_set_padding(ctx.get(), 0) != 1) { ThrowFakeluaException("aes_encrypt_ecb: failed to disable padding"); } int outlen = 0; - if (EVP_EncryptUpdate(ctx, out, &outlen, in, 16) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_EncryptUpdate(ctx.get(), out, &outlen, in, 16) != 1) { ThrowFakeluaException("aes_encrypt_ecb: EVP_EncryptUpdate failed"); } int final_len = 0; - if (EVP_EncryptFinal_ex(ctx, out + outlen, &final_len) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_EncryptFinal_ex(ctx.get(), out + outlen, &final_len) != 1) { ThrowFakeluaException("aes_encrypt_ecb: EVP_EncryptFinal_ex failed"); } - - EVP_CIPHER_CTX_free(ctx); } void AesDecryptEcb(const uint8_t in[16], uint8_t out[16], const uint8_t *key, AesKeySize key_size) { - EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); + EvpCipherCtxPtr ctx(EVP_CIPHER_CTX_new()); if (!ctx) ThrowFakeluaException("aes_decrypt_ecb: failed to create EVP_CIPHER_CTX"); - const EVP_CIPHER *cipher = SelectEcbCipher(key_size, ctx); + const EVP_CIPHER *cipher = SelectEcbCipher(key_size); - if (EVP_DecryptInit_ex(ctx, cipher, nullptr, key, nullptr) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_DecryptInit_ex(ctx.get(), cipher, nullptr, key, nullptr) != 1) { ThrowFakeluaException("aes_decrypt_ecb: failed to initialize"); } // Disable padding — same reasoning as encrypt path. - if (EVP_CIPHER_CTX_set_padding(ctx, 0) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_CIPHER_CTX_set_padding(ctx.get(), 0) != 1) { ThrowFakeluaException("aes_decrypt_ecb: failed to disable padding"); } int outlen = 0; - if (EVP_DecryptUpdate(ctx, out, &outlen, in, 16) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_DecryptUpdate(ctx.get(), out, &outlen, in, 16) != 1) { ThrowFakeluaException("aes_decrypt_ecb: EVP_DecryptUpdate failed"); } int final_len = 0; - if (EVP_DecryptFinal_ex(ctx, out + outlen, &final_len) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_DecryptFinal_ex(ctx.get(), out + outlen, &final_len) != 1) { ThrowFakeluaException("aes_decrypt_ecb: EVP_DecryptFinal_ex failed"); } - - EVP_CIPHER_CTX_free(ctx); } // CBC mode (cipher block chaining) — PKCS#7 padding, full buffer per call std::vector AesEncryptCbc(const uint8_t *data, size_t len, const uint8_t *key, AesKeySize key_size, const uint8_t iv[AES_BLOCK_SIZE]) { - EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); + if (len > static_cast(INT_MAX) - static_cast(EVP_MAX_BLOCK_LENGTH)) { + ThrowFakeluaException("aes_encrypt_cbc: data too long"); + } + + EvpCipherCtxPtr ctx(EVP_CIPHER_CTX_new()); if (!ctx) ThrowFakeluaException("aes_encrypt_cbc: failed to create EVP_CIPHER_CTX"); - const EVP_CIPHER *cipher = SelectCbcCipher(key_size, ctx); + const EVP_CIPHER *cipher = SelectCbcCipher(key_size); - if (EVP_EncryptInit_ex(ctx, cipher, nullptr, key, iv) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_EncryptInit_ex(ctx.get(), cipher, nullptr, key, iv) != 1) { ThrowFakeluaException("aes_encrypt_cbc: failed to initialize"); } // Padding is ON by default (PKCS#7); no need to call set_padding(ctx, 1). std::vector result(len + AES_BLOCK_SIZE); int outlen = 0; - if (EVP_EncryptUpdate(ctx, result.data(), &outlen, data, static_cast(len)) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_EncryptUpdate(ctx.get(), result.data(), &outlen, data ? data : result.data(), static_cast(len)) != 1) { ThrowFakeluaException("aes_encrypt_cbc: EVP_EncryptUpdate failed"); } int final_len = 0; - if (EVP_EncryptFinal_ex(ctx, result.data() + outlen, &final_len) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_EncryptFinal_ex(ctx.get(), result.data() + outlen, &final_len) != 1) { ThrowFakeluaException("aes_encrypt_cbc: EVP_EncryptFinal_ex failed"); } outlen += final_len; - result.resize(outlen); - EVP_CIPHER_CTX_free(ctx); + result.resize(static_cast(outlen)); return result; } @@ -150,33 +149,32 @@ std::vector AesDecryptCbc(const uint8_t *data, size_t len, const uint8_ if (len == 0 || len % AES_BLOCK_SIZE != 0) { ThrowFakeluaException("aes_decrypt_cbc: ciphertext length must be a multiple of 16"); } + if (len > static_cast(INT_MAX) - static_cast(EVP_MAX_BLOCK_LENGTH)) { + ThrowFakeluaException("aes_decrypt_cbc: data too long"); + } - EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); + EvpCipherCtxPtr ctx(EVP_CIPHER_CTX_new()); if (!ctx) ThrowFakeluaException("aes_decrypt_cbc: failed to create EVP_CIPHER_CTX"); - const EVP_CIPHER *cipher = SelectCbcCipher(key_size, ctx); + const EVP_CIPHER *cipher = SelectCbcCipher(key_size); - if (EVP_DecryptInit_ex(ctx, cipher, nullptr, key, iv) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_DecryptInit_ex(ctx.get(), cipher, nullptr, key, iv) != 1) { ThrowFakeluaException("aes_decrypt_cbc: failed to initialize"); } // Padding is ON by default (PKCS#7). std::vector result(len); int outlen = 0; - if (EVP_DecryptUpdate(ctx, result.data(), &outlen, data, static_cast(len)) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_DecryptUpdate(ctx.get(), result.data(), &outlen, data, static_cast(len)) != 1) { ThrowFakeluaException("aes_decrypt_cbc: EVP_DecryptUpdate failed"); } int final_len = 0; - if (EVP_DecryptFinal_ex(ctx, result.data() + outlen, &final_len) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_DecryptFinal_ex(ctx.get(), result.data() + outlen, &final_len) != 1) { ThrowFakeluaException("aes_decrypt_cbc: EVP_DecryptFinal_ex failed — bad padding or corrupt data"); } outlen += final_len; - result.resize(outlen); - EVP_CIPHER_CTX_free(ctx); + result.resize(static_cast(outlen)); return result; } @@ -184,27 +182,27 @@ std::vector AesDecryptCbc(const uint8_t *data, size_t len, const uint8_ // Matches crypto.encrypt("aes-*-ctr", ...). Output length equals input length. std::vector AesEncryptCtr(const uint8_t *data, size_t len, const uint8_t *key, AesKeySize key_size, const uint8_t iv[AES_BLOCK_SIZE]) { - EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); + if (len > static_cast(INT_MAX) - static_cast(EVP_MAX_BLOCK_LENGTH)) { + ThrowFakeluaException("aes_encrypt_ctr: data too long"); + } + + EvpCipherCtxPtr ctx(EVP_CIPHER_CTX_new()); if (!ctx) ThrowFakeluaException("aes_encrypt_ctr: failed to create EVP_CIPHER_CTX"); - const EVP_CIPHER *cipher = SelectCtrCipher(key_size, ctx); - if (EVP_EncryptInit_ex(ctx, cipher, nullptr, key, iv) != 1) { - EVP_CIPHER_CTX_free(ctx); + const EVP_CIPHER *cipher = SelectCtrCipher(key_size); + if (EVP_EncryptInit_ex(ctx.get(), cipher, nullptr, key, iv) != 1) { ThrowFakeluaException("aes_encrypt_ctr: failed to initialize"); } - EVP_CIPHER_CTX_set_padding(ctx, 0); + EVP_CIPHER_CTX_set_padding(ctx.get(), 0); std::vector result(len + AES_BLOCK_SIZE); int outlen = 0; - if (len > 0 && EVP_EncryptUpdate(ctx, result.data(), &outlen, data, static_cast(len)) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (len > 0 && EVP_EncryptUpdate(ctx.get(), result.data(), &outlen, data, static_cast(len)) != 1) { ThrowFakeluaException("aes_encrypt_ctr: EVP_EncryptUpdate failed"); } int final_len = 0; - if (EVP_EncryptFinal_ex(ctx, result.data() + outlen, &final_len) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_EncryptFinal_ex(ctx.get(), result.data() + outlen, &final_len) != 1) { ThrowFakeluaException("aes_encrypt_ctr: EVP_EncryptFinal_ex failed"); } result.resize(static_cast(outlen + final_len)); - EVP_CIPHER_CTX_free(ctx); return result; } diff --git a/src/native/crypto/crypto_cipher.cpp b/src/native/crypto/crypto_cipher.cpp index 1e648188..af6685d4 100644 --- a/src/native/crypto/crypto_cipher.cpp +++ b/src/native/crypto/crypto_cipher.cpp @@ -3,47 +3,56 @@ #include #include +#include #include namespace fakelua::crypto { +namespace { + +struct EvpCipherCtxDeleter { + void operator()(EVP_CIPHER_CTX *p) const noexcept { + EVP_CIPHER_CTX_free(p); + } +}; + +using EvpCipherCtxPtr = std::unique_ptr; + +constexpr size_t kMaxCipherDataLen = static_cast(INT_MAX) - static_cast(EVP_MAX_BLOCK_LENGTH); + +}// namespace + // RC4 stream cipher — EVP_rc4() (variable key length, no IV) std::vector Rc4(const uint8_t *key, size_t key_len, const uint8_t *data, size_t data_len) { if (key_len == 0) ThrowFakeluaException("rc4: empty key"); if (key_len > static_cast(INT_MAX)) ThrowFakeluaException("rc4: key too long"); if (data_len == 0) return {}; - if (data_len > static_cast(INT_MAX)) ThrowFakeluaException("rc4: data too long"); + if (data_len > kMaxCipherDataLen) ThrowFakeluaException("rc4: data too long"); - EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); + EvpCipherCtxPtr ctx(EVP_CIPHER_CTX_new()); if (!ctx) ThrowFakeluaException("rc4: failed to create EVP_CIPHER_CTX"); - if (EVP_EncryptInit_ex(ctx, EVP_rc4(), nullptr, nullptr, nullptr) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_EncryptInit_ex(ctx.get(), EVP_rc4(), nullptr, nullptr, nullptr) != 1) { ThrowFakeluaException("rc4: EVP_EncryptInit_ex (cipher) failed"); } - if (EVP_CIPHER_CTX_set_key_length(ctx, static_cast(key_len)) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_CIPHER_CTX_set_key_length(ctx.get(), static_cast(key_len)) != 1) { ThrowFakeluaException("rc4: EVP_CIPHER_CTX_set_key_length failed"); } - if (EVP_EncryptInit_ex(ctx, nullptr, nullptr, key, nullptr) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_EncryptInit_ex(ctx.get(), nullptr, nullptr, key, nullptr) != 1) { ThrowFakeluaException("rc4: EVP_EncryptInit_ex (key) failed"); } std::vector out(data_len); int outlen = 0; - if (EVP_EncryptUpdate(ctx, out.data(), &outlen, data, static_cast(data_len)) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_EncryptUpdate(ctx.get(), out.data(), &outlen, data, static_cast(data_len)) != 1) { ThrowFakeluaException("rc4: EVP_EncryptUpdate failed"); } int final_len = 0; - if (EVP_EncryptFinal_ex(ctx, out.data() + outlen, &final_len) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_EncryptFinal_ex(ctx.get(), out.data() + outlen, &final_len) != 1) { ThrowFakeluaException("rc4: EVP_EncryptFinal_ex failed"); } - EVP_CIPHER_CTX_free(ctx); return out; } @@ -55,44 +64,38 @@ std::vector BlowfishEncrypt(const uint8_t *key, size_t key_len, const u if (key_len > static_cast(INT_MAX)) ThrowFakeluaException("blowfish_encrypt: key too long"); if (data_len == 0) return {}; + if (data_len > kMaxCipherDataLen) ThrowFakeluaException("blowfish_encrypt: data too long"); size_t padded = (data_len + 7) & ~size_t(7); std::vector padded_data(data, data + data_len); padded_data.resize(padded, 0); - EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); + EvpCipherCtxPtr ctx(EVP_CIPHER_CTX_new()); if (!ctx) ThrowFakeluaException("blowfish_encrypt: failed to create EVP_CIPHER_CTX"); - if (EVP_EncryptInit_ex(ctx, EVP_bf_ecb(), nullptr, nullptr, nullptr) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_EncryptInit_ex(ctx.get(), EVP_bf_ecb(), nullptr, nullptr, nullptr) != 1) { ThrowFakeluaException("blowfish_encrypt: EVP_EncryptInit_ex (cipher) failed"); } - if (EVP_CIPHER_CTX_set_key_length(ctx, static_cast(key_len)) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_CIPHER_CTX_set_key_length(ctx.get(), static_cast(key_len)) != 1) { ThrowFakeluaException("blowfish_encrypt: EVP_CIPHER_CTX_set_key_length failed"); } - if (EVP_EncryptInit_ex(ctx, nullptr, nullptr, key, nullptr) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_EncryptInit_ex(ctx.get(), nullptr, nullptr, key, nullptr) != 1) { ThrowFakeluaException("blowfish_encrypt: EVP_EncryptInit_ex (key) failed"); } - if (EVP_CIPHER_CTX_set_padding(ctx, 0) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_CIPHER_CTX_set_padding(ctx.get(), 0) != 1) { ThrowFakeluaException("blowfish_encrypt: failed to disable padding"); } std::vector out(padded); int outlen = 0; - if (EVP_EncryptUpdate(ctx, out.data(), &outlen, padded_data.data(), static_cast(padded)) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_EncryptUpdate(ctx.get(), out.data(), &outlen, padded_data.data(), static_cast(padded)) != 1) { ThrowFakeluaException("blowfish_encrypt: EVP_EncryptUpdate failed"); } int final_len = 0; - if (EVP_EncryptFinal_ex(ctx, out.data() + outlen, &final_len) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_EncryptFinal_ex(ctx.get(), out.data() + outlen, &final_len) != 1) { ThrowFakeluaException("blowfish_encrypt: EVP_EncryptFinal_ex failed"); } - EVP_CIPHER_CTX_free(ctx); - out.resize(outlen + final_len); + out.resize(static_cast(outlen + final_len)); return out; } @@ -101,41 +104,35 @@ std::vector BlowfishDecrypt(const uint8_t *key, size_t key_len, const u if (key_len > static_cast(INT_MAX)) ThrowFakeluaException("blowfish_decrypt: key too long"); if (data_len == 0) return {}; if (data_len % 8 != 0) ThrowFakeluaException("blowfish_decrypt: length must be a multiple of 8"); + if (data_len > kMaxCipherDataLen) ThrowFakeluaException("blowfish_decrypt: data too long"); - EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); + EvpCipherCtxPtr ctx(EVP_CIPHER_CTX_new()); if (!ctx) ThrowFakeluaException("blowfish_decrypt: failed to create EVP_CIPHER_CTX"); - if (EVP_DecryptInit_ex(ctx, EVP_bf_ecb(), nullptr, nullptr, nullptr) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_DecryptInit_ex(ctx.get(), EVP_bf_ecb(), nullptr, nullptr, nullptr) != 1) { ThrowFakeluaException("blowfish_decrypt: EVP_DecryptInit_ex (cipher) failed"); } - if (EVP_CIPHER_CTX_set_key_length(ctx, static_cast(key_len)) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_CIPHER_CTX_set_key_length(ctx.get(), static_cast(key_len)) != 1) { ThrowFakeluaException("blowfish_decrypt: EVP_CIPHER_CTX_set_key_length failed"); } - if (EVP_DecryptInit_ex(ctx, nullptr, nullptr, key, nullptr) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_DecryptInit_ex(ctx.get(), nullptr, nullptr, key, nullptr) != 1) { ThrowFakeluaException("blowfish_decrypt: EVP_DecryptInit_ex (key) failed"); } - if (EVP_CIPHER_CTX_set_padding(ctx, 0) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_CIPHER_CTX_set_padding(ctx.get(), 0) != 1) { ThrowFakeluaException("blowfish_decrypt: failed to disable padding"); } std::vector out(data_len); int outlen = 0; - if (EVP_DecryptUpdate(ctx, out.data(), &outlen, data, static_cast(data_len)) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_DecryptUpdate(ctx.get(), out.data(), &outlen, data, static_cast(data_len)) != 1) { ThrowFakeluaException("blowfish_decrypt: EVP_DecryptUpdate failed"); } int final_len = 0; - if (EVP_DecryptFinal_ex(ctx, out.data() + outlen, &final_len) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_DecryptFinal_ex(ctx.get(), out.data() + outlen, &final_len) != 1) { ThrowFakeluaException("blowfish_decrypt: EVP_DecryptFinal_ex failed"); } - EVP_CIPHER_CTX_free(ctx); - out.resize(outlen + final_len); + out.resize(static_cast(outlen + final_len)); return out; } @@ -146,36 +143,32 @@ std::vector DesEncrypt(const uint8_t *key, size_t key_len, const uint8_ if (key_len < 8) ThrowFakeluaException("des_encrypt: key must be at least 8 bytes"); if (data_len == 0) return {}; + if (data_len > kMaxCipherDataLen) ThrowFakeluaException("des_encrypt: data too long"); size_t padded = (data_len + 7) & ~size_t(7); std::vector padded_data(data, data + data_len); padded_data.resize(padded, 0); - EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); + EvpCipherCtxPtr ctx(EVP_CIPHER_CTX_new()); if (!ctx) ThrowFakeluaException("des_encrypt: failed to create EVP_CIPHER_CTX"); - if (EVP_EncryptInit_ex(ctx, EVP_des_ecb(), nullptr, key, nullptr) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_EncryptInit_ex(ctx.get(), EVP_des_ecb(), nullptr, key, nullptr) != 1) { ThrowFakeluaException("des_encrypt: EVP_EncryptInit_ex failed"); } - if (EVP_CIPHER_CTX_set_padding(ctx, 0) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_CIPHER_CTX_set_padding(ctx.get(), 0) != 1) { ThrowFakeluaException("des_encrypt: failed to disable padding"); } std::vector out(padded); int outlen = 0; - if (EVP_EncryptUpdate(ctx, out.data(), &outlen, padded_data.data(), static_cast(padded)) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_EncryptUpdate(ctx.get(), out.data(), &outlen, padded_data.data(), static_cast(padded)) != 1) { ThrowFakeluaException("des_encrypt: EVP_EncryptUpdate failed"); } int final_len = 0; - if (EVP_EncryptFinal_ex(ctx, out.data() + outlen, &final_len) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_EncryptFinal_ex(ctx.get(), out.data() + outlen, &final_len) != 1) { ThrowFakeluaException("des_encrypt: EVP_EncryptFinal_ex failed"); } - EVP_CIPHER_CTX_free(ctx); - out.resize(outlen + final_len); + out.resize(static_cast(outlen + final_len)); return out; } @@ -183,33 +176,29 @@ std::vector DesDecrypt(const uint8_t *key, size_t key_len, const uint8_ if (key_len < 8) ThrowFakeluaException("des_decrypt: key must be at least 8 bytes"); if (data_len == 0) return {}; if (data_len % 8 != 0) ThrowFakeluaException("des_decrypt: length must be a multiple of 8"); + if (data_len > kMaxCipherDataLen) ThrowFakeluaException("des_decrypt: data too long"); - EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); + EvpCipherCtxPtr ctx(EVP_CIPHER_CTX_new()); if (!ctx) ThrowFakeluaException("des_decrypt: failed to create EVP_CIPHER_CTX"); - if (EVP_DecryptInit_ex(ctx, EVP_des_ecb(), nullptr, key, nullptr) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_DecryptInit_ex(ctx.get(), EVP_des_ecb(), nullptr, key, nullptr) != 1) { ThrowFakeluaException("des_decrypt: EVP_DecryptInit_ex failed"); } - if (EVP_CIPHER_CTX_set_padding(ctx, 0) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_CIPHER_CTX_set_padding(ctx.get(), 0) != 1) { ThrowFakeluaException("des_decrypt: failed to disable padding"); } std::vector out(data_len); int outlen = 0; - if (EVP_DecryptUpdate(ctx, out.data(), &outlen, data, static_cast(data_len)) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_DecryptUpdate(ctx.get(), out.data(), &outlen, data, static_cast(data_len)) != 1) { ThrowFakeluaException("des_decrypt: EVP_DecryptUpdate failed"); } int final_len = 0; - if (EVP_DecryptFinal_ex(ctx, out.data() + outlen, &final_len) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_DecryptFinal_ex(ctx.get(), out.data() + outlen, &final_len) != 1) { ThrowFakeluaException("des_decrypt: EVP_DecryptFinal_ex failed"); } - EVP_CIPHER_CTX_free(ctx); - out.resize(outlen + final_len); + out.resize(static_cast(outlen + final_len)); return out; } @@ -220,36 +209,32 @@ std::vector TripleDesEncrypt(const uint8_t *key, size_t key_len, const if (key_len < 24) ThrowFakeluaException("triple_des_encrypt: key must be at least 24 bytes"); if (data_len == 0) return {}; + if (data_len > kMaxCipherDataLen) ThrowFakeluaException("triple_des_encrypt: data too long"); size_t padded = (data_len + 7) & ~size_t(7); std::vector padded_data(data, data + data_len); padded_data.resize(padded, 0); - EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); + EvpCipherCtxPtr ctx(EVP_CIPHER_CTX_new()); if (!ctx) ThrowFakeluaException("triple_des_encrypt: failed to create EVP_CIPHER_CTX"); - if (EVP_EncryptInit_ex(ctx, EVP_des_ede3_ecb(), nullptr, key, nullptr) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_EncryptInit_ex(ctx.get(), EVP_des_ede3_ecb(), nullptr, key, nullptr) != 1) { ThrowFakeluaException("triple_des_encrypt: EVP_EncryptInit_ex failed"); } - if (EVP_CIPHER_CTX_set_padding(ctx, 0) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_CIPHER_CTX_set_padding(ctx.get(), 0) != 1) { ThrowFakeluaException("triple_des_encrypt: failed to disable padding"); } std::vector out(padded); int outlen = 0; - if (EVP_EncryptUpdate(ctx, out.data(), &outlen, padded_data.data(), static_cast(padded)) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_EncryptUpdate(ctx.get(), out.data(), &outlen, padded_data.data(), static_cast(padded)) != 1) { ThrowFakeluaException("triple_des_encrypt: EVP_EncryptUpdate failed"); } int final_len = 0; - if (EVP_EncryptFinal_ex(ctx, out.data() + outlen, &final_len) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_EncryptFinal_ex(ctx.get(), out.data() + outlen, &final_len) != 1) { ThrowFakeluaException("triple_des_encrypt: EVP_EncryptFinal_ex failed"); } - EVP_CIPHER_CTX_free(ctx); - out.resize(outlen + final_len); + out.resize(static_cast(outlen + final_len)); return out; } @@ -257,33 +242,29 @@ std::vector TripleDesDecrypt(const uint8_t *key, size_t key_len, const if (key_len < 24) ThrowFakeluaException("triple_des_decrypt: key must be at least 24 bytes"); if (data_len == 0) return {}; if (data_len % 8 != 0) ThrowFakeluaException("triple_des_decrypt: length must be a multiple of 8"); + if (data_len > kMaxCipherDataLen) ThrowFakeluaException("triple_des_decrypt: data too long"); - EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); + EvpCipherCtxPtr ctx(EVP_CIPHER_CTX_new()); if (!ctx) ThrowFakeluaException("triple_des_decrypt: failed to create EVP_CIPHER_CTX"); - if (EVP_DecryptInit_ex(ctx, EVP_des_ede3_ecb(), nullptr, key, nullptr) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_DecryptInit_ex(ctx.get(), EVP_des_ede3_ecb(), nullptr, key, nullptr) != 1) { ThrowFakeluaException("triple_des_decrypt: EVP_DecryptInit_ex failed"); } - if (EVP_CIPHER_CTX_set_padding(ctx, 0) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_CIPHER_CTX_set_padding(ctx.get(), 0) != 1) { ThrowFakeluaException("triple_des_decrypt: failed to disable padding"); } std::vector out(data_len); int outlen = 0; - if (EVP_DecryptUpdate(ctx, out.data(), &outlen, data, static_cast(data_len)) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_DecryptUpdate(ctx.get(), out.data(), &outlen, data, static_cast(data_len)) != 1) { ThrowFakeluaException("triple_des_decrypt: EVP_DecryptUpdate failed"); } int final_len = 0; - if (EVP_DecryptFinal_ex(ctx, out.data() + outlen, &final_len) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_DecryptFinal_ex(ctx.get(), out.data() + outlen, &final_len) != 1) { ThrowFakeluaException("triple_des_decrypt: EVP_DecryptFinal_ex failed"); } - EVP_CIPHER_CTX_free(ctx); - out.resize(outlen + final_len); + out.resize(static_cast(outlen + final_len)); return out; } diff --git a/src/native/crypto/native_crypto.cpp b/src/native/crypto/native_crypto.cpp index 1ce2de19..8670c55c 100644 --- a/src/native/crypto/native_crypto.cpp +++ b/src/native/crypto/native_crypto.cpp @@ -9,9 +9,11 @@ #include #include #include +#include #include #include #include +#include #include #include #include @@ -72,6 +74,9 @@ static CVar CryptoAesEncryptEcb(State *s, CVar *args, int n) { uint8_t key[16]; ReadKeyArg(s, key_arg, key, "key"); + if (data.size() > static_cast(INT_MAX) - static_cast(EVP_MAX_BLOCK_LENGTH)) { + ThrowFakeluaException("crypto.aes_encrypt_ecb: data too long"); + } if (data.size() % 16 != 0) { LOG_ERROR(s, "crypto", "aes_encrypt_ecb: data length {} not multiple of 16", data.size()); ThrowFakeluaException("crypto.aes_encrypt_ecb: data length must be a multiple of 16"); @@ -93,6 +98,9 @@ static CVar CryptoAesDecryptEcb(State *s, CVar *args, int n) { uint8_t key[16]; ReadKeyArg(s, key_arg, key, "key"); + if (data.size() > static_cast(INT_MAX) - static_cast(EVP_MAX_BLOCK_LENGTH)) { + ThrowFakeluaException("crypto.aes_decrypt_ecb: data too long"); + } if (data.size() % 16 != 0) { LOG_ERROR(s, "crypto", "aes_decrypt_ecb: data length {} not multiple of 16", data.size()); ThrowFakeluaException("crypto.aes_decrypt_ecb: data length must be a multiple of 16"); @@ -338,8 +346,33 @@ static CVar CryptoTripleDesDecrypt(State *s, CVar *args, int n) { // only non-AEAD ciphers are reliably supported. // ============================================================================= +struct EvpCipherCtxDeleter { + void operator()(EVP_CIPHER_CTX *p) const noexcept { + EVP_CIPHER_CTX_free(p); + } +}; + +using EvpCipherCtxPtr = std::unique_ptr; + +struct EvpMdCtxDeleter { + void operator()(EVP_MD_CTX *p) const noexcept { + EVP_MD_CTX_free(p); + } +}; + +using EvpMdCtxPtr = std::unique_ptr; + // Internal: run an EVP cipher operation (encrypt or decrypt) static std::vector EvpCipherOp(const std::string &algo, const std::string &key, const std::string &iv, const uint8_t *data, size_t data_len, bool encrypt, bool no_padding) { + if (data_len > static_cast(INT_MAX) - static_cast(EVP_MAX_BLOCK_LENGTH)) { + ThrowFakeluaException(std::format("crypto.{}: data too long", encrypt ? "encrypt" : "decrypt")); + } + if (key.size() > static_cast(INT_MAX)) { + ThrowFakeluaException(std::format("crypto.{}: key too long", encrypt ? "encrypt" : "decrypt")); + } + if (iv.size() > static_cast(INT_MAX)) { + ThrowFakeluaException(std::format("crypto.{}: IV too long", encrypt ? "encrypt" : "decrypt")); + } const EVP_CIPHER *cipher = EVP_get_cipherbyname(algo.c_str()); if (!cipher) { @@ -348,34 +381,31 @@ static std::vector EvpCipherOp(const std::string &algo, const std::stri encrypt ? "encrypt" : "decrypt", algo)); } - EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); + EvpCipherCtxPtr ctx(EVP_CIPHER_CTX_new()); if (!ctx) { ThrowFakeluaException(std::format("crypto.{}: failed to create EVP_CIPHER_CTX", encrypt ? "encrypt" : "decrypt")); } // Phase 1: init with cipher only (no key/iv yet) so we can adjust key length auto init_fn = encrypt ? EVP_EncryptInit_ex : EVP_DecryptInit_ex; - if (init_fn(ctx, cipher, nullptr, nullptr, nullptr) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (init_fn(ctx.get(), cipher, nullptr, nullptr, nullptr) != 1) { ThrowFakeluaException(std::format("crypto.{}: EVP init failed for cipher '{}'", encrypt ? "encrypt" : "decrypt", algo)); } // For variable-key-length ciphers (RC4, Blowfish, ChaCha20, ...), // set the actual key length before providing the key bytes. - int expected_key_len = EVP_CIPHER_CTX_key_length(ctx); + int expected_key_len = EVP_CIPHER_CTX_key_length(ctx.get()); if (static_cast(key.size()) != expected_key_len) { - if (EVP_CIPHER_CTX_set_key_length(ctx, static_cast(key.size())) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_CIPHER_CTX_set_key_length(ctx.get(), static_cast(key.size())) != 1) { ThrowFakeluaException(std::format("crypto.{}: key length {} is not valid for cipher '{}' (expected {} bytes)", encrypt ? "encrypt" : "decrypt", key.size(), algo, expected_key_len)); } } // Validate IV length - int cipher_iv_len = EVP_CIPHER_CTX_iv_length(ctx); + int cipher_iv_len = EVP_CIPHER_CTX_iv_length(ctx.get()); const uint8_t *iv_ptr = nullptr; if (cipher_iv_len > 0) { if (static_cast(iv.size()) != cipher_iv_len) { - EVP_CIPHER_CTX_free(ctx); ThrowFakeluaException(std::format("crypto.{}: IV length {} is not valid for cipher '{}' (expected {} bytes)", encrypt ? "encrypt" : "decrypt", iv.size(), algo, cipher_iv_len)); } iv_ptr = reinterpret_cast(iv.data()); @@ -385,42 +415,37 @@ static std::vector EvpCipherOp(const std::string &algo, const std::stri } // Phase 2: provide key and IV - if (init_fn(ctx, nullptr, nullptr, reinterpret_cast(key.data()), iv_ptr) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (init_fn(ctx.get(), nullptr, nullptr, reinterpret_cast(key.data()), iv_ptr) != 1) { ThrowFakeluaException(std::format("crypto.{}: failed to set key/IV for cipher '{}'", encrypt ? "encrypt" : "decrypt", algo)); } // Configure padding - if (EVP_CIPHER_CTX_set_padding(ctx, no_padding ? 0 : 1) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (EVP_CIPHER_CTX_set_padding(ctx.get(), no_padding ? 0 : 1) != 1) { ThrowFakeluaException(std::format("crypto.{}: EVP_CIPHER_CTX_set_padding failed", encrypt ? "encrypt" : "decrypt")); } // Allocate output: max size = data_len + one full block for padding - int block_size = EVP_CIPHER_CTX_block_size(ctx); + int block_size = EVP_CIPHER_CTX_block_size(ctx.get()); if (block_size < 1) block_size = 1; std::vector out(data_len + static_cast(block_size)); int outlen = 0; if (data_len > 0) { auto update_fn = encrypt ? EVP_EncryptUpdate : EVP_DecryptUpdate; - if (update_fn(ctx, out.data(), &outlen, data, static_cast(data_len)) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (update_fn(ctx.get(), out.data(), &outlen, data, static_cast(data_len)) != 1) { ThrowFakeluaException(std::format("crypto.{}: EVP_Update failed for cipher '{}'", encrypt ? "encrypt" : "decrypt", algo)); } } int final_len = 0; auto final_fn = encrypt ? EVP_EncryptFinal_ex : EVP_DecryptFinal_ex; - if (final_fn(ctx, out.data() + outlen, &final_len) != 1) { - EVP_CIPHER_CTX_free(ctx); + if (final_fn(ctx.get(), out.data() + outlen, &final_len) != 1) { ThrowFakeluaException(std::format("crypto.{}: EVP_Final failed for cipher '{}' — " "check key/IV length, padding setting, or data integrity", encrypt ? "encrypt" : "decrypt", algo)); } out.resize(static_cast(outlen) + static_cast(final_len)); - EVP_CIPHER_CTX_free(ctx); return out; } @@ -437,25 +462,21 @@ static CVar CryptoDigest(State *s, CVar *args, int n) { algo)); } - EVP_MD_CTX *ctx = EVP_MD_CTX_new(); + EvpMdCtxPtr ctx(EVP_MD_CTX_new()); if (!ctx) ThrowFakeluaException("crypto.digest: failed to create EVP_MD_CTX"); - if (EVP_DigestInit_ex(ctx, md, nullptr) != 1) { - EVP_MD_CTX_free(ctx); + if (EVP_DigestInit_ex(ctx.get(), md, nullptr) != 1) { ThrowFakeluaException(std::format("crypto.digest: EVP_DigestInit_ex failed for '{}'", algo)); } - if (!data.empty() && EVP_DigestUpdate(ctx, data.data(), data.size()) != 1) { - EVP_MD_CTX_free(ctx); + if (!data.empty() && EVP_DigestUpdate(ctx.get(), data.data(), data.size()) != 1) { ThrowFakeluaException(std::format("crypto.digest: EVP_DigestUpdate failed for '{}'", algo)); } uint8_t digest_buf[EVP_MAX_MD_SIZE]; unsigned int digest_len = 0; - if (EVP_DigestFinal_ex(ctx, digest_buf, &digest_len) != 1) { - EVP_MD_CTX_free(ctx); + if (EVP_DigestFinal_ex(ctx.get(), digest_buf, &digest_len) != 1) { ThrowFakeluaException(std::format("crypto.digest: EVP_DigestFinal_ex failed for '{}'", algo)); } - EVP_MD_CTX_free(ctx); return inter::NativeToFakeluaString(s, ToHex(digest_buf, digest_len)); } @@ -472,25 +493,21 @@ static CVar CryptoDigestRaw(State *s, CVar *args, int n) { ThrowFakeluaException(std::format("crypto.digest_raw: unknown digest algorithm '{}'", algo)); } - EVP_MD_CTX *ctx = EVP_MD_CTX_new(); + EvpMdCtxPtr ctx(EVP_MD_CTX_new()); if (!ctx) ThrowFakeluaException("crypto.digest_raw: failed to create EVP_MD_CTX"); - if (EVP_DigestInit_ex(ctx, md, nullptr) != 1) { - EVP_MD_CTX_free(ctx); + if (EVP_DigestInit_ex(ctx.get(), md, nullptr) != 1) { ThrowFakeluaException(std::format("crypto.digest_raw: EVP_DigestInit_ex failed for '{}'", algo)); } - if (!data.empty() && EVP_DigestUpdate(ctx, data.data(), data.size()) != 1) { - EVP_MD_CTX_free(ctx); + if (!data.empty() && EVP_DigestUpdate(ctx.get(), data.data(), data.size()) != 1) { ThrowFakeluaException(std::format("crypto.digest_raw: EVP_DigestUpdate failed for '{}'", algo)); } uint8_t digest_buf[EVP_MAX_MD_SIZE]; unsigned int digest_len = 0; - if (EVP_DigestFinal_ex(ctx, digest_buf, &digest_len) != 1) { - EVP_MD_CTX_free(ctx); + if (EVP_DigestFinal_ex(ctx.get(), digest_buf, &digest_len) != 1) { ThrowFakeluaException(std::format("crypto.digest_raw: EVP_DigestFinal_ex failed for '{}'", algo)); } - EVP_MD_CTX_free(ctx); return inter::NativeToFakeluaString(s, std::string(reinterpret_cast(digest_buf), digest_len)); } diff --git a/src/native/event/native_event.cpp b/src/native/event/native_event.cpp index 39308c5b..c833d083 100644 --- a/src/native/event/native_event.cpp +++ b/src/native/event/native_event.cpp @@ -12,11 +12,18 @@ namespace fakelua::event { // 每个 State 一份事件状态(避免跨 VM 串数据) +struct ListenerEntry { + uint64_t id = 0; + std::string func_name; + JITType cb_jit = JIT_TCC; +}; + struct EventState { - // event_name → 有序回调函数名列表 - std::unordered_map> listeners; - // event_name → 一次性回调函数名列表(触发后自动移除) - std::unordered_map> once_listeners; + uint64_t next_id = 0; + // event_name → 有序回调列表 + std::unordered_map> listeners; + // event_name → 一次性回调列表(触发后自动移除) + std::unordered_map> once_listeners; }; // 每个 State 一份,随 State 销毁。放在 State 上而不是这里的 static map:后者是全进程 @@ -41,23 +48,9 @@ static std::string CVarToString(CVar v) { // C++ → Lua 回调派发(与 timer/net 同款机制) -static void DispatchEvent(State *state, const std::string &func_name, CVar *args, int arg_count) { - if (func_name.empty()) return; - - auto func = state->GetVM().GetFunction(func_name); - if (func.Empty()) return; - - void *addr = func.GetAddr(JIT_TCC); - JITType jit_type = JIT_TCC; - if (!addr) { - addr = func.GetAddr(JIT_GCC); - jit_type = JIT_GCC; - } - - if (addr) { - inter::DispatchCall(state, addr, args, arg_count, jit_type); - } - // 不存在的函数静默跳过(可能已被卸载) +static void DispatchEvent(State *state, const ListenerEntry &entry, const CVar *args, int arg_count) { + if (!state || entry.func_name.empty()) return; + DispatchNamedLuaCallback(state, entry.func_name, args, arg_count, entry.cb_jit); } // 原生函数实现 @@ -78,8 +71,9 @@ static CVar EventOn(State *s, CVar *args, int n) { ThrowBadArgument(2, "event.on", "func_name must be a non-empty string"); } - GetEventState(s).listeners[event_name].push_back(std::move(func_name)); LOG_DEBUG(s, "event", "event.on: event={} func={}", event_name, func_name); + auto &es = GetEventState(s); + es.listeners[event_name].push_back(ListenerEntry{++es.next_id, std::move(func_name), s->CurrentJit()}); return inter::NativeToFakeluaNil(s); } @@ -99,7 +93,8 @@ static CVar EventOnce(State *s, CVar *args, int n) { ThrowBadArgument(2, "event.once", "func_name must be a non-empty string"); } - GetEventState(s).once_listeners[event_name].push_back(std::move(func_name)); + auto &es = GetEventState(s); + es.once_listeners[event_name].push_back(ListenerEntry{++es.next_id, std::move(func_name), s->CurrentJit()}); return inter::NativeToFakeluaNil(s); } @@ -113,34 +108,35 @@ static CVar EventOff(State *s, CVar *args, int n) { CVar a1 = inter::GetNativeArg(s, args, n, 1); std::string func_name = CVarToString(a1); + auto &es = GetEventState(s); // 从 listeners 中移除 - auto it = GetEventState(s).listeners.find(event_name); - if (it != GetEventState(s).listeners.end()) { + auto it = es.listeners.find(event_name); + if (it != es.listeners.end()) { auto &vec = it->second; for (auto vit = vec.begin(); vit != vec.end(); ++vit) { - if (*vit == func_name) { + if (vit->func_name == func_name) { vec.erase(vit); break; } } if (vec.empty()) { - GetEventState(s).listeners.erase(it); + es.listeners.erase(it); } } LOG_DEBUG(s, "event", "event.off: event={} func={}", event_name, func_name); // 从 once_listeners 中移除 - auto it2 = GetEventState(s).once_listeners.find(event_name); - if (it2 != GetEventState(s).once_listeners.end()) { + auto it2 = es.once_listeners.find(event_name); + if (it2 != es.once_listeners.end()) { auto &vec = it2->second; for (auto vit = vec.begin(); vit != vec.end(); ++vit) { - if (*vit == func_name) { + if (vit->func_name == func_name) { vec.erase(vit); break; } } if (vec.empty()) { - GetEventState(s).once_listeners.erase(it2); + es.once_listeners.erase(it2); } } @@ -164,23 +160,43 @@ static CVar EventEmit(State *s, CVar *args, int n) { event_args[event_arg_count++] = inter::GetNativeArg(s, args, n, i); } - // 快照 listeners(防止回调中修改列表导致迭代器失效) - auto it = GetEventState(s).listeners.find(event_name); - if (it != GetEventState(s).listeners.end()) { - std::vector snapshot = it->second; - LOG_DEBUG(s, "event", "event.emit: event={} listeners={} args={}", event_name, snapshot.size(), event_arg_count); - for (const auto &func_name: snapshot) { - DispatchEvent(s, func_name, event_args, event_arg_count); + // 在派发任何回调前同时快照 listeners 和 once_listeners,防止回调内注册的 + // event.once 在同一次 emit 中立即触发,也防止提前整表擦除导致异常中断时丢监听器。 + auto &es = GetEventState(s); + std::vector listeners_snapshot; + if (auto it = es.listeners.find(event_name); it != es.listeners.end()) { + listeners_snapshot = it->second; + } + std::vector once_snapshot; + if (auto it2 = es.once_listeners.find(event_name); it2 != es.once_listeners.end()) { + once_snapshot = it2->second; + } + + if (!listeners_snapshot.empty()) { + LOG_DEBUG(s, "event", "event.emit: event={} listeners={} args={}", event_name, listeners_snapshot.size(), event_arg_count); + for (const auto &entry: listeners_snapshot) { + DispatchEvent(s, entry, event_args, event_arg_count); } } - // 一次性回调:触发后清除 - auto it2 = GetEventState(s).once_listeners.find(event_name); - if (it2 != GetEventState(s).once_listeners.end()) { - std::vector snapshot = it2->second; - GetEventState(s).once_listeners.erase(it2); - for (const auto &func_name: snapshot) { - DispatchEvent(s, func_name, event_args, event_arg_count); + for (const auto &entry: once_snapshot) { + auto &cur_es = GetEventState(s); + auto it2 = cur_es.once_listeners.find(event_name); + if (it2 == cur_es.once_listeners.end()) continue; + auto &vec = it2->second; + bool still_present = false; + for (auto vit = vec.begin(); vit != vec.end(); ++vit) { + if (vit->id == entry.id) { + vec.erase(vit); + still_present = true; + break; + } + } + if (vec.empty()) { + cur_es.once_listeners.erase(it2); + } + if (still_present) { + DispatchEvent(s, entry, event_args, event_arg_count); } } diff --git a/src/native/http/native_http.cpp b/src/native/http/native_http.cpp index 5c146cd8..920480f8 100644 --- a/src/native/http/native_http.cpp +++ b/src/native/http/native_http.cpp @@ -23,6 +23,7 @@ #include #include #include +#include #include #include #include @@ -55,19 +56,10 @@ static bool CVarToBoolFlag(CVar v, bool default_val) { return true; } -static CVar CallNamed(State *s, const std::string &name, CVar *args, int n) { +static CVar CallNamed(State *s, const std::string &name, CVar *args, int n, JITType preferred_jit) { if (!s || name.empty()) return inter::NativeToFakeluaNil(s); - auto func = s->GetVM().GetFunction(name); - if (func.Empty()) return inter::NativeToFakeluaNil(s); - void *addr = func.GetAddr(JIT_TCC); - JITType jit_type = JIT_TCC; - if (!addr) { - addr = func.GetAddr(JIT_GCC); - jit_type = JIT_GCC; - } - if (!addr) return inter::NativeToFakeluaNil(s); native::IoContext::DispatchScope scope(s->GetIoContext()); - return inter::DispatchCall(s, addr, args, n, jit_type); + return DispatchNamedLuaCallback(s, name, args, n, preferred_jit); } static CVar HeadersToTable(State *s, const HeaderList &fields) { @@ -356,6 +348,14 @@ struct HttpResponseData { std::string err; }; +class HttpClientOp; + +struct ClientHold { + std::shared_ptr ptr; +}; + +static void ReleaseClientOp(NativeObject *nat); + class HttpClientOp : public std::enable_shared_from_this { public: HttpClientOp(State *state, NativeObject *nat) : io_(state->GetIoContext()), lua_state_(state), native_obj_(nat) { @@ -382,7 +382,8 @@ class HttpClientOp : public std::enable_shared_from_this { return; } use_tls_ = https; - host_ = std::string(u.host()); + std::string raw_host = std::string(u.host()); + host_ = tls::HostnameWithoutPort(raw_host); if (host_.empty()) { Finish("url missing host"); return; @@ -397,7 +398,7 @@ class HttpClientOp : public std::enable_shared_from_this { target.push_back('?'); target += std::string(u.encoded_query()); } - HeaderSet(headers, "Host", u.has_port() ? (host_ + ":" + std::to_string(port)) : host_); + HeaderSet(headers, "Host", u.has_port() ? (raw_host + ":" + std::to_string(port)) : raw_host); HeaderSet(headers, "User-Agent", "fakelua"); HeaderSet(headers, "Connection", "close"); req_wire_ = FormatRequest(method, target, version, std::move(headers), body); @@ -424,9 +425,16 @@ class HttpClientOp : public std::enable_shared_from_this { } void Tick() { + auto self_guard = shared_from_this(); io_.Poll(); if (!pending_) return; pending_ = false; + struct CleanupGuard { + HttpClientOp *self; + ~CleanupGuard() { + ReleaseClientOp(self->native_obj_); + } + } cleanup{this}; Dispatch(); } @@ -436,12 +444,17 @@ class HttpClientOp : public std::enable_shared_from_this { if (!done_) Finish("closed"); } + void ClearNativeObject() { + native_obj_ = nullptr; + } + bool Done() const { return done_ && !pending_; } - void SetCallback(std::string name) { + void SetCallback(std::string name, JITType jit) { cb_ = std::move(name); + cb_jit_ = jit; } private: @@ -449,7 +462,10 @@ class HttpClientOp : public std::enable_shared_from_this { if (ssl_ctx_) { SSL *ssl = SSL_new(ssl_ctx_); if (!ssl) return nullptr; - tls::SetSniHostname(ssl, host_); + if (!tls::ConfigurePeerVerification(ssl, host_, tls_verify_)) { + SSL_free(ssl); + return nullptr; + } auto *bev = bufferevent_openssl_socket_new(io_.Get(), -1, ssl, BUFFEREVENT_SSL_CONNECTING, BEV_OPT_CLOSE_ON_FREE); if (!bev) { SSL_free(ssl); @@ -471,7 +487,15 @@ class HttpClientOp : public std::enable_shared_from_this { void ArmTimeout() { ClearTimeout(); if (timeout_ms_ <= 0) return; - timeout_ev_ = evtimer_new(io_.Get(), [](evutil_socket_t, short, void *p) { static_cast(p)->Finish("timeout"); }, this); + timeout_ev_ = evtimer_new( + io_.Get(), + [](evutil_socket_t, short, void *p) { + auto *self = static_cast(p); + if (!self) return; + auto self_guard = self->shared_from_this(); + self->Finish("timeout"); + }, + this); timeval tv{}; tv.tv_sec = timeout_ms_ / 1000; tv.tv_usec = (timeout_ms_ % 1000) * 1000; @@ -498,9 +522,13 @@ class HttpClientOp : public std::enable_shared_from_this { } void OnConnected() { - if (bev_ && !req_wire_.empty()) { - bufferevent_write(bev_, req_wire_.data(), req_wire_.size()); - req_wire_.clear(); + if (bev_) { + evutil_socket_t fd = bufferevent_getfd(bev_); + if (fd != -1) evutil_make_socket_closeonexec(fd); + if (!req_wire_.empty()) { + bufferevent_write(bev_, req_wire_.data(), req_wire_.size()); + req_wire_.clear(); + } } } @@ -524,17 +552,20 @@ class HttpClientOp : public std::enable_shared_from_this { args[1] = inter::NativeToFakeluaNil(lua_state_); args[2] = ResponseToTable(lua_state_, resp_.status, resp_.reason, resp_.headers, resp_.body); } - CallNamed(lua_state_, cb_, args, 3); + CallNamed(lua_state_, cb_, args, 3, cb_jit_); } static void ReadCb(bufferevent *, void *ctx) { auto *self = static_cast(ctx); - if (self) self->HandleRead(false); + if (!self) return; + auto self_guard = self->shared_from_this(); + self->HandleRead(false); } static void EventCb(bufferevent *, short what, void *ctx) { auto *self = static_cast(ctx); if (!self) return; + auto self_guard = self->shared_from_this(); if (what & BEV_EVENT_CONNECTED) { self->OnConnected(); return; @@ -592,6 +623,7 @@ class HttpClientOp : public std::enable_shared_from_this { HttpResponseData resp_; std::string host_; std::string cb_; + JITType cb_jit_ = JIT_TCC; std::string tls_ca_; State *lua_state_ = nullptr; NativeObject *native_obj_ = nullptr; @@ -656,7 +688,9 @@ class HttpServerConn : public std::enable_shared_from_this { bufferevent_free(bev_); bev_ = nullptr; } - if (on_close_) on_close_(conn_id_); + auto on_close = std::move(on_close_); + on_request_ = nullptr; + if (on_close) on_close(conn_id_); } int ConnId() const { @@ -667,7 +701,15 @@ class HttpServerConn : public std::enable_shared_from_this { void ArmTimeout() { ClearTimeout(); if (timeout_ms_ <= 0) return; - timeout_ev_ = evtimer_new(io_.Get(), [](evutil_socket_t, short, void *p) { static_cast(p)->Close(); }, this); + timeout_ev_ = evtimer_new( + io_.Get(), + [](evutil_socket_t, short, void *p) { + auto *self = static_cast(p); + if (!self) return; + auto self_guard = self->shared_from_this(); + if (!self->closed_) self->Close(); + }, + this); timeval tv{}; tv.tv_sec = timeout_ms_ / 1000; tv.tv_usec = (timeout_ms_ % 1000) * 1000; @@ -707,26 +749,32 @@ class HttpServerConn : public std::enable_shared_from_this { } recv_.swap(tmp); req_ = req; - if (on_request_) on_request_(conn_id_, std::move(req)); + auto on_req = on_request_; + if (on_req) on_req(conn_id_, std::move(req)); } static void ReadCb(bufferevent *, void *ctx) { auto *self = static_cast(ctx); - if (self) self->HandleRead(false); + if (!self) return; + auto self_guard = self->shared_from_this(); + self->HandleRead(false); } static void EventCb(bufferevent *, short what, void *ctx) { auto *self = static_cast(ctx); if (!self) return; + auto self_guard = self->shared_from_this(); if (what & BEV_EVENT_CONNECTED) return; if (what & BEV_EVENT_EOF) { self->HandleRead(true); - if (self->writing_ || self->closed_) { + if (self->writing_ && !self->closed_) { self->Close(); } return; } - if (what & (BEV_EVENT_ERROR | BEV_EVENT_TIMEOUT)) self->Close(); + if ((what & (BEV_EVENT_ERROR | BEV_EVENT_TIMEOUT)) && !self->closed_) { + self->Close(); + } } native::IoContext &io_; @@ -760,8 +808,8 @@ class HttpServer { throw std::runtime_error("invalid listen address"); } listener_ = evconnlistener_new_bind( - io_.Get(), [](evconnlistener *, evutil_socket_t fd, sockaddr *, int, void *p) { static_cast(p)->OnAccept(fd); }, this, LEV_OPT_CLOSE_ON_FREE | LEV_OPT_REUSEABLE, - backlog > 0 ? backlog : -1, reinterpret_cast(&addr), sizeof(addr)); + io_.Get(), [](evconnlistener *, evutil_socket_t fd, sockaddr *, int, void *p) { static_cast(p)->OnAccept(fd); }, this, + LEV_OPT_CLOSE_ON_FREE | LEV_OPT_CLOSE_ON_EXEC | LEV_OPT_REUSEABLE, backlog > 0 ? backlog : -1, reinterpret_cast(&addr), sizeof(addr)); if (!listener_) throw std::runtime_error("listen failed"); auto fd = evconnlistener_get_fd(listener_); sockaddr_in local{}; @@ -775,8 +823,9 @@ class HttpServer { return bound_port_; } - void SetDispatch(std::string name) { + void SetDispatch(std::string name, JITType jit) { dispatch_ = std::move(name); + dispatch_jit_ = jit; } void SetNativeObject(NativeObject *nat) { @@ -785,16 +834,23 @@ class HttpServer { void Tick() { io_.Poll(); - auto pending = std::move(pending_requests_); - pending_requests_.clear(); - for (auto &item: pending) { + struct ConnsCleanupGuard { + std::unordered_map> &conns; + ~ConnsCleanupGuard() { + for (auto it = conns.begin(); it != conns.end();) { + if (!it->second) it = conns.erase(it); + else + ++it; + } + } + } cleanup{conns_}; + + const size_t n = pending_requests_.size(); + for (size_t i = 0; i < n && !pending_requests_.empty() && !closed_; ++i) { + auto item = std::move(pending_requests_.front()); + pending_requests_.pop_front(); DispatchRequest(item.first, item.second); } - for (auto it = conns_.begin(); it != conns_.end();) { - if (!it->second) it = conns_.erase(it); - else - ++it; - } } bool Reply(int conn_id, int status, std::string reason, HeaderList headers, std::string body) { @@ -810,6 +866,7 @@ class HttpServer { evconnlistener_free(listener_); listener_ = nullptr; } + pending_requests_.clear(); auto conns = conns_; for (auto &kv: conns) { if (kv.second) kv.second->Close(); @@ -823,6 +880,7 @@ class HttpServer { private: void OnAccept(evutil_socket_t fd) { + evutil_make_socket_closeonexec(fd); if (closed_) { evutil_closesocket(fd); return; @@ -839,7 +897,7 @@ class HttpServer { args[0] = inter::NativeToFakeluaString(lua_state_, "request"); args[1] = inter::NativeToFakeluaInt(lua_state_, conn_id); args[2] = RequestToTable(lua_state_, req); - CVar ret = CallNamed(lua_state_, dispatch_, args, 3); + CVar ret = CallNamed(lua_state_, dispatch_, args, 3, dispatch_jit_); if (ret.type_ == static_cast(VarType::Multi) && ret.data_.m && ret.data_.m->GetCount() > 0) { ret = ret.data_.m->GetVars()[0]; } @@ -866,8 +924,9 @@ class HttpServer { evconnlistener *listener_ = nullptr; SSL_CTX *ssl_ctx_ = nullptr; std::unordered_map> conns_; - std::vector> pending_requests_; + std::deque> pending_requests_; std::string dispatch_; + JITType dispatch_jit_ = JIT_TCC; State *lua_state_ = nullptr; NativeObject *native_obj_ = nullptr; uint16_t bound_port_ = 0; @@ -889,7 +948,9 @@ static std::vector &WrapperList(State *s, bool is_server) { static void EraseWrapper(State *st, bool is_server, NativeObject *nat) { if (!st) return; - auto &v = WrapperList(st, is_server); + auto *ws = st->TryGetModuleState(); + if (!ws) return; + auto &v = is_server ? ws->servers : ws->clients; v.erase(std::remove(v.begin(), v.end(), nat), v.end()); } @@ -918,6 +979,22 @@ static HttpServer *UnwrapServer(NativeObject *self) { return reinterpret_cast(self->GetInt("__http_server__", 0)); } +static void ReleaseClientOp(NativeObject *nat) { + if (!nat) return; + UnregisterWrapper(nat); + auto *c = UnwrapClient(nat); + if (c) { + nat->SetInt("__http_client__", 0); + c->ClearNativeObject(); + c->Close(); + } + auto *hold = reinterpret_cast(nat->GetInt("__http_hold__", 0)); + if (hold) { + nat->SetInt("__http_hold__", 0); + delete hold; + } +} + static void DestroyWrappers(State *s, bool is_server) { auto *ws = s->TryGetModuleState(); if (!ws) return; @@ -952,9 +1029,7 @@ void OnStateDeleted(State *s) { } static CVar ClientClose(NativeObject *self, State *s, CVar * /*args*/, int /*n*/) { - auto *op = UnwrapClient(self); - if (op) op->Close(); - (void) s; + ReleaseClientOp(self); return inter::NativeToFakeluaNil(s); } @@ -962,7 +1037,7 @@ static CVar ServerDispatch(NativeObject *self, State *s, CVar *args, int n) { if (n < 1) ThrowBadArgument(1, "dispatch", "function name expected"); auto *srv = UnwrapServer(self); if (!srv) return inter::NativeToFakeluaNil(s); - srv->SetDispatch(CVarToString(inter::GetNativeArg(s, args, n, 0))); + srv->SetDispatch(CVarToString(inter::GetNativeArg(s, args, n, 0)), s->CurrentJit()); return inter::NativeToFakeluaNil(s); } @@ -992,8 +1067,13 @@ static CVar ServerReply(NativeObject *self, State *s, CVar *args, int n) { } static CVar ServerClose(NativeObject *self, State *s, CVar * /*args*/, int /*n*/) { + UnregisterWrapper(self); auto *srv = UnwrapServer(self); - if (srv) srv->Close(); + if (srv) { + self->SetInt("__http_server__", 0); + srv->Close(); + delete srv; + } return inter::NativeToFakeluaNil(s); } @@ -1040,29 +1120,21 @@ static CVar StartClient(State *s, std::string method, std::string url, HeaderLis int64_t gid = s->GetNativeObjectManager().CreateGroup(); auto *nat = s->GetNativeObjectManager().Create(gid, "http_request"); auto op = std::make_shared(s, nat); - op->SetCallback(std::move(cb)); + op->SetCallback(std::move(cb), s->CurrentJit()); nat->SetInt("__http_client__", reinterpret_cast(op.get())); nat->SetInt("__http_owned__", 1); nat->RegisterMethod("close", ClientClose); RegisterWrapper(s, nat, false); - struct ClientHold { - std::shared_ptr ptr; - }; - auto *hold = new ClientHold{op}; nat->SetInt("__http_hold__", reinterpret_cast(hold)); - nat->SetFinalizer([hold](NativeObject *self) { - UnregisterWrapper(self); - auto *c = UnwrapClient(self); - if (c) { - self->SetInt("__http_client__", 0); - c->Close(); - } - self->SetInt("__http_hold__", 0); - delete hold; - }); - op->Start(std::move(method), std::move(url), std::move(headers), std::move(body), timeout_ms, version, tls_verify, std::move(tls_ca)); + nat->SetFinalizer([](NativeObject *self) { ReleaseClientOp(self); }); + try { + op->Start(std::move(method), std::move(url), std::move(headers), std::move(body), timeout_ms, version, tls_verify, std::move(tls_ca)); + } catch (...) { + s->GetNativeObjectManager().DestroyGroup(gid); + throw; + } return inter::NativeToFakeluaNativeObject(s, nat); } diff --git a/src/native/ini/native_ini.cpp b/src/native/ini/native_ini.cpp index a96249bb..2b1c8c56 100644 --- a/src/native/ini/native_ini.cpp +++ b/src/native/ini/native_ini.cpp @@ -75,7 +75,7 @@ static int IniHandlerV2(void *user, const char *section, const char *name, const } else { idx = it->second; } - table::TableHelper::SetTableStrId(st->state, st->sections[idx].tbl, name, ValueToLua(st->state, value ? value : "")); + table::TableHelper::SetTableTempStr(st->state, st->sections[idx].tbl, name, ValueToLua(st->state, value ? value : "")); return 1; } @@ -98,7 +98,7 @@ static CVar IniDecode(State *s, CVar *args, int n) { } for (auto &sec: st.sections) { - table::TableHelper::SetTableStrId(s, st.root, sec.name.c_str(), sec.tbl); + table::TableHelper::SetTableTempStr(s, st.root, sec.name, sec.tbl); } return st.root; } diff --git a/src/native/io/native_io.cpp b/src/native/io/native_io.cpp index 654af365..fe1c10d1 100644 --- a/src/native/io/native_io.cpp +++ b/src/native/io/native_io.cpp @@ -30,6 +30,24 @@ static constexpr const char *kPopenKey = "__popen__"; static constexpr const char *kIoStateKey = "__io_state__"; static constexpr const char *kLinesCloseKey = "__io_lines_close__"; +struct OwnedLinesFile { + FILE *fp = nullptr; + + explicit OwnedLinesFile(FILE *f) : fp(f) { + } + + void Close() { + if (fp) { + std::fclose(fp); + fp = nullptr; + } + } + + ~OwnedLinesFile() { + Close(); + } +}; + // 存在 State 上而不是这里的 static map:后者是全进程一份,多个线程各跑自己的 State 时 // 会并发改同一个容器。 struct IoState { @@ -183,12 +201,30 @@ extern "C" CVar FileLinesIterator(VarClosure *cl, CVar /*s*/, CVar /*var*/) { if (!ReadLine(fp, result)) { if (obj->GetBool(kLinesCloseKey, false)) { CloseIoFileHandle(obj); + UnregisterIoWrapper(obj); } return inter::NativeToFakeluaNil(iter_state); } return inter::NativeToFakeluaString(iter_state, result); } +extern "C" CVar OwnedFileLinesIterator(VarClosure *cl, CVar /*s*/, CVar /*var*/) { + if (!cl || cl->upvalue_count < 2) { + return CVar{static_cast(VarType::Nil)}; + } + State *iter_state = reinterpret_cast(cl->upvalues[0]->data_.i); + auto *holder = reinterpret_cast(cl->upvalues[1]->data_.i); + if (!iter_state || !holder || !holder->fp) { + return inter::NativeToFakeluaNil(iter_state); + } + std::string result; + if (!ReadLine(holder->fp, result)) { + holder->Close(); + return inter::NativeToFakeluaNil(iter_state); + } + return inter::NativeToFakeluaString(iter_state, result); +} + // 单格式读取辅助函数 // 从 fp 读取一个格式(* *l *L *a *n 或数字字节数),返回 CVar(可能为 nil) // 标准 Lua:file:read 接受 string(格式)或 number(字节数),Bool/Table 不合法 @@ -402,6 +438,7 @@ static NativeObject *MakeIoFile(State *s, FILE *fp, bool is_popen = false) { bool is_popen = self->GetBool(kPopenKey, false); int ret = is_popen ? ::pclose(fp) : std::fclose(fp); self->SetInt(kFpKey, 0); + UnregisterIoWrapper(self); if (ret == 0) { LOG_DEBUG(state, "io", "file:close: success"); return inter::NativeToFakeluaBool(state, true); @@ -582,6 +619,7 @@ void RegisterIoLibraryApi(State *s) { bool is_popen = obj->GetBool(kPopenKey, false); int ret = is_popen ? ::pclose(fp) : std::fclose(fp); obj->SetInt(kFpKey, 0); + UnregisterIoWrapper(obj); return ret == 0 ? inter::NativeToFakeluaBool(state, true) : inter::NativeToFakeluaNil(state); }); @@ -707,7 +745,6 @@ void RegisterIoLibraryApi(State *s) { }); // io.lines([filename]) → iterator|nil - // 简化:如果指定文件名则打开文件返回对象(用户手动循环 read),否则返回 nil RegisterNativeFunction(s, "io.lines", 0, true, [](State *state, CVar *args, int n) -> CVar { if (n < 1) { return MakeFileLinesClosure(state, CurrentInObj(state)); @@ -719,9 +756,10 @@ void RegisterIoLibraryApi(State *s) { if (filename.empty()) return inter::NativeToFakeluaNil(state); FILE *fp = utf8_io::Fopen(std::string(filename).c_str(), "r"); if (!fp) return inter::NativeToFakeluaNil(state); - auto *obj = MakeIoFile(state, fp); - obj->SetBool(kLinesCloseKey, true); - return MakeFileLinesClosure(state, obj); + // 挂在当前值分配器(常规执行期为 temp 堆)上注册析构器: + // 若循环因 break/return/报错提前退出,State::Reset() 也会立即 fclose,不泄漏 fd。 + auto *holder = state->GetValueAllocator().New(fp); + return MakeIteratorClosure(state, reinterpret_cast(OwnedFileLinesIterator), holder); }); // io.stdin / io.stdout / io.stderr 文件对象 diff --git a/src/native/json/native_json.cpp b/src/native/json/native_json.cpp index 7e6d41b1..f1421ff2 100644 --- a/src/native/json/native_json.cpp +++ b/src/native/json/native_json.cpp @@ -77,7 +77,7 @@ static CVar JsonValueToLua(State *s, const bj::value &v) { const bj::object &obj = v.get_object(); for (const auto &[key, val]: obj) { CVar lua_val = JsonValueToLua(s, val); - table::TableHelper::SetTableStrId(s, tbl, std::string_view(key.data(), key.size()), lua_val); + table::TableHelper::SetTableTempStr(s, tbl, std::string_view(key.data(), key.size()), lua_val); } return tbl; } diff --git a/src/native/mysql/mysql_connection.cpp b/src/native/mysql/mysql_connection.cpp index d7488917..4d349f2c 100644 --- a/src/native/mysql/mysql_connection.cpp +++ b/src/native/mysql/mysql_connection.cpp @@ -8,6 +8,7 @@ #include #include +#include #include #include #include @@ -98,10 +99,19 @@ void MysqlConnection::ClearWait() { void MysqlConnection::Teardown() { ClearWait(); + if (pending_stmt_) { + mysql_stmt_close(pending_stmt_); + pending_stmt_ = nullptr; + } + if (closing_exec_stmt_) { + mysql_stmt_close(closing_exec_stmt_); + closing_exec_stmt_ = nullptr; + } for (auto &kv: prepared_statements_) { if (kv.second) mysql_stmt_close(kv.second); } prepared_statements_.clear(); + pending_exec_stmt_id_ = 0; if (mysql_) { mysql_close(mysql_); mysql_ = nullptr; @@ -344,15 +354,26 @@ ResultsetData MysqlConnection::ConsumeResult(MYSQL_RES *res, bool is_resultset) return out; } +void MysqlConnection::StmtPrepare(const std::string &sql, const ResultCallback &callback) { + if (!mysql_ || close_pending_) { + deferred_errors_.push_back(DeferredError{callback, !mysql_ ? "connection closed" : "connection closing"}); + return; + } + if (state_ != ConnState::Ready || !ready_) { + deferred_errors_.push_back(DeferredError{callback, "connection not ready for prepare"}); + return; + } + result_cb_ = callback; + StmtPrepare(sql); +} + void MysqlConnection::StmtPrepare(const std::string &sql) { if (!mysql_ || close_pending_) { - pending_result_err_ = !mysql_ ? "connection closed" : "connection closing"; - pending_result_ = true; + deferred_errors_.push_back(DeferredError{result_cb_, !mysql_ ? "connection closed" : "connection closing"}); return; } if (state_ != ConnState::Ready || !ready_) { - pending_result_err_ = "connection not ready for prepare"; - pending_result_ = true; + deferred_errors_.push_back(DeferredError{result_cb_, "connection not ready for prepare"}); return; } state_ = ConnState::Querying; @@ -392,26 +413,35 @@ void MysqlConnection::StmtPrepare(const std::string &sql) { wait_op_ = WaitOp::None; } +void MysqlConnection::StmtExecute(uint32_t stmt_id, const std::vector ¶ms, const ResultCallback &callback) { + if (!mysql_ || close_pending_) { + deferred_errors_.push_back(DeferredError{callback, !mysql_ ? "connection closed" : "connection closing"}); + return; + } + if (state_ != ConnState::Ready || !ready_) { + deferred_errors_.push_back(DeferredError{callback, "connection not ready for execute"}); + return; + } + result_cb_ = callback; + StmtExecute(stmt_id, params); +} + void MysqlConnection::StmtExecute(uint32_t stmt_id, const std::vector ¶ms) { if (!mysql_ || close_pending_) { - pending_result_err_ = !mysql_ ? "connection closed" : "connection closing"; - pending_result_ = true; + deferred_errors_.push_back(DeferredError{result_cb_, !mysql_ ? "connection closed" : "connection closing"}); return; } if (state_ != ConnState::Ready || !ready_) { - pending_result_err_ = "connection not ready for execute"; - pending_result_ = true; + deferred_errors_.push_back(DeferredError{result_cb_, "connection not ready for execute"}); return; } auto it = prepared_statements_.find(stmt_id); if (it == prepared_statements_.end() || !it->second) { - pending_result_err_ = "statement not prepared"; - pending_result_ = true; + deferred_errors_.push_back(DeferredError{result_cb_, "statement not prepared"}); return; } if (params.size() != mysql_stmt_param_count(it->second)) { - pending_result_err_ = "statement parameter count mismatch"; - pending_result_ = true; + deferred_errors_.push_back(DeferredError{result_cb_, "statement parameter count mismatch"}); return; } state_ = ConnState::Querying; @@ -446,6 +476,7 @@ void MysqlConnection::StmtExecute(uint32_t stmt_id, const std::vector ArmWait(st); return; } + pending_exec_stmt_id_ = 0; if (err) { pending_result_err_ = mysql_stmt_error(stmt); pending_result_ = true; @@ -458,6 +489,9 @@ void MysqlConnection::StmtExecute(uint32_t stmt_id, const std::vector } ResultsetData MysqlConnection::ConsumeStmtResult(MYSQL_STMT *stmt) { + static constexpr size_t kMaxInitialStmtColBuf = 1024 * 1024; + static constexpr size_t kMaxStmtCellBytes = 64 * 1024 * 1024; + ResultsetData out; MYSQL_RES *meta = mysql_stmt_result_metadata(stmt); if (!meta) { @@ -479,9 +513,9 @@ ResultsetData MysqlConnection::ConsumeStmtResult(MYSQL_STMT *stmt) { std::vector nulls(n); std::memset(binds.data(), 0, n * sizeof(MYSQL_BIND)); for (unsigned int i = 0; i < n; ++i) { - unsigned long sz = fields[i].length ? fields[i].length + 1 : 256; - if (sz > 1024 * 1024) sz = 1024 * 1024; - bufs[i].assign(sz, 0); + const uint64_t raw_len = fields[i].length; + const size_t alloc_len = raw_len > 0 ? (raw_len >= kMaxInitialStmtColBuf ? kMaxInitialStmtColBuf : static_cast(raw_len) + 1) : 256; + bufs[i].assign(alloc_len, 0); binds[i].buffer_type = MYSQL_TYPE_STRING; binds[i].buffer = bufs[i].data(); binds[i].buffer_length = static_cast(bufs[i].size() - 1); @@ -497,10 +531,22 @@ ResultsetData MysqlConnection::ConsumeStmtResult(MYSQL_STMT *stmt) { FieldCell c; if (nulls[i]) { c.is_null = true; + } else if (lens[i] > binds[i].buffer_length) { + const size_t full_len = std::min(static_cast(lens[i]), kMaxStmtCellBytes); + c.value.resize(full_len); + MYSQL_BIND col_bind{}; + unsigned long col_len = 0; + my_bool col_null = 0; + col_bind.buffer_type = MYSQL_TYPE_STRING; + col_bind.buffer = c.value.data(); + col_bind.buffer_length = static_cast(full_len); + col_bind.length = &col_len; + col_bind.is_null = &col_null; + if (mysql_stmt_fetch_column(stmt, &col_bind, i, 0) != 0) { + c.value.assign(bufs[i].data(), binds[i].buffer_length); + } } else { - unsigned long ncopy = lens[i]; - if (ncopy > binds[i].buffer_length) ncopy = binds[i].buffer_length; - c.value.assign(bufs[i].data(), ncopy); + c.value.assign(bufs[i].data(), static_cast(lens[i])); } cells.push_back(std::move(c)); } @@ -514,8 +560,17 @@ ResultsetData MysqlConnection::ConsumeStmtResult(MYSQL_STMT *stmt) { void MysqlConnection::StmtClose(uint32_t stmt_id) { auto it = prepared_statements_.find(stmt_id); if (it == prepared_statements_.end()) return; - if (it->second) mysql_stmt_close(it->second); + MYSQL_STMT *stmt = it->second; prepared_statements_.erase(it); + if (!stmt) return; + if (wait_op_ == WaitOp::StmtExecute && pending_exec_stmt_id_ == stmt_id) { + if (closing_exec_stmt_ && closing_exec_stmt_ != stmt) { + mysql_stmt_close(closing_exec_stmt_); + } + closing_exec_stmt_ = stmt; + return; + } + mysql_stmt_close(stmt); } bool MysqlConnection::Ping() { @@ -524,8 +579,9 @@ bool MysqlConnection::Ping() { query_type_ = QueryType::Ping; int err = 0; int st = mysql_ping_start(&err, mysql_); - wait_op_ = WaitOp::Ping; if (st) { + state_ = ConnState::Querying; + wait_op_ = WaitOp::Ping; ArmWait(st); return true; } @@ -540,10 +596,21 @@ bool MysqlConnection::Ping() { void MysqlConnection::Close() { Teardown(); state_ = ConnState::Idle; + close_pending_ = false; pending_connect_ = false; + pending_connect_err_.clear(); pending_result_ = false; + pending_result_err_.clear(); pending_results_.clear(); + has_pending_stmt_id_ = false; + pending_stmt_id_ = 0; + dispatch_stmt_id_ = 0; next_stmt_id_ = 1; + while (!deferred_errors_.empty()) { + DeferredError item = std::move(deferred_errors_.front()); + deferred_errors_.pop_front(); + DispatchCallbackWithResult(item.cb, item.err.c_str()); + } DrainQueryQueue(); } @@ -646,6 +713,8 @@ void MysqlConnection::Continue(int ready) { if (err) { state_ = ConnState::Error; ready_ = false; + } else { + state_ = ConnState::Ready; } break; } @@ -679,9 +748,20 @@ void MysqlConnection::Continue(int ready) { break; } case WaitOp::StmtExecute: { - auto it = prepared_statements_.find(pending_exec_stmt_id_); - MYSQL_STMT *stmt = it != prepared_statements_.end() ? it->second : nullptr; - if (!stmt) return; + MYSQL_STMT *stmt = closing_exec_stmt_; + if (!stmt) { + auto it = prepared_statements_.find(pending_exec_stmt_id_); + if (it != prepared_statements_.end()) stmt = it->second; + } + if (!stmt) { + wait_op_ = WaitOp::None; + pending_exec_stmt_id_ = 0; + ClearWait(); + pending_result_err_ = "statement closed"; + pending_result_ = true; + state_ = ConnState::Ready; + return; + } int err = 0; int st = mysql_stmt_execute_cont(&err, stmt, ready); if (st) { @@ -689,14 +769,23 @@ void MysqlConnection::Continue(int ready) { return; } wait_op_ = WaitOp::None; + pending_exec_stmt_id_ = 0; ClearWait(); if (err) { pending_result_err_ = mysql_stmt_error(stmt); + if (closing_exec_stmt_ == stmt) { + mysql_stmt_close(closing_exec_stmt_); + closing_exec_stmt_ = nullptr; + } pending_result_ = true; state_ = ConnState::Ready; return; } pending_results_.push_back(ConsumeStmtResult(stmt)); + if (closing_exec_stmt_ == stmt) { + mysql_stmt_close(closing_exec_stmt_); + closing_exec_stmt_ = nullptr; + } FinishQueryOk(); break; } @@ -707,6 +796,14 @@ void MysqlConnection::Continue(int ready) { void MysqlConnection::Tick() { if (tick_depth_ > 0) return; + struct DeferredCloseOnUnwind { + MysqlConnection *self; + ~DeferredCloseOnUnwind() { + if (self->tick_depth_ == 0 && self->close_pending_ && !self->delete_on_unwind_) { + self->Close(); + } + } + } close_on_unwind{this}; TickDepthGuard guard(tick_depth_); if (state_ == ConnState::Connecting && timeout_ms_ > 0) { @@ -722,29 +819,46 @@ void MysqlConnection::Tick() { if (pending_connect_) { pending_connect_ = false; - if (!pending_connect_err_.empty()) DispatchConnect(pending_connect_err_.c_str()); + std::string connect_err = std::move(pending_connect_err_); + pending_connect_err_.clear(); + if (!connect_err.empty()) DispatchConnect(connect_err.c_str()); else DispatchConnect(nullptr); - pending_connect_err_.clear(); } if (pending_result_) { pending_result_ = false; - bool had_stmt_id = has_pending_stmt_id_; - uint32_t stmt_id_for_dispatch = pending_stmt_id_; + const bool had_stmt_id = has_pending_stmt_id_; + const uint32_t stmt_id_for_dispatch = pending_stmt_id_; has_pending_stmt_id_ = false; pending_stmt_id_ = 0; - if (!pending_result_err_.empty()) { - DispatchResult(pending_result_err_.c_str()); + std::string result_err = std::move(pending_result_err_); + pending_result_err_.clear(); + + struct ResultScopeGuard { + uint32_t &dispatch_stmt_id; + std::vector &pending_results; + ~ResultScopeGuard() { + dispatch_stmt_id = 0; + pending_results.clear(); + } + } result_guard{dispatch_stmt_id_, pending_results_}; + + if (!result_err.empty()) { + DispatchResult(result_err.c_str()); } else if (had_stmt_id) { dispatch_stmt_id_ = stmt_id_for_dispatch; DispatchResult(nullptr); - dispatch_stmt_id_ = 0; } else { DispatchResult(nullptr); } - pending_result_err_.clear(); - pending_results_.clear(); + } + + while (!deferred_errors_.empty()) { + DeferredError item = std::move(deferred_errors_.front()); + deferred_errors_.pop_front(); + DispatchCallbackWithResult(item.cb, item.err.c_str()); + if (close_pending_) break; } if (!queued_queries_.empty()) { @@ -804,7 +918,7 @@ void MysqlConnection::SetNativeObject(::fakelua::NativeObject *obj) { } bool MysqlConnection::Connected() const { - return ready_; + return ready_ && !close_pending_; } void MysqlConnection::MarkConnectedForTest() { @@ -815,6 +929,7 @@ void MysqlConnection::MarkConnectedForTest() { state_ = ConnState::Ready; ready_ = true; close_pending_ = false; + delete_on_unwind_ = false; } bool MysqlConnection::Connecting() const { @@ -829,13 +944,23 @@ bool MysqlConnection::ClosePending() const { return close_pending_; } +bool MysqlConnection::DeletePending() const { + return delete_on_unwind_; +} + void MysqlConnection::RequestClose() { close_pending_ = true; } +void MysqlConnection::RequestDelete() { + close_pending_ = true; + native_obj_ = nullptr; + delete_on_unwind_ = true; +} + bool MysqlConnection::HasPendingWork() const { return state_ == ConnState::Querying || state_ == ConnState::Connecting || state_ == ConnState::Handshaking || wait_op_ != WaitOp::None || pending_result_ || pending_connect_ || - !queued_queries_.empty(); + !queued_queries_.empty() || !deferred_errors_.empty(); } void MysqlConnection::SetError(MysqlErrorType type, uint16_t code, const std::string &msg, const std::string &sql_state) { @@ -846,26 +971,7 @@ void MysqlConnection::SetError(MysqlErrorType type, uint16_t code, const std::st } void MysqlConnection::InvokeCallback(const ResultCallback &cb, CVar *args, int n) { - // 派回【登记回调时的引擎】(与旧内联闭包自带 func_ptr 的语义一致)。 - auto func = lua_state_->GetVM().GetFunction(cb.name); - if (func.Empty()) return; - JITType jit_type = cb.jit; - void *addr = func.GetAddr(jit_type); - if (!addr) { - // 兜底:登记引擎没有该函数的编译产物(正常不应发生——同一份脚本三引擎都会编译)。 - // 按其余引擎依次找,避免回调静默丢失。 - static constexpr JITType kFallbacks[] = {JIT_TCC, JIT_GCC, JIT_INTERP}; - for (JITType t: kFallbacks) { - if (t == jit_type) continue; - addr = func.GetAddr(t); - if (addr) { - jit_type = t; - break; - } - } - } - if (!addr) return; - inter::DispatchCall(lua_state_, addr, args, n, jit_type); + DispatchNamedLuaCallback(lua_state_, cb.name, args, n, cb.jit); } namespace { @@ -910,7 +1016,21 @@ void MysqlConnection::DispatchConnect(const char *err_msg) { void MysqlConnection::DispatchCallbackWithResult(const ResultCallback &cb, const char *err_msg) { TickDepthGuard guard(tick_depth_); native::IoContext::DispatchScope dispatch_scope(io_); - if (!lua_state_ || cb.Empty()) return; + if (!lua_state_ || cb.Empty()) { + if (!err_msg) { + dispatch_stmt_id_ = 0; + pending_results_.clear(); + } + return; + } + + const uint32_t stmt_id = !err_msg ? dispatch_stmt_id_ : 0; + std::vector local_results; + if (!err_msg) { + dispatch_stmt_id_ = 0; + local_results = std::move(pending_results_); + pending_results_.clear(); + } // 多结果集可能在本函数内多次调用同一回调;绑定参数只 decode 一次,各次调用复用。 // decoded 必须活到最后一次 InvokeCallback 返回。 @@ -924,14 +1044,14 @@ void MysqlConnection::DispatchCallbackWithResult(const ResultCallback &cb, const if (err_msg) { std::vector args = BuildCallbackArgs(a0, inter::NativeToFakeluaString(lua_state_, msg), nil, decoded); InvokeCallback(cb, args.data(), static_cast(args.size())); - } else if (dispatch_stmt_id_ != 0) { - std::vector args = BuildCallbackArgs(a0, nil, inter::NativeToFakeluaInt(lua_state_, static_cast(dispatch_stmt_id_)), decoded); + } else if (stmt_id != 0) { + std::vector args = BuildCallbackArgs(a0, nil, inter::NativeToFakeluaInt(lua_state_, static_cast(stmt_id)), decoded); InvokeCallback(cb, args.data(), static_cast(args.size())); - } else if (pending_results_.empty()) { + } else if (local_results.empty()) { std::vector args = BuildCallbackArgs(a0, nil, table::TableHelper::CreateTable(lua_state_), decoded); InvokeCallback(cb, args.data(), static_cast(args.size())); } else { - for (const auto &rs: pending_results_) { + for (const auto &rs: local_results) { std::vector args = BuildCallbackArgs(a0, nil, ResultsetToLua(lua_state_, rs), decoded); InvokeCallback(cb, args.data(), static_cast(args.size())); if (close_pending_) break; diff --git a/src/native/mysql/mysql_connection.h b/src/native/mysql/mysql_connection.h index c65085d8..49a3f7d2 100644 --- a/src/native/mysql/mysql_connection.h +++ b/src/native/mysql/mysql_connection.h @@ -14,6 +14,7 @@ #include #include +#include #include #include #include @@ -99,7 +100,9 @@ class MysqlConnection { void Query(const std::string &sql); void Query(const std::string &sql, const ResultCallback &callback); void StmtPrepare(const std::string &sql); + void StmtPrepare(const std::string &sql, const ResultCallback &callback); void StmtExecute(uint32_t stmt_id, const std::vector ¶ms); + void StmtExecute(uint32_t stmt_id, const std::vector ¶ms, const ResultCallback &callback); void StmtClose(uint32_t stmt_id); bool Ping(); void Close(); @@ -121,7 +124,9 @@ class MysqlConnection { int TickDepth() const; bool ClosePending() const; + bool DeletePending() const; void RequestClose(); + void RequestDelete(); bool HasPendingWork() const; private: @@ -147,6 +152,13 @@ class MysqlConnection { std::vector queued_queries_; + struct DeferredError { + ResultCallback cb; + std::string err; + }; + + std::deque deferred_errors_; + enum class QueryType { None, Query, StmtPrepare, StmtExecute, Ping }; QueryType query_type_ = QueryType::None; @@ -157,6 +169,7 @@ class MysqlConnection { uint32_t next_stmt_id_ = 1; uint32_t pending_exec_stmt_id_ = 0; MYSQL_STMT *pending_stmt_ = nullptr; + MYSQL_STMT *closing_exec_stmt_ = nullptr; std::vector pending_stmt_params_; std::vector pending_binds_; std::vector pending_bind_lens_; @@ -186,6 +199,7 @@ class MysqlConnection { bool ready_ = false; int tick_depth_ = 0; bool close_pending_ = false; + bool delete_on_unwind_ = false; native::LifeToken life_; diff --git a/src/native/mysql/native_mysql.cpp b/src/native/mysql/native_mysql.cpp index 06731b2d..d50682c7 100644 --- a/src/native/mysql/native_mysql.cpp +++ b/src/native/mysql/native_mysql.cpp @@ -77,7 +77,9 @@ static std::vector &WrapperList(State *s, bool is_pool) { static void EraseWrapper(State *st, bool is_pool, NativeObject *nat) { if (!st) return; - auto &v = WrapperList(st, is_pool); + auto *ws = st->TryGetModuleState(); + if (!ws) return; + auto &v = is_pool ? ws->pools : ws->conns; v.erase(std::remove(v.begin(), v.end(), nat), v.end()); } @@ -227,9 +229,11 @@ static CVar MysqlConnect(State *s, CVar *args, int n) { auto *c = UnwrapConnNative(self); if (c) { self->SetInt("__mysql_conn__", 0); + c->SetNativeObject(nullptr); if (c->TickDepth() > 0) { - c->RequestClose(); + c->RequestDelete(); } else { + c->Close(); delete c; } } @@ -298,8 +302,7 @@ CVar ConnStmtPrepare(NativeObject *self, State *s, CVar *args, int n) { if (!conn || !conn->Connected()) error("conn:stmt_prepare: connection is closed"); conn->SetState(s); - conn->SetResultCallback(cb); - conn->StmtPrepare(sql); + conn->StmtPrepare(sql, cb); MaybeReleaseOwnedConn(self); return inter::NativeToFakeluaNil(s); @@ -356,8 +359,7 @@ CVar ConnStmtExecute(NativeObject *self, State *s, CVar *args, int n) { if (!conn || !conn->Connected()) error("conn:stmt_execute: connection is closed"); conn->SetState(s); - conn->SetResultCallback(cb); - conn->StmtExecute(stmt_id, params); + conn->StmtExecute(stmt_id, params, cb); MaybeReleaseOwnedConn(self); return inter::NativeToFakeluaNil(s); @@ -386,11 +388,30 @@ void TickMysqlConnection(NativeObject *self, State *s) { if (!conn) return; if (conn->TickDepth() > 0) return; + struct AfterTickGuard { + NativeObject *self; + MysqlConnection *conn; + ~AfterTickGuard() { + if (conn->TickDepth() == 0) { + if (conn->DeletePending()) { + conn->Close(); + delete conn; + return; + } + if (conn->ClosePending()) { + conn->Close(); + } + } + if (self && self->Alive()) { + MaybeReleaseOwnedConn(self); + MaybeReleasePooledConn(self); + MaybeReapPool(self); + } + } + } after{self, conn}; + conn->SetState(s); conn->Tick(); - MaybeReleaseOwnedConn(self); - MaybeReleasePooledConn(self); - MaybeReapPool(self); } // conn:close() diff --git a/src/native/mysql/native_mysql_pool.cpp b/src/native/mysql/native_mysql_pool.cpp index a51ae43f..54d6bb68 100644 --- a/src/native/mysql/native_mysql_pool.cpp +++ b/src/native/mysql/native_mysql_pool.cpp @@ -76,22 +76,36 @@ void PoolObject::InvalidateAcquiredWrappers() { wrappers.clear(); for (auto *nat: held) { if (!nat) continue; + UnregisterMysqlNativeWrapper(nat); auto *c = UnwrapConnNative(nat); if (c) c->SetNativeObject(nullptr); nat->SetInt("__mysql_conn__", 0); nat->SetInt("__mysql_pool_ptr__", 0); nat->SetInt("__mysql_pool_obj__", 0); + nat->SetInt("__mysql_auto_release__", 0); } } -void DetachAcquiredWrapper(NativeObject *nat) { +static void DetachAcquiredWrapperImpl(NativeObject *nat, bool destroy_group) { if (!nat) return; + auto *st = reinterpret_cast(nat->GetInt("__mysql_owner_state__", 0)); + if (!st) st = reinterpret_cast(nat->GetInt("__mysql_state__", 0)); + const int64_t gid = nat->GetGroupId(); + + UnregisterMysqlNativeWrapper(nat); auto *po = reinterpret_cast(nat->GetInt("__mysql_pool_obj__", 0)); auto *c = UnwrapConnNative(nat); if (po) { po->wrappers.erase(nat); if (po->pool && c) { c->SetNativeObject(nullptr); + if (c->HasPendingWork()) { + if (c->TickDepth() > 0) { + c->RequestClose(); + } else { + c->Close(); + } + } po->pool->Release(c); } } @@ -99,6 +113,15 @@ void DetachAcquiredWrapper(NativeObject *nat) { nat->SetInt("__mysql_pool_ptr__", 0); nat->SetInt("__mysql_pool_obj__", 0); nat->SetInt("__mysql_auto_release__", 0); + nat->SetInt("__mysql_owner_state__", 0); + + if (destroy_group && st && gid != 0) { + st->GetNativeObjectManager().DestroyGroup(gid); + } +} + +void DetachAcquiredWrapper(NativeObject *nat) { + DetachAcquiredWrapperImpl(nat, true); } void MaybeReleasePooledConn(NativeObject *self) { @@ -231,13 +254,11 @@ static NativeObject *AcquireConnObject(State *s, PoolObject *pool_obj) { nat->SetInt("__mysql_conn__", reinterpret_cast(conn)); nat->SetInt("__mysql_pool_ptr__", reinterpret_cast(pool_obj->pool.get())); nat->SetInt("__mysql_pool_obj__", reinterpret_cast(pool_obj)); + nat->SetInt("__mysql_owner_state__", reinterpret_cast(s)); nat->SetInt("__mysql_owned__", 0); pool_obj->wrappers.insert(nat); RegisterMysqlNativeWrapper(s, nat, false); - nat->SetFinalizer([](NativeObject *self) { - UnregisterMysqlNativeWrapper(self); - DetachAcquiredWrapper(self); - }); + nat->SetFinalizer([](NativeObject *self) { DetachAcquiredWrapperImpl(self, false); }); nat->RegisterMethod("query", ConnQuery); nat->RegisterMethod("stmt_prepare", ConnStmtPrepare); nat->RegisterMethod("stmt_execute", ConnStmtExecute); diff --git a/src/native/native_common.h b/src/native/native_common.h index 6fc98ffd..96e93f76 100644 --- a/src/native/native_common.h +++ b/src/native/native_common.h @@ -155,4 +155,78 @@ inline CVar MakeIteratorClosure(State *state, void *func_ptr, void *iter_state) return res; } +// 按 Lua 调用语义(缺参补 nil、多余实参丢弃、vararg 打包为 Multi)分发具名回调, +// 优先采用登记时或当前活跃的执行后端,未编译该后端时依次回退 TCC / GCC / INTERP,支持原生函数回退。 +inline CVar DispatchNamedLuaCallback(State *state, std::string_view func_name, const CVar *args, int arg_count, JITType preferred_jit) { + if (!state || func_name.empty()) { + return CVar{static_cast(VarType::Nil)}; + } + if (!args || arg_count < 0) { + arg_count = 0; + } + if (arg_count > static_cast(kMaxFunctionInputParams)) { + ThrowFakeluaException(std::format("callback '{}' passed too many arguments ({}), max is {}", func_name, arg_count, kMaxFunctionInputParams)); + } + + if (const VmFunction *jit_func = state->GetVM().FindFunction(func_name)) { + const bool is_vararg = jit_func->IsVararg(); + const int expected = jit_func->GetArgCount(); + JITType target_jit = preferred_jit; + void *addr = nullptr; + const JITType candidates[5] = {preferred_jit, state->CurrentJit(), JIT_TCC, JIT_GCC, JIT_INTERP}; + for (JITType cand: candidates) { + if (static_cast(cand) < static_cast(JIT_MAX)) { + if (void *p = jit_func->GetAddr(cand)) { + addr = p; + target_jit = cand; + break; + } + } + } + jit_func = nullptr; + if (!addr) { + return CVar{static_cast(VarType::Nil)}; + } + if (expected < 0 || expected > static_cast(kMaxFunctionInputParams)) { + ThrowFakeluaException(std::format("callback '{}' declares too many parameters ({}), max is {}", func_name, expected, kMaxFunctionInputParams)); + } + if (is_vararg) { + CVar padded[kMaxFunctionInputParams]{}; + const int fixed = (expected > 0) ? (expected - 1) : 0; + for (int i = 0; i < fixed; ++i) { + padded[i] = (i < arg_count) ? args[i] : inter::NativeToFakeluaNil(state); + } + const int extra = (arg_count > fixed) ? (arg_count - fixed) : 0; + CVar multi = inter::AllocMultiCVar(state, extra); + for (int i = 0; i < extra; ++i) { + inter::SetMultiCVarElement(multi, i, args[fixed + i]); + } + padded[fixed] = multi; + const int n_dispatch = (expected > 0) ? expected : 1; + return inter::DispatchCall(state, addr, padded, n_dispatch, target_jit); + } + if (arg_count == expected && (expected == 0 || args != nullptr)) { + return inter::DispatchCall(state, addr, args, expected, target_jit); + } + CVar padded[kMaxFunctionInputParams]{}; + for (int i = 0; i < expected; ++i) { + padded[i] = (i < arg_count) ? args[i] : inter::NativeToFakeluaNil(state); + } + return inter::DispatchCall(state, addr, padded, expected, target_jit); + } + + if (const auto *entry = state->GetVM().FindNativeFunction(func_name); entry && entry->callback) { + CVar buf[kMaxFunctionInputParams]{}; + for (int i = 0; i < arg_count; ++i) { + buf[i] = args[i]; + } + return entry->callback(state, buf, arg_count); + } + return CVar{static_cast(VarType::Nil)}; +} + +inline CVar DispatchNamedLuaCallback(State *state, std::string_view func_name, const CVar *args, int arg_count) { + return DispatchNamedLuaCallback(state, func_name, args, arg_count, state ? state->CurrentJit() : JIT_TCC); +} + }// namespace fakelua diff --git a/src/native/net/native_net.cpp b/src/native/net/native_net.cpp index 506f2d7e..4d14fcc5 100644 --- a/src/native/net/native_net.cpp +++ b/src/native/net/native_net.cpp @@ -9,6 +9,7 @@ #include #include +#include #include #include #include @@ -25,6 +26,7 @@ namespace fakelua::net { struct NetObject { State *state = nullptr; std::string dispatch_name;// Lua 回调函数名(统一入口) + JITType dispatch_jit = JIT_TCC; bool is_server = false; // 可变状态全部存 C++ 侧 @@ -45,6 +47,8 @@ struct NetObject { // tick 回调里 Lua 可能 :close(),不能立刻 delete this。延后到 tick 返回。 int tick_depth = 0; bool close_pending = false; + std::exception_ptr pending_exception; + native::LifeToken life; // 回调上下文(native dispatch 期间)里的 send 先入队,由本轮 tick 派发完后统一 // 泵出——消除"回调里 send 是否生效"的平台相关行为(事件驱动改轮询驱动)。 @@ -87,59 +91,23 @@ static std::string CVarToString(CVar v) { // C++ → Lua 回调派发(核心:按函数名查找,不存闭包) // 回调是纯函数:接收事件参数,返回可选指令(echo 等) -static CVar CallLuaEvent(State *state, const std::string &func_name, const char *type, int connid, const char *data, size_t len, int reason) { - if (func_name.empty()) return CVar{static_cast(VarType::Nil)}; - - // 优先查找 JIT 编译的 Lua 函数 - auto func = state->GetVM().GetFunction(func_name); - void *addr = nullptr; - JITType jit_type = JIT_TCC; - if (!func.Empty()) { - addr = func.GetAddr(JIT_TCC); - if (!addr) { - addr = func.GetAddr(JIT_GCC); - jit_type = JIT_GCC; - } - } - - if (addr) { - // 构造参数: (type, connid, data, len, reason) - CVar args[5]; - args[0] = inter::NativeToFakeluaString(state, type); - args[1] = inter::NativeToFakeluaInt(state, connid); - if (data && len > 0) { - args[2] = inter::NativeToFakeluaString(state, std::string(data, len)); - args[3] = inter::NativeToFakeluaInt(state, static_cast(len)); - } else { - CVar nil{}; - nil.type_ = static_cast(VarType::Nil); - args[2] = nil; - args[3] = nil; - } - args[4] = inter::NativeToFakeluaInt(state, reason); +static CVar CallLuaEvent(State *state, const std::string &func_name, JITType preferred_jit, const char *type, int connid, const char *data, size_t len, int reason) { + if (!state || func_name.empty()) return CVar{static_cast(VarType::Nil)}; - return inter::DispatchCall(state, addr, args, 5, jit_type); + CVar args[5]; + args[0] = inter::NativeToFakeluaString(state, type); + args[1] = inter::NativeToFakeluaInt(state, connid); + if (data && len > 0) { + args[2] = inter::NativeToFakeluaString(state, std::string(data, len)); + args[3] = inter::NativeToFakeluaInt(state, static_cast(len)); } else { - // 回退:尝试原生函数 - auto *entry = state->GetVM().FindNativeFunction(func_name); - if (entry && entry->callback) { - CVar args[5]; - args[0] = inter::NativeToFakeluaString(state, type); - args[1] = inter::NativeToFakeluaInt(state, connid); - if (data && len > 0) { - args[2] = inter::NativeToFakeluaString(state, std::string(data, len)); - args[3] = inter::NativeToFakeluaInt(state, static_cast(len)); - } else { - CVar nil{}; - nil.type_ = static_cast(VarType::Nil); - args[2] = nil; - args[3] = nil; - } - args[4] = inter::NativeToFakeluaInt(state, reason); - return entry->callback(state, args, 5); - } + CVar nil{}; + nil.type_ = static_cast(VarType::Nil); + args[2] = nil; + args[3] = nil; } - return CVar{static_cast(VarType::Nil)}; + args[4] = inter::NativeToFakeluaInt(state, reason); + return DispatchNamedLuaCallback(state, func_name, args, 5, preferred_jit); } // 处理回调返回值:解析 Lua 返回的指令 @@ -301,18 +269,20 @@ static CVar NetDispatch(NativeObject *self, State *s, CVar *args, int n) { } } obj->dispatch_name = std::move(fname); + obj->dispatch_jit = s->CurrentJit(); return inter::NativeToFakeluaNil(s); } // 派发单条事件给 Lua(在 tick() 同步上下文里执行,保留 tick_depth/close_pending 语义) void NetObject::DispatchEventFor(const ConnEvent &ev) { + if (close_pending) return; switch (ev.kind) { case EventKind::Connect: conn_count++; server_connid = ev.conn_id; PushEvent("conn"); { - CVar ret = CallLuaEvent(state, dispatch_name, "conn", ev.conn_id, nullptr, 0, 0); + CVar ret = CallLuaEvent(state, dispatch_name, dispatch_jit, "conn", ev.conn_id, nullptr, 0, 0); HandleCallbackReturn(ret, ev.conn_id); } break; @@ -326,14 +296,14 @@ void NetObject::DispatchEventFor(const ConnEvent &ev) { PushEvent("recv"); LOG_DEBUG(state, "net", "{} recv: connid={} len={}", is_server ? "server" : "client", ev.conn_id, ev.data.size()); { - CVar ret = CallLuaEvent(state, dispatch_name, "recv", ev.conn_id, ev.data.data(), ev.data.size(), 0); + CVar ret = CallLuaEvent(state, dispatch_name, dispatch_jit, "recv", ev.conn_id, ev.data.data(), ev.data.size(), 0); HandleCallbackReturn(ret, ev.conn_id); } break; case EventKind::Close: PushEvent("close"); { - CVar ret = CallLuaEvent(state, dispatch_name, "close", ev.conn_id, nullptr, 0, 0); + CVar ret = CallLuaEvent(state, dispatch_name, dispatch_jit, "close", ev.conn_id, nullptr, 0, 0); HandleCallbackReturn(ret, ev.conn_id); } break; @@ -341,13 +311,16 @@ void NetObject::DispatchEventFor(const ConnEvent &ev) { } // 驱动 IO 处理,由 runtime.tick() 调用 -// 新版:Boost.Asio 引擎在后台线程跑,事件入队;tick() 排空队列并同步派发 Lua 回调。 // tick_depth + close_pending 语义保持不变。 // 关闭后的对象 unwrap 返回空,于是自然变成 no-op。 static void TickNetObject(NativeObject *self) { auto *obj = Unwrap(self); if (!obj) return; if (obj->tick_depth > 0) return; + if (obj->close_pending && !obj->pending_exception) { + ReleaseNetObject(self); + return; + } auto finish_tick = [self, obj]() { if (obj->tick_depth < 0) obj->tick_depth = 0; @@ -366,11 +339,20 @@ static void TickNetObject(NativeObject *self) { obj->client->DrainEventsWith([obj](const ConnEvent &ev) { obj->DispatchEventFor(ev); }); } } catch (...) { + obj->pending_exception = nullptr; obj->tick_depth--; obj->FlushPendingSends(); finish_tick(); throw; } + if (obj->pending_exception) { + auto ex = obj->pending_exception; + obj->pending_exception = nullptr; + obj->tick_depth--; + obj->FlushPendingSends(); + finish_tick(); + std::rethrow_exception(ex); + } obj->tick_depth--; // 回调期间积压的 send 在这里统一泵出(socket 写在派发上下文之外执行)。 obj->FlushPendingSends(); @@ -387,6 +369,16 @@ void TickAll(State *s) { for (auto *nat: wrappers) { TickNetObject(nat); } + auto post_wrappers = ws->list; + for (auto *nat: post_wrappers) { + auto *obj = Unwrap(nat); + if (!obj || obj->tick_depth > 0) continue; + if (obj->pending_exception) { + TickNetObject(nat); + } else if (obj->close_pending) { + ReleaseNetObject(nat); + } + } } // server:send(connid, data) / client:send(data) @@ -454,12 +446,29 @@ static CVar NetSend(NativeObject *self, State *s, CVar *args, int n) { // server:close_connection(connid) — 关闭单条连接(C++ 已有能力,现导出到 Lua) static CVar NetCloseConnection(NativeObject *self, State *s, CVar *args, int n) { auto *obj = Unwrap(self); - if (!obj || !obj->is_server || !obj->server) return inter::NativeToFakeluaBool(s, false); + if (!obj || !obj->is_server || !obj->server || obj->close_pending) return inter::NativeToFakeluaBool(s, false); if (n < 1) ThrowBadArgument(1, "close_connection", "connid expected"); int connid = static_cast(CheckIntegerArg(inter::GetNativeArg(s, args, n, 0), 1, "close_connection")); - if (!obj->server->CloseConnection(connid)) return inter::NativeToFakeluaBool(s, false); + if (!obj->server->CloseConnection(connid, false)) return inter::NativeToFakeluaBool(s, false); obj->PushEvent("close"); - CVar ret = CallLuaEvent(obj->state, obj->dispatch_name, "close", connid, nullptr, 0, 0); + struct CloseDispatchGuard { + NativeObject *self; + NetObject *obj; + explicit CloseDispatchGuard(NativeObject *nat, NetObject *o) : self(nat), obj(o) { + ++obj->tick_depth; + } + ~CloseDispatchGuard() { + if (obj->tick_depth > 0) --obj->tick_depth; + if (obj->tick_depth == 0) { + obj->FlushPendingSends(); + if (obj->close_pending) { + ReleaseNetObject(self); + } + } + } + } guard(self, obj); + native::IoContext::DispatchScope dispatch_scope(s->GetIoContext()); + CVar ret = CallLuaEvent(obj->state, obj->dispatch_name, obj->dispatch_jit, "close", connid, nullptr, 0, 0); obj->HandleCallbackReturn(ret, connid); return inter::NativeToFakeluaBool(s, true); } @@ -719,17 +728,19 @@ static net::NetConfig ParseConfig(State *s, CVar *args, int n) { } // 辅助:建立 Lua 自定义解包函数的 C++ parser 桥接 -static void SetupLuaCustomParser(State *s, net::NetConfig &cfg, const std::string &parser_name) { - if (parser_name.empty()) return; +static void SetupLuaCustomParser(State *s, NetObject *obj, net::NetConfig &cfg, const std::string &parser_name) { + if (parser_name.empty() || !obj) return; cfg.framer = net::FramerType::Custom; cfg.custom_parser_name = parser_name; // 创建捕获 parser_name 的 C++ 回调,从 CircularBuffer 窥视数据,调用 Lua parser 解包 - // 按值捕获 max_packet_len,避免 lambda 存入 cfg 后引用工厂局部 cfg 导致悬空 + // 按值捕获 max_packet_len 与登记时的脚本引擎,避免悬空或走错后端 const int max_pkt = cfg.max_packet_len; - cfg.custom_parser_fn = [s, parser_name, max_pkt](net::CircularBuffer &buf, const char *&out_payload, uint32_t &out_len) -> bool { - if (buf.Empty()) return false; + const JITType parser_jit = s->CurrentJit(); + auto watch = obj->life.GetWatch(); + cfg.custom_parser_fn = [s, obj, watch, parser_name, parser_jit, max_pkt](net::CircularBuffer &buf, const char *&out_payload, uint32_t &out_len) -> bool { + if (!watch.Alive() || obj->close_pending || obj->pending_exception || buf.Empty()) return false; // 用 buf 自己的暂存区:写在 lambda 体内的 static 是所有连接、所有 State 共享同一 // 份,按缓冲区各存一份既没有竞争,也不会解析另一条连接就把这里的数据冲掉。 @@ -741,55 +752,53 @@ static void SetupLuaCustomParser(State *s, net::NetConfig &cfg, const std::strin if (peek_buf.size() < total) peek_buf.resize(total); buf.Peek(peek_buf.data(), total); - // 调用 Lua 解包函数: parser(buffer_str) - // 期望返回值: - // 1. (packet_str, consumed_bytes) - // 2. 或仅 packet_str(默认 consumed_bytes = packet_str.length()) - // 3. 或 nil(表示数据尚未就绪,需等待更多数据) - auto func = s->GetVM().GetFunction(parser_name); - void *addr = nullptr; - JITType jit_type = JIT_TCC; - if (!func.Empty()) { - addr = func.GetAddr(JIT_TCC); - if (!addr) { - addr = func.GetAddr(JIT_GCC); - jit_type = JIT_GCC; + struct ParserTickGuard { + NetObject *obj; + explicit ParserTickGuard(NetObject *o) : obj(o) { + ++obj->tick_depth; } - } - - CVar res{static_cast(VarType::Nil)}; - CVar in_arg = inter::NativeToFakeluaString(s, std::string(peek_buf.data(), total)); - - if (addr) { - CVar args[1] = {in_arg}; - res = inter::DispatchCall(s, addr, args, 1, jit_type); - } else { - auto *entry = s->GetVM().FindNativeFunction(parser_name); - if (entry && entry->callback) { - CVar args[1] = {in_arg}; - res = entry->callback(s, args, 1); + ~ParserTickGuard() { + if (obj->tick_depth > 0) --obj->tick_depth; } - } - - if (res.type_ == static_cast(VarType::Nil)) { - return false; - } + } tick_guard(obj); + native::IoContext::DispatchScope dispatch_scope(s->GetIoContext()); + // 调用 Lua 解包函数: parser(buffer_str) + // 必须在此处拦截 C++ 异常,绝不让异常穿过 C 编译的 libevent 栈帧: + // 异常暂存在 obj->pending_exception,并在不消费 buf 的前提下返回 true, + // 使 TryParsePacket 标记 out_error=true 并干净关闭连接,随后由 TickNetObject 在外层重抛。 std::string parsed_str; size_t consumed = 0; + try { + CVar in_arg = inter::NativeToFakeluaString(s, std::string(peek_buf.data(), total)); + CVar args[1] = {in_arg}; + CVar res = DispatchNamedLuaCallback(s, parser_name, args, 1, parser_jit); + + if (obj->close_pending || res.type_ == static_cast(VarType::Nil)) { + return false; + } - if (res.type_ == static_cast(VarType::Multi)) { - CVar p_var = inter::GetMultiCVarElement(res, 0); - parsed_str = CVarToString(p_var); - CVar c_var = inter::GetMultiCVarElement(res, 1); - if (c_var.type_ != static_cast(VarType::Nil)) { - consumed = static_cast(inter::CVarToInteger(c_var, static_cast(parsed_str.size()))); + if (res.type_ == static_cast(VarType::Multi)) { + CVar p_var = inter::GetMultiCVarElement(res, 0); + parsed_str = CVarToString(p_var); + CVar c_var = inter::GetMultiCVarElement(res, 1); + if (c_var.type_ != static_cast(VarType::Nil)) { + int64_t raw_consumed = inter::CVarToInteger(c_var, static_cast(parsed_str.size())); + consumed = raw_consumed > 0 ? static_cast(raw_consumed) : 0; + } else { + consumed = parsed_str.size(); + } } else { + parsed_str = CVarToString(res); consumed = parsed_str.size(); } - } else { - parsed_str = CVarToString(res); - consumed = parsed_str.size(); + } catch (...) { + if (!obj->pending_exception) { + obj->pending_exception = std::current_exception(); + } + out_payload = nullptr; + out_len = 0; + return true; } if (consumed == 0 && parsed_str.empty()) { @@ -812,9 +821,6 @@ static void SetupLuaCustomParser(State *s, net::NetConfig &cfg, const std::strin } static CVar CreateNetServer(State *s, net::NetConfig cfg, const char *type_name) { - if (!cfg.custom_parser_name.empty()) { - SetupLuaCustomParser(s, cfg, cfg.custom_parser_name); - } if (cfg.tls && (cfg.tls_cert.empty() || cfg.tls_key.empty())) { ThrowFakeluaException(std::format("{}: tls=true requires cert and key", type_name)); } @@ -824,6 +830,9 @@ static CVar CreateNetServer(State *s, net::NetConfig cfg, const char *type_name) auto *obj = new NetObject(); obj->state = s; obj->is_server = true; + if (!cfg.custom_parser_name.empty()) { + SetupLuaCustomParser(s, obj, cfg, cfg.custom_parser_name); + } obj->server = std::make_unique(cfg, s); obj->server->Start(); @@ -859,15 +868,14 @@ static CVar CreateNetServer(State *s, net::NetConfig cfg, const char *type_name) } static CVar CreateNetClient(State *s, net::NetConfig cfg, const char *type_name) { - if (!cfg.custom_parser_name.empty()) { - SetupLuaCustomParser(s, cfg, cfg.custom_parser_name); - } - net::NetInit(); auto *obj = new NetObject(); obj->state = s; obj->is_server = false; + if (!cfg.custom_parser_name.empty()) { + SetupLuaCustomParser(s, obj, cfg, cfg.custom_parser_name); + } obj->client = std::make_unique(cfg, s); obj->client->Connect(); diff --git a/src/native/net/net_event.cpp b/src/native/net/net_event.cpp index 70beb294..c06cd633 100644 --- a/src/native/net/net_event.cpp +++ b/src/native/net/net_event.cpp @@ -24,6 +24,7 @@ bool IsWebSocket(const NetConfig &cfg) { } void ApplyFdOptions(evutil_socket_t fd, const NetConfig &cfg) { + evutil_make_socket_closeonexec(fd); SetSocketOptions(static_cast(fd), cfg); } @@ -245,6 +246,10 @@ class EventConn : public std::enable_shared_from_this { } void OnConnected() { + if (bev_) { + evutil_socket_t fd = bufferevent_getfd(bev_); + if (fd != -1) evutil_make_socket_closeonexec(fd); + } if (IsWebSocket(cfg_)) return; MarkReady(from_client_ || tls_); } @@ -384,12 +389,15 @@ class EventConn : public std::enable_shared_from_this { static void ReadCb(bufferevent *, void *ctx) { auto *self = static_cast(ctx); - if (self) self->HandleRead(); + if (!self) return; + auto self_guard = self->shared_from_this(); + self->HandleRead(); } static void EventCb(bufferevent *, short what, void *ctx) { auto *self = static_cast(ctx); if (!self) return; + auto self_guard = self->shared_from_this(); if (what & BEV_EVENT_CONNECTED) { self->OnConnected(); return; @@ -444,8 +452,8 @@ void TcpServer::Start() { sockaddr_in addr{}; if (!FillSockaddr(addr, config_.ip, config_.port)) return; listener_ = evconnlistener_new_bind( - io_.Get(), [](evconnlistener *, evutil_socket_t fd, sockaddr *, int, void *p) { static_cast(p)->OnAccept(fd); }, this, LEV_OPT_CLOSE_ON_FREE | LEV_OPT_REUSEABLE, - config_.backlog > 0 ? config_.backlog : -1, reinterpret_cast(&addr), sizeof(addr)); + io_.Get(), [](evconnlistener *, evutil_socket_t fd, sockaddr *, int, void *p) { static_cast(p)->OnAccept(fd); }, this, + LEV_OPT_CLOSE_ON_FREE | LEV_OPT_CLOSE_ON_EXEC | LEV_OPT_REUSEABLE, config_.backlog > 0 ? config_.backlog : -1, reinterpret_cast(&addr), sizeof(addr)); } void TcpServer::Stop() { @@ -458,6 +466,7 @@ void TcpServer::Stop() { if (c) c->Close(false); } conns_.clear(); + events_.clear(); } void TcpServer::OnAccept(evutil_socket_t fd) { @@ -494,12 +503,20 @@ void TcpServer::EmitEvent(ConnEvent ev) { void TcpServer::DrainEventsWith(const std::function &dispatcher) { io_.Poll(); - std::vector evs; - evs.swap(events_); + struct CleanupGuard { + std::vector> &conns; + ~CleanupGuard() { + for (auto &c: conns) { + if (c && !c->IsOpen()) c.reset(); + } + } + } cleanup{conns_}; native::IoContext::DispatchScope scope(io_); - for (const auto &ev: evs) dispatcher(ev); - for (auto &c: conns_) { - if (c && !c->IsOpen()) c.reset(); + const size_t n = events_.size(); + for (size_t i = 0; i < n && !events_.empty(); ++i) { + ConnEvent ev = std::move(events_.front()); + events_.pop_front(); + dispatcher(ev); } } @@ -508,9 +525,11 @@ bool TcpServer::Send(int conn_id, const char *data, size_t len) { return conns_[static_cast(conn_id)]->Send(data, len); } -bool TcpServer::CloseConnection(int conn_id) { - if (conn_id < 0 || conn_id >= static_cast(conns_.size()) || !conns_[static_cast(conn_id)]) return false; - conns_[static_cast(conn_id)]->Close(true); +bool TcpServer::CloseConnection(int conn_id, bool notify) { + if (conn_id < 0 || conn_id >= static_cast(conns_.size())) return false; + auto conn = std::move(conns_[static_cast(conn_id)]); + if (!conn || !conn->IsOpen()) return false; + conn->Close(notify); return true; } @@ -540,7 +559,14 @@ void TcpClient::Connect() { } if (ssl_ctx_) { SSL *ssl = bufferevent_openssl_get_ssl(bev); - tls::SetSniHostname(ssl, tls::HostnameWithoutPort(config_.ip)); + const std::string peer_host = !config_.ws_host.empty() ? tls::HostnameWithoutPort(config_.ws_host) : tls::HostnameWithoutPort(config_.ip); + if (!tls::ConfigurePeerVerification(ssl, peer_host, config_.tls_verify)) { + connecting_ = false; + bufferevent_free(bev); + conn_.reset(); + EmitEvent({EventKind::Close, 0, {}}); + return; + } } conn_->Attach(bev); sockaddr_in addr{}; @@ -557,6 +583,7 @@ void TcpClient::Disconnect() { conn_->Close(false); conn_.reset(); } + events_.clear(); } void TcpClient::EmitEvent(ConnEvent ev) { @@ -567,11 +594,19 @@ void TcpClient::EmitEvent(ConnEvent ev) { void TcpClient::DrainEventsWith(const std::function &dispatcher) { io_.Poll(); - std::vector evs; - evs.swap(events_); + struct CleanupGuard { + std::shared_ptr &conn; + ~CleanupGuard() { + if (conn && !conn->IsOpen()) conn.reset(); + } + } cleanup{conn_}; native::IoContext::DispatchScope scope(io_); - for (const auto &ev: evs) dispatcher(ev); - if (conn_ && !conn_->IsOpen()) conn_.reset(); + const size_t n = events_.size(); + for (size_t i = 0; i < n && !events_.empty(); ++i) { + ConnEvent ev = std::move(events_.front()); + events_.pop_front(); + dispatcher(ev); + } } bool TcpClient::Send(const char *data, size_t len) { @@ -591,8 +626,13 @@ UdpSocket::~UdpSocket() { } bool UdpSocket::Start() { +#if defined(SOCK_CLOEXEC) && !defined(_WIN32) + fd_ = static_cast(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0)); +#else fd_ = static_cast(socket(AF_INET, SOCK_DGRAM, 0)); +#endif if (fd_ == INVALID_SOCKET_VAL) return false; + evutil_make_socket_closeonexec(fd_); evutil_make_socket_nonblocking(fd_); int opt = 1; setsockopt(fd_, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast(&opt), sizeof(opt)); @@ -631,6 +671,7 @@ void UdpSocket::Stop() { CloseSocket(fd_); fd_ = INVALID_SOCKET_VAL; } + events_.clear(); } void UdpSocket::OnRecv() { @@ -657,10 +698,13 @@ void UdpSocket::EmitEvent(ConnEvent ev) { void UdpSocket::DrainEventsWith(const std::function &dispatcher) { io_.Poll(); - std::vector evs; - evs.swap(events_); native::IoContext::DispatchScope scope(io_); - for (const auto &ev: evs) dispatcher(ev); + const size_t n = events_.size(); + for (size_t i = 0; i < n && !events_.empty(); ++i) { + ConnEvent ev = std::move(events_.front()); + events_.pop_front(); + dispatcher(ev); + } } bool UdpSocket::Send(const char *data, size_t len) { diff --git a/src/native/net/net_event.h b/src/native/net/net_event.h index 0aee7395..ca1c11fb 100644 --- a/src/native/net/net_event.h +++ b/src/native/net/net_event.h @@ -11,6 +11,7 @@ struct evconnlistener; #include +#include #include #include #include @@ -49,7 +50,7 @@ class TcpServer { void Stop(); void DrainEventsWith(const std::function &dispatcher); bool Send(int conn_id, const char *data, size_t len); - bool CloseConnection(int conn_id); + bool CloseConnection(int conn_id, bool notify = true); [[nodiscard]] bool Running() const { return listener_ != nullptr; @@ -64,7 +65,7 @@ class TcpServer { struct evconnlistener *listener_ = nullptr; SSL_CTX *ssl_ctx_ = nullptr; std::vector> conns_; - std::vector events_; + std::deque events_; native::LifeToken life_; }; @@ -88,7 +89,7 @@ class TcpClient { std::shared_ptr conn_; SSL_CTX *ssl_ctx_ = nullptr; bool connecting_ = false; - std::vector events_; + std::deque events_; native::LifeToken life_; }; @@ -127,7 +128,7 @@ class UdpSocket { bool open_ = false; uint16_t bound_port_ = 0; std::vector recv_buf_; - std::vector events_; + std::deque events_; native::LifeToken life_; }; diff --git a/src/native/object/native_object.cpp b/src/native/object/native_object.cpp index 9539470e..a95dd0fe 100644 --- a/src/native/object/native_object.cpp +++ b/src/native/object/native_object.cpp @@ -82,10 +82,12 @@ CVar NativeFieldToCVar(const NativeField &field, State *s) { r.data_.b = field.b; break; case NativeField::Kind::String: - // 返回指向 C++ 堆 VarString 缓存的指针; - // fakelua 不会释放它(arena 仅管理自己的分配),安全。 - r.type_ = static_cast(VarType::String); - r.data_.s = field.GetVarString(); + if (s != nullptr) { + r = inter::NativeToFakeluaStringView(s, field.s); + } else { + r.type_ = static_cast(VarType::String); + r.data_.s = field.GetVarString(); + } break; case NativeField::Kind::Object: if (field.obj != nullptr && s != nullptr) { @@ -95,7 +97,7 @@ CVar NativeFieldToCVar(const NativeField &field, State *s) { } break; case NativeField::Kind::Table: - if (field.t != nullptr) { + if (field.t != nullptr && (field.table_epoch == 0 || (s != nullptr && s->ArenaEpoch() == field.table_epoch))) { r.type_ = static_cast(VarType::Table); r.data_.t = field.t; } else { @@ -106,7 +108,7 @@ CVar NativeFieldToCVar(const NativeField &field, State *s) { return r; } -NativeField CVarToNativeField(CVar v) { +NativeField CVarToNativeField(CVar v, State *s) { NativeField f; const int t = v.type_; @@ -136,10 +138,10 @@ NativeField CVarToNativeField(CVar v) { f.kind = NativeField::Kind::Object; f.obj = nested; } else if (v.data_.t) { - // 指针跟 Lua 表同一生命周期:跨 Call() Reset 后失效。存在 C++ 堆上的 - // NativeObject 不能深拷整个表,所以只保留指针,调用方需在同一帧内使用。 f.kind = NativeField::Kind::Table; f.t = v.data_.t; + // CONST_FLAG (0x1) 表存在 const_heap 跨帧持久;其余临时表绑定当前帧 epoch,Reset 后自动失效返回 nil。 + f.table_epoch = (v.flag_ & 0x1) ? 0 : (s ? s->ArenaEpoch() : 1); } } // Multi / Closure 类型不做转换,保持 Nil @@ -169,6 +171,13 @@ NativeObject *NativeObjectManager::Create(int64_t group_id, const std::string &t return it->second; } auto *obj = NativeObject::Create(group_id, type_name, id); + obj->impl_->on_rebind_id = [this, obj](int64_t old_id, int64_t new_id) { + auto old_key = std::make_pair(obj->GetTypeName(), old_id); + if (auto oit = objects_.find(old_key); oit != objects_.end() && oit->second == obj) { + objects_.erase(oit); + } + objects_[std::make_pair(obj->GetTypeName(), new_id)] = obj; + }; objects_[key] = obj; group_objects_[group_id].push_back(obj); return obj; @@ -221,9 +230,18 @@ NativeObject *NativeObjectManager::GlobalCreate(const std::string &key, const st } if (id == 0) { id = --next_auto_obj_id_; + } else if (auto existing = objects_.find(std::make_pair(type_name, id)); existing != objects_.end()) { + return existing->second; } // 全局对象 group_id = 0,不加入 group_objects_ 索引 auto *obj = NativeObject::Create(0, type_name, id); + obj->impl_->on_rebind_id = [this, obj](int64_t old_id, int64_t new_id) { + auto old_key = std::make_pair(obj->GetTypeName(), old_id); + if (auto oit = objects_.find(old_key); oit != objects_.end() && oit->second == obj) { + objects_.erase(oit); + } + objects_[std::make_pair(obj->GetTypeName(), new_id)] = obj; + }; objects_[std::make_pair(type_name, id)] = obj; global_objects_[key] = obj; return obj; @@ -241,7 +259,9 @@ bool NativeObjectManager::GlobalDestroy(const std::string &key) { } NativeObject *obj = it->second; auto obj_key = std::make_pair(obj->GetTypeName(), obj->GetId()); - objects_.erase(obj_key); + if (objects_.erase(obj_key) == 0) { + std::erase_if(objects_, [obj](const auto &kv) { return kv.second == obj; }); + } global_objects_.erase(it); NativeObject::Destroy(obj); zombies_.push_back(obj); @@ -261,7 +281,9 @@ size_t NativeObjectManager::DestroyGroup(int64_t group_id) { for (auto *obj: to_destroy) { if (obj) { auto key = std::make_pair(obj->GetTypeName(), obj->GetId()); - objects_.erase(key); + if (objects_.erase(key) == 0) { + std::erase_if(objects_, [obj](const auto &kv) { return kv.second == obj; }); + } NativeObject::Destroy(obj); zombies_.push_back(obj); count++; @@ -275,65 +297,73 @@ void NativeObjectManager::Clear() { // (which invoke io::OnStateDeleted) no longer reference freed NativeObjects. io::OnNativeObjectManagerCleared(owner_); - // objects_ 中的对象仍然"存活"(impl_ 非空),必须先调 Destroy 触发 finalizer 再 delete。 - // zombies_ 中的对象已经由 DestroySingle/GlobalDestroy/DestroyGroup 调用过 Destroy(), - // impl_ 已被置 nullptr,只剩一个空壳,只需 delete 释放堆内存即可。 - // 两个集合保证互不重叠(erase 之后才 push_back),因此不存在 double-free。 + std::unordered_set deleted; for (auto &[k, v]: objects_) { - NativeObject::Destroy(v); - delete v; + if (v && deleted.insert(v).second) { + NativeObject::Destroy(v); + delete v; + } } objects_.clear(); group_objects_.clear(); global_objects_.clear(); for (auto *z: zombies_) { - // impl_ 已为 nullptr(Destroy 已清空),直接释放对象本身 - delete z; + if (z && deleted.insert(z).second) { + delete z; + } } zombies_.clear(); } // NativeMethodBridge — 宿主 C++ 成员回调的方法派发桥接 +static CVar AllocSpecKeyCVar(State *s, std::string_view key); + CVar NativeMethodBridge(VarClosure *cl, CVar vararg_cvar) { - if (!cl || cl->upvalue_count < 3) { + if (!cl || cl->upvalue_count < 3 || !cl->upvalues[1]) { ThrowFakeluaException("NativeMethodBridge failed: invalid VarClosure metadata"); } - - auto *obj = reinterpret_cast(cl->upvalues[0]->data_.i); auto *state = reinterpret_cast(cl->upvalues[1]->data_.i); - auto *method_ptr = reinterpret_cast(cl->upvalues[2]->data_.i); - - if (!obj || !obj->impl_) { - ThrowFakeluaException("native object is destroyed"); - } - if (!method_ptr || !(*method_ptr)) { - ThrowFakeluaException("NativeMethodBridge failed: obj or method is null"); + if (!state) { + ThrowFakeluaException("NativeMethodBridge failed: state is null"); } - CVar *all_args = nullptr; - int total_arg_count = 0; - if (vararg_cvar.type_ == static_cast(VarType::Multi) && vararg_cvar.data_.m) { - total_arg_count = static_cast(vararg_cvar.data_.m->GetCount()); - all_args = vararg_cvar.data_.m->GetVars(); - } + return GuardJitEntry(state, [&]() -> CVar { + auto *obj = reinterpret_cast(cl->upvalues[0]->data_.i); + if (!obj || !obj->impl_) { + ThrowFakeluaException("native object is destroyed"); + } + const std::string_view method_name = KeyToStringView(*cl->upvalues[2]); + const auto mit = obj->impl_->methods.find(method_name); + if (mit == obj->impl_->methods.end() || !mit->second) { + ThrowFakeluaException("NativeMethodBridge failed: obj or method is null"); + } + const NativeMethod method_copy = mit->second; - // 自动判断 self 传递 (冒号 player:method(...) / 点号 player.method(player, ...) vs fn(...)) - NativeObject *passed_self = (total_arg_count > 0) ? NativeObject::Unwrap(all_args[0]) : nullptr; - NativeObject *actual_self = (passed_self != nullptr) ? passed_self : obj; + CVar *all_args = nullptr; + int total_arg_count = 0; + if (vararg_cvar.type_ == static_cast(VarType::Multi) && vararg_cvar.data_.m) { + total_arg_count = static_cast(vararg_cvar.data_.m->GetCount()); + all_args = vararg_cvar.data_.m->GetVars(); + } - CVar *call_args = nullptr; - int call_n = 0; + // 自动判断 self 传递 (冒号 player:method(...) / 点号 player.method(player, ...) vs fn(...)) + NativeObject *passed_self = (total_arg_count > 0) ? NativeObject::Unwrap(all_args[0]) : nullptr; + NativeObject *actual_self = (passed_self != nullptr) ? passed_self : obj; - if (passed_self != nullptr) { - call_args = all_args + 1; - call_n = total_arg_count - 1; - } else { - call_args = all_args; - call_n = total_arg_count; - } + CVar *call_args = nullptr; + int call_n = 0; - return GuardJitEntry(state, [&]() -> CVar { return (*method_ptr)(actual_self, state, call_args, call_n); }); + if (passed_self != nullptr) { + call_args = all_args + 1; + call_n = total_arg_count - 1; + } else { + call_args = all_args; + call_n = total_arg_count; + } + + return method_copy(actual_self, state, call_args, call_n); + }); } // spec_get / spec_set 实现 @@ -400,6 +430,7 @@ void RefreshSpecKeys(VarTable *tbl, const NativeObject *obj, State *s) { auto *spec = static_cast(tbl->spec); const auto &kv = obj->impl_->kv; const size_t n = kv.size(); + const uint64_t cur_epoch = (s && s->InterpConstAlloc()) ? 0 : (s ? s->ArenaEpoch() : 0); if (n == 0) { tbl->spec_keys = nullptr; @@ -408,6 +439,7 @@ void RefreshSpecKeys(VarTable *tbl, const NativeObject *obj, State *s) { if (spec) { spec->spec_cap = 0; spec->snapshot_ready = true; + spec->snapshot_epoch = cur_epoch; } return; } @@ -422,17 +454,30 @@ void RefreshSpecKeys(VarTable *tbl, const NativeObject *obj, State *s) { tbl->spec_vals[i] = NativeFieldToCVar(v, s); ++i; } - if (spec) spec->snapshot_ready = true; + if (spec) { + spec->snapshot_ready = true; + spec->snapshot_epoch = cur_epoch; + } } void EnsureNativeSpecSnapshotSlow(VarTable *tbl) { if (!tbl || !tbl->spec || tbl->spec_get != reinterpret_cast(NativeSpecGet)) return; auto *spec = static_cast(tbl->spec); - if (spec->snapshot_ready) return; - NativeObject *obj = spec->obj; State *s = spec->state; + if (spec->snapshot_ready) { + if (spec->snapshot_epoch == 0 || (s && spec->snapshot_epoch == s->ArenaEpoch())) { + return; + } + tbl->spec_keys = nullptr; + tbl->spec_vals = nullptr; + tbl->spec_count = 0; + spec->spec_cap = 0; + spec->snapshot_ready = false; + } + NativeObject *obj = spec->obj; if (!obj || !obj->Alive() || !s) { spec->snapshot_ready = true; + spec->snapshot_epoch = s ? s->ArenaEpoch() : 0; return; } RefreshSpecKeys(tbl, obj, s); @@ -484,8 +529,7 @@ CVar NativeSpecGet(VarTable *tbl, CVar k, bool *finish) { uv1->data_.i = reinterpret_cast(s); auto *uv2 = static_cast(alloc.Alloc(sizeof(CVar))); - uv2->type_ = static_cast(VarType::Int); - uv2->data_.i = reinterpret_cast(&mit->second); + *uv2 = AllocSpecKeyCVar(s, key); auto *cl = static_cast(alloc.Alloc(sizeof(VarClosure) + 3 * sizeof(CVar *))); cl->func_ptr = reinterpret_cast(NativeMethodBridge); @@ -526,6 +570,18 @@ void NativeSpecSet(VarTable *tbl, CVar k, CVar v, bool *finish) { *finish = true; State *s = spec->state; + if (spec->snapshot_ready) { + const bool epoch_stale = (spec->snapshot_epoch != 0 && (!s || spec->snapshot_epoch != s->ArenaEpoch())); + const bool const_snapshot_at_runtime = (spec->snapshot_epoch == 0 && (!s || !s->InterpConstAlloc())); + if (epoch_stale || const_snapshot_at_runtime) { + tbl->spec_keys = nullptr; + tbl->spec_vals = nullptr; + tbl->spec_count = 0; + spec->spec_cap = 0; + spec->snapshot_ready = false; + } + } + // 快照尚未建立:只写 kv,保持惰性;首次 pairs/next/GET_TABLE_ENTRY 再 RefreshSpecKeys。 if (!spec->snapshot_ready) { if (v.type_ == static_cast(VarType::Nil)) { @@ -533,7 +589,7 @@ void NativeSpecSet(VarTable *tbl, CVar k, CVar v, bool *finish) { obj->impl_->kv.erase(it); } } else { - auto new_field = CVarToNativeField(v); + auto new_field = CVarToNativeField(v, s); if (auto it = obj->impl_->kv.find(key); it != obj->impl_->kv.end()) { it->second = std::move(new_field); } else { @@ -565,7 +621,7 @@ void NativeSpecSet(VarTable *tbl, CVar k, CVar v, bool *finish) { return; } - auto new_field = CVarToNativeField(v); + auto new_field = CVarToNativeField(v, s); auto it = obj->impl_->kv.find(key); if (it != obj->impl_->kv.end()) { it->second = std::move(new_field); @@ -885,7 +941,12 @@ int64_t NativeObject::GetId() const { void NativeObject::SetId(int64_t id) { if (!impl_) return; + const int64_t old_id = impl_->id; + if (old_id == id) return; impl_->id = id; + if (impl_->on_rebind_id) { + impl_->on_rebind_id(old_id, id); + } TouchVersion(); } diff --git a/src/native/object/native_object.h b/src/native/object/native_object.h index 2aa9c3c1..47cfb61c 100644 --- a/src/native/object/native_object.h +++ b/src/native/object/native_object.h @@ -33,6 +33,7 @@ struct NativeField { std::string s; // Kind::String 时的原始字符串 NativeObject *obj = nullptr;// Kind::Object 时的嵌套对象(不拥有) VarTable *t = nullptr; // Kind::Table 时的 Lua 表指针 + uint64_t table_epoch = 0; // 0 表示 const_heap 持久表;非 0 仅在 s->ArenaEpoch() 相同时有效 // 惰性构建 VarString 缓存(存在 C++ 堆,供 spec_get 返回 VAR_STRING CVar) // 当 s 内容变化时重建;由于 fakelua 是单线程的,此处不加锁。 @@ -67,6 +68,7 @@ struct NativeObjectSpec { // 首次遍历时再 EnsureNativeSpecSnapshot。snapshot_ready 为真后,NativeSpecSet // 走增量维护;为假时写入只改 kv,快照仍保持惰性。 bool snapshot_ready = false; + uint64_t snapshot_epoch = 0; }; // NativeObject: 完整实现(pImpl 的 Impl 部分) @@ -99,6 +101,7 @@ struct NativeObject::Impl { std::unordered_map methods; // 可选销毁回调:NativeObject 被 Destroy 时调用(无论是否经 close 方法),用于释放关联资源 std::function finalizer; + std::function on_rebind_id; // ---- 对象级版本号的内部簿记(不进入存档,不改变既有数据格式)---- // 版本号只是「本对象可能变过」的信号,不做精确引用账本: @@ -149,7 +152,7 @@ inline std::string_view KeyToStringView(CVar k) { CVar NativeFieldToCVar(const NativeField &field, State *s); // CVar → NativeField(将 fakelua 值转为 C++ 持久值) -NativeField CVarToNativeField(CVar v); +NativeField CVarToNativeField(CVar v, State *s = nullptr); }// namespace fakelua diff --git a/src/native/os/native_os.cpp b/src/native/os/native_os.cpp index ea0386af..127581b3 100644 --- a/src/native/os/native_os.cpp +++ b/src/native/os/native_os.cpp @@ -24,7 +24,10 @@ #if defined(_WIN32) #include #else +#include +#include #include +#include #endif namespace fakelua::os { @@ -425,22 +428,37 @@ void RegisterOsLibraryApi(State *s) { return inter::NativeToFakeluaInt(state, static_cast(t)); }); - // os.tmpname() — temp_directory_path + unique_path,并创建空文件(与 mkstemp/GetTempFileName 一致) + // os.tmpname() — POSIX 用 mkstemp 创建 0600 独占文件,Windows 用 CREATE_NEW RegisterNativeFunction(s, "os.tmpname", 0, false, [](State *state, CVar *args, int n) -> CVar { + (void) args; + (void) n; boost::system::error_code ec; auto dir = fs::temp_directory_path(ec); if (ec) return inter::NativeToFakeluaNil(state); +#if !defined(_WIN32) + std::string tmpl = (dir / "lua_XXXXXX").string(); + std::vector buf(tmpl.begin(), tmpl.end()); + buf.push_back('\0'); +#if defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) + int fd = ::mkostemp(buf.data(), O_CLOEXEC); +#else + int fd = ::mkstemp(buf.data()); +#endif + if (fd < 0) return inter::NativeToFakeluaNil(state); + ::fchmod(fd, 0600); + ::close(fd); + return inter::NativeToFakeluaStringView(state, std::string_view(buf.data())); +#else for (int i = 0; i < 32; ++i) { auto p = dir / fs::unique_path("lua_%%%%-%%%%-%%%%-%%%%", ec); if (ec) return inter::NativeToFakeluaNil(state); - boost::system::error_code exists_ec; - if (fs::exists(p, exists_ec)) continue; - utf8_io::ofstream out(p.string(), std::ios::out | std::ios::trunc); - if (!out) continue; - out.close(); + HANDLE h = ::CreateFileW(p.wstring().c_str(), GENERIC_WRITE, 0, nullptr, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr); + if (h == INVALID_HANDLE_VALUE) continue; + ::CloseHandle(h); return inter::NativeToFakeluaStringView(state, p.string()); } return inter::NativeToFakeluaNil(state); +#endif }); // --- Boost.Filesystem 扩展(Lua 5.4 os 没有这些)--- diff --git a/src/native/process/native_process.cpp b/src/native/process/native_process.cpp index 7ebc34f6..117aa944 100644 --- a/src/native/process/native_process.cpp +++ b/src/native/process/native_process.cpp @@ -21,10 +21,14 @@ #if defined(_WIN32) #include #else +#include #include #include #include #include +#if defined(__linux__) +#include +#endif #include #include #include @@ -37,9 +41,11 @@ using table::TableHelper; static constexpr size_t kMaxOutput = 8 * 1024 * 1024; +#if defined(_WIN32) static boost::filesystem::path MakeProcTempPath() { return boost::filesystem::temp_directory_path() / boost::filesystem::unique_path("fakelua-proc-%%%%-%%%%.tmp"); } +#endif static std::string ReadCappedFile(const boost::filesystem::path &p) { std::string out; @@ -163,6 +169,69 @@ static std::string FindExecutable(const std::string &name) { return name; } +#if !defined(_WIN32) +static int CreateSecureTempFile(boost::filesystem::path &out_path) { + boost::system::error_code ec; + boost::filesystem::path dir = boost::filesystem::temp_directory_path(ec); + if (ec || dir.empty()) dir = "/tmp"; + std::string tmpl = (dir / "fakelua-proc-XXXXXX").string(); + std::vector buf(tmpl.begin(), tmpl.end()); + buf.push_back('\0'); +#if defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) + int fd = ::mkostemp(buf.data(), O_CLOEXEC); +#else + int fd = ::mkstemp(buf.data()); + if (fd >= 0) { + int flags = ::fcntl(fd, F_GETFD); + if (flags >= 0) ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC); + } +#endif + if (fd < 0) { + ThrowFakeluaException(std::format("process.run: mkstemp failed: {}", std::strerror(errno))); + } + ::fchmod(fd, 0600); + out_path = boost::filesystem::path(buf.data()); + return fd; +} + +static void CloseExtraFdsFrom(int first_fd) { +#if defined(__linux__) && defined(SYS_close_range) + if (::syscall(SYS_close_range, static_cast(first_fd), ~0U, 0) == 0) { + return; + } +#endif +#if defined(__APPLE__) + const char *fd_dir_path = "/dev/fd"; +#else + const char *fd_dir_path = "/proc/self/fd"; +#endif + if (DIR *dir = ::opendir(fd_dir_path)) { + const int dfd = ::dirfd(dir); + std::vector to_close; + while (struct dirent *ent = ::readdir(dir)) { + if (ent->d_name[0] < '0' || ent->d_name[0] > '9') continue; + char *end = nullptr; + long val = std::strtol(ent->d_name, &end, 10); + if (!end || *end != '\0') continue; + if (val >= first_fd && val <= std::numeric_limits::max() && static_cast(val) != dfd) { + to_close.push_back(static_cast(val)); + } + } + ::closedir(dir); + for (int fd: to_close) { + ::close(fd); + } + return; + } + long max_fd = ::sysconf(_SC_OPEN_MAX); + if (max_fd < 0) max_fd = 1024; + if (max_fd > 65536) max_fd = 65536; + for (int fd = first_fd; fd < static_cast(max_fd); ++fd) { + ::close(fd); + } +} +#endif + #if defined(_WIN32) struct FileStdio { HANDLE hin = INVALID_HANDLE_VALUE; @@ -263,21 +332,32 @@ static CVar ProcessRun(State *s, CVar *args, int n) { int exit_code = -1; bool timed_out = false; - const auto out_path = MakeProcTempPath(); - const auto err_path = MakeProcTempPath(); - boost::filesystem::path in_path; + struct TempFilesGuard { + boost::filesystem::path out_path; + boost::filesystem::path err_path; + boost::filesystem::path in_path; + ~TempFilesGuard() { + boost::system::error_code ec; + if (!out_path.empty()) boost::filesystem::remove(out_path, ec); + if (!err_path.empty()) boost::filesystem::remove(err_path, ec); + if (!in_path.empty()) boost::filesystem::remove(in_path, ec); + } + } temp_files; + +#if defined(_WIN32) + temp_files.out_path = MakeProcTempPath(); + temp_files.err_path = MakeProcTempPath(); { - boost::nowide::ofstream{out_path.string(), std::ios::binary}; - boost::nowide::ofstream{err_path.string(), std::ios::binary}; + boost::nowide::ofstream{temp_files.out_path.string(), std::ios::binary}; + boost::nowide::ofstream{temp_files.err_path.string(), std::ios::binary}; } if (!stdin_data.empty()) { - in_path = MakeProcTempPath(); - boost::nowide::ofstream in(in_path.string(), std::ios::binary); + temp_files.in_path = MakeProcTempPath(); + boost::nowide::ofstream in(temp_files.in_path.string(), std::ios::binary); in.write(stdin_data.data(), static_cast(stdin_data.size())); in.close(); } -#if defined(_WIN32) auto QuoteWinArg = [](const std::wstring &arg) -> std::wstring { std::wstring out = L"\""; int backslashes = 0; @@ -300,9 +380,9 @@ static CVar ProcessRun(State *s, CVar *args, int n) { }; FileStdio stdio; - stdio.hin = FileStdio::Open(in_path.empty() ? L"NUL" : in_path.wstring().c_str(), true); - stdio.hout = FileStdio::Open(out_path.wstring().c_str(), false); - stdio.herr = FileStdio::Open(err_path.wstring().c_str(), false); + stdio.hin = FileStdio::Open(temp_files.in_path.empty() ? L"NUL" : temp_files.in_path.wstring().c_str(), true); + stdio.hout = FileStdio::Open(temp_files.out_path.wstring().c_str(), false); + stdio.herr = FileStdio::Open(temp_files.err_path.wstring().c_str(), false); std::wstring cmd = QuoteWinArg(boost::nowide::widen(exe)); for (size_t i = 1; i < argv.size(); ++i) { @@ -358,86 +438,149 @@ static CVar ProcessRun(State *s, CVar *args, int n) { ::CloseHandle(pi.hProcess); ::CloseHandle(pi.hThread); #else - int in_fd = ::open(in_path.empty() ? "/dev/null" : in_path.string().c_str(), O_RDONLY); - int out_fd = ::open(out_path.string().c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0600); - int err_fd = ::open(err_path.string().c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0600); - if (in_fd < 0 || out_fd < 0 || err_fd < 0) { - if (in_fd >= 0) ::close(in_fd); - if (out_fd >= 0) ::close(out_fd); - if (err_fd >= 0) ::close(err_fd); + struct PosixFdGuard { + int in_fd = -1; + int out_fd = -1; + int err_fd = -1; + void Close() { + if (in_fd >= 0) { + ::close(in_fd); + in_fd = -1; + } + if (out_fd >= 0) { + ::close(out_fd); + out_fd = -1; + } + if (err_fd >= 0) { + ::close(err_fd); + err_fd = -1; + } + } + ~PosixFdGuard() { + Close(); + } + } stdio_fds; + + stdio_fds.out_fd = CreateSecureTempFile(temp_files.out_path); + stdio_fds.err_fd = CreateSecureTempFile(temp_files.err_path); + if (stdin_data.empty()) { +#if defined(O_CLOEXEC) + stdio_fds.in_fd = ::open("/dev/null", O_RDONLY | O_CLOEXEC); +#else + stdio_fds.in_fd = ::open("/dev/null", O_RDONLY); +#endif + } else { + int wfd = CreateSecureTempFile(temp_files.in_path); + size_t written = 0; + while (written < stdin_data.size()) { + ssize_t nw = ::write(wfd, stdin_data.data() + written, stdin_data.size() - written); + if (nw < 0) { + if (errno == EINTR) continue; + ::close(wfd); + ThrowFakeluaException("process.run: failed to write stdin file"); + } + written += static_cast(nw); + } + ::close(wfd); +#if defined(O_CLOEXEC) + stdio_fds.in_fd = ::open(temp_files.in_path.string().c_str(), O_RDONLY | O_CLOEXEC); +#else + stdio_fds.in_fd = ::open(temp_files.in_path.string().c_str(), O_RDONLY); +#endif + } + if (stdio_fds.in_fd < 0 || stdio_fds.out_fd < 0 || stdio_fds.err_fd < 0) { ThrowFakeluaException("process.run: failed to open stdio files"); } + + std::vector cargv; + cargv.reserve(argv.size() + 1); + for (auto &a: argv) cargv.push_back(a.data()); + cargv.push_back(nullptr); + auto env_list = CurrentEnviron(); + ApplyEnvOverrides(env_list, env_overrides); + std::vector cenv; + cenv.reserve(env_list.size() + 1); + for (auto &e: env_list) cenv.push_back(e.data()); + cenv.push_back(nullptr); + pid_t pid = ::fork(); if (pid < 0) { - ::close(in_fd); - ::close(out_fd); - ::close(err_fd); ThrowFakeluaException(std::format("process.run: failed to spawn '{}': {}", argv[0], strerror(errno))); } if (pid == 0) { if (!cwd.empty() && ::chdir(cwd.c_str()) != 0) _exit(127); - dup2(in_fd, STDIN_FILENO); - dup2(out_fd, STDOUT_FILENO); - dup2(err_fd, STDERR_FILENO); - if (in_fd > 2) ::close(in_fd); - if (out_fd > 2) ::close(out_fd); - if (err_fd > 2) ::close(err_fd); - std::vector cargv; - for (auto &a: argv) cargv.push_back(a.data()); - cargv.push_back(nullptr); - auto env_list = CurrentEnviron(); - ApplyEnvOverrides(env_list, env_overrides); - std::vector cenv; - for (auto &e: env_list) cenv.push_back(e.data()); - cenv.push_back(nullptr); + int in_fd = stdio_fds.in_fd; + int out_fd = stdio_fds.out_fd; + int err_fd = stdio_fds.err_fd; + if (in_fd < 3) { + in_fd = ::fcntl(in_fd, F_DUPFD, 3); + if (in_fd < 0) _exit(127); + } + if (out_fd < 3) { + out_fd = ::fcntl(out_fd, F_DUPFD, 3); + if (out_fd < 0) _exit(127); + } + if (err_fd < 3) { + err_fd = ::fcntl(err_fd, F_DUPFD, 3); + if (err_fd < 0) _exit(127); + } + if (::dup2(in_fd, STDIN_FILENO) < 0 || ::dup2(out_fd, STDOUT_FILENO) < 0 || ::dup2(err_fd, STDERR_FILENO) < 0) { + _exit(127); + } + CloseExtraFdsFrom(3); execve(exe.c_str(), cargv.data(), cenv.data()); _exit(127); } - ::close(in_fd); - ::close(out_fd); - ::close(err_fd); - auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout_ms > 0 ? timeout_ms : 0); - for (;;) { + stdio_fds.Close(); + + if (timeout_ms <= 0) { int status = 0; - pid_t r = ::waitpid(pid, &status, WNOHANG); + pid_t r = -1; + do { + r = ::waitpid(pid, &status, 0); + } while (r < 0 && errno == EINTR); if (r == pid) { if (WIFEXITED(status)) exit_code = WEXITSTATUS(status); else if (WIFSIGNALED(status)) exit_code = 128 + WTERMSIG(status); else exit_code = -1; - break; - } - if (r < 0 && errno != EINTR) { + } else { exit_code = -1; - break; - } - if (timeout_ms > 0 && std::chrono::steady_clock::now() >= deadline) { - timed_out = true; - ::kill(pid, SIGKILL); - ::waitpid(pid, &status, 0); - exit_code = 9; - break; } - std::this_thread::sleep_for(std::chrono::milliseconds(10)); - if (timeout_ms == 0) { - r = ::waitpid(pid, &status, 0); + } else { + auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout_ms); + for (;;) { + int status = 0; + pid_t r = ::waitpid(pid, &status, WNOHANG); if (r == pid) { if (WIFEXITED(status)) exit_code = WEXITSTATUS(status); else if (WIFSIGNALED(status)) exit_code = 128 + WTERMSIG(status); + else + exit_code = -1; + break; + } + if (r < 0 && errno != EINTR) { + exit_code = -1; + break; + } + if (std::chrono::steady_clock::now() >= deadline) { + timed_out = true; + ::kill(pid, SIGKILL); + do { + r = ::waitpid(pid, &status, 0); + } while (r < 0 && errno == EINTR); + exit_code = 9; + break; } - break; + std::this_thread::sleep_for(std::chrono::milliseconds(10)); } } #endif - stdout_s = ReadCappedFile(out_path); - stderr_s = ReadCappedFile(err_path); - boost::system::error_code rec; - boost::filesystem::remove(out_path, rec); - boost::filesystem::remove(err_path, rec); - if (!in_path.empty()) boost::filesystem::remove(in_path, rec); + stdout_s = ReadCappedFile(temp_files.out_path); + stderr_s = ReadCappedFile(temp_files.err_path); if (timed_out && exit_code < 0) exit_code = 9; diff --git a/src/native/protobuf/native_protobuf.cpp b/src/native/protobuf/native_protobuf.cpp index e1cb85f9..e7057bd9 100644 --- a/src/native/protobuf/native_protobuf.cpp +++ b/src/native/protobuf/native_protobuf.cpp @@ -32,14 +32,21 @@ static std::string CVarToString(const CVar &v) { return {}; } +static int EffectiveArgCount(CVar *args, int n) { + if (n > 0 && args && args[0].type_ == static_cast(VarType::Multi)) { + return inter::GetMultiCVarCount(args[0]); + } + return n; +} + // protobuf.load(proto_text) // 解析 .proto 文本,注册所有 message/enum。成功返回 "ok",失败返回错误信息字符串。 static CVar PbLoad(State *s, CVar *args, int n) { - if (n < 1) { + if (EffectiveArgCount(args, n) < 1) { return inter::NativeToFakeluaString(s, "protobuf.load: missing argument"); } - std::string text = CVarToString(args[0]); + std::string text = CVarToString(inter::GetNativeArg(s, args, n, 0)); std::string err = ParseProto(s, text); if (!err.empty()) { LOG_ERROR(s, "protobuf", "protobuf.load failed: {}", err); @@ -51,11 +58,11 @@ static CVar PbLoad(State *s, CVar *args, int n) { // protobuf.encode(message_name, table) → binary static CVar PbEncode(State *s, CVar *args, int n) { - if (n < 2) { + if (EffectiveArgCount(args, n) < 2) { ThrowFakeluaException("protobuf.encode: requires message_name and table"); } - std::string msg_name = CVarToString(args[0]); - CVar table = args[1]; + std::string msg_name = CVarToString(inter::GetNativeArg(s, args, n, 0)); + CVar table = inter::GetNativeArg(s, args, n, 1); std::string bin = EncodeMessage(s, msg_name, table); LOG_DEBUG(s, "protobuf", "protobuf.encode: msg={} bytes={}", msg_name, bin.size()); @@ -64,11 +71,11 @@ static CVar PbEncode(State *s, CVar *args, int n) { // protobuf.decode(message_name, binary) → table static CVar PbDecode(State *s, CVar *args, int n) { - if (n < 2) { + if (EffectiveArgCount(args, n) < 2) { ThrowFakeluaException("protobuf.decode: requires message_name and binary"); } - std::string msg_name = CVarToString(args[0]); - std::string data = CVarToString(args[1]); + std::string msg_name = CVarToString(inter::GetNativeArg(s, args, n, 0)); + std::string data = CVarToString(inter::GetNativeArg(s, args, n, 1)); LOG_DEBUG(s, "protobuf", "protobuf.decode: msg={} bytes={}", msg_name, data.size()); return DecodeMessage(s, msg_name, data); @@ -76,6 +83,8 @@ static CVar PbDecode(State *s, CVar *args, int n) { // protobuf.types() → 已注册消息名列表 static CVar PbTypes(State *s, CVar *args, int n) { + (void) args; + (void) n; auto names = GetProtobufState(s).MessageNames(); CVar tbl = TableHelper::CreateTable(s); for (size_t i = 0; i < names.size(); ++i) { @@ -86,10 +95,10 @@ static CVar PbTypes(State *s, CVar *args, int n) { // protobuf.fields(message_name) → 字段信息表 static CVar PbFields(State *s, CVar *args, int n) { - if (n < 1) { + if (EffectiveArgCount(args, n) < 1) { ThrowFakeluaException("protobuf.fields: requires message_name"); } - std::string msg_name = CVarToString(args[0]); + std::string msg_name = CVarToString(inter::GetNativeArg(s, args, n, 0)); const MessageDef *msg = GetProtobufState(s).FindMessage(msg_name); if (!msg) { ThrowFakeluaException(std::format("protobuf.fields: unknown message '{}'", msg_name)); diff --git a/src/native/protobuf/protobuf_parser.cpp b/src/native/protobuf/protobuf_parser.cpp index c201a7dc..9af34c75 100644 --- a/src/native/protobuf/protobuf_parser.cpp +++ b/src/native/protobuf/protobuf_parser.cpp @@ -81,11 +81,11 @@ class Lexer { return ReadString(c, start_line); } // 数字 - if (std::isdigit(c) || (c == '.' && pos_ + 1 < text_.size() && std::isdigit(text_[pos_ + 1]))) { + if (std::isdigit(static_cast(c)) || (c == '.' && pos_ + 1 < text_.size() && std::isdigit(static_cast(text_[pos_ + 1])))) { return ReadNumber(start_line); } // 标识符 / 关键字 - if (std::isalpha(c) || c == '_') { + if (std::isalpha(static_cast(c)) || c == '_') { return ReadIdent(start_line); } // 符号 @@ -174,13 +174,13 @@ class Lexer { bool is_float = false; if (text_[pos_] == '0' && pos_ + 1 < text_.size() && (text_[pos_ + 1] == 'x' || text_[pos_ + 1] == 'X')) { pos_ += 2; - while (pos_ < text_.size() && std::isxdigit(text_[pos_])) pos_++; + while (pos_ < text_.size() && std::isxdigit(static_cast(text_[pos_]))) pos_++; } else { - while (pos_ < text_.size() && std::isdigit(text_[pos_])) pos_++; + while (pos_ < text_.size() && std::isdigit(static_cast(text_[pos_]))) pos_++; if (pos_ < text_.size() && text_[pos_] == '.') { is_float = true; pos_++; - while (pos_ < text_.size() && std::isdigit(text_[pos_])) pos_++; + while (pos_ < text_.size() && std::isdigit(static_cast(text_[pos_]))) pos_++; } } return {is_float ? Token::T_FLOAT : Token::T_INT, std::string(text_, start, pos_ - start), 0, start_line}; @@ -188,7 +188,7 @@ class Lexer { Token ReadIdent(int start_line) { size_t start = pos_; - while (pos_ < text_.size() && (std::isalnum(text_[pos_]) || text_[pos_] == '_')) pos_++; + while (pos_ < text_.size() && (std::isalnum(static_cast(text_[pos_])) || text_[pos_] == '_')) pos_++; std::string word(text_, start, pos_ - start); auto &kw = Keywords(); auto it = kw.find(word); @@ -214,14 +214,31 @@ class Parser { while (current_.type != Token::T_EOF) { ParseStatement(lexer, ""); } + ResolvePendingMessages(); } private: + static constexpr int kMaxProtoNestingDepth = 64; + + struct PendingFieldRef { + size_t field_index = 0; + std::string raw_type_name; + bool is_map_val = false; + }; + + struct PendingMessage { + MessageDef def; + std::string scope; + std::vector refs; + }; + Token current_; State *s_ = nullptr;// schema 注册表所属的 State std::string filename_; std::string package_;// 当前 package std::string syntax_; // "proto2" / "proto3" + int message_depth_ = 0; + std::vector pending_messages_; void Advance(Lexer &lexer) { current_ = lexer.Next(); @@ -242,10 +259,17 @@ class Parser { } std::string ParseQualifiedName(Lexer &lexer) { - if (current_.type != Token::T_IDENT) { + std::string name; + if (current_.type == Token::T_SYMBOL && current_.value == ".") { + name = "."; + Advance(lexer); + if (current_.type != Token::T_IDENT) { + ThrowFakeluaException(std::format("proto parse error at line {}: expected type name", current_.line)); + } + } else if (current_.type != Token::T_IDENT) { ThrowFakeluaException(std::format("proto parse error at line {}: expected type name", current_.line)); } - std::string name = current_.value; + name += current_.value; Advance(lexer); while (current_.type == Token::T_SYMBOL && current_.value == ".") { Advance(lexer); @@ -373,33 +397,82 @@ class Parser { return name; } - // 将相对类型名解析为完全限定名 + // 将相对类型名解析为完全限定名(可重入:首次按已注册类型解析,Parse 结束后对整份文件做二次解析) std::string ResolveTypeName(const std::string &name, const std::string &prefix) { - // 已经是完全限定名(以 package 开头或含点) - if (!package_.empty() && name.find('.') != std::string::npos) return name; + if (name.empty()) return {}; // 以点开头 = 绝对名 - if (!name.empty() && name[0] == '.') return name.substr(1); - // 有 prefix(嵌套类型内) - if (!prefix.empty()) { - // 先在 prefix 下查找 - std::string candidate = prefix + "." + name; - if (GetProtobufState(s_).FindMessage(candidate) || GetProtobufState(s_).FindEnum(candidate)) { + if (name[0] == '.') return name.substr(1); + auto &st = GetProtobufState(s_); + // 从最内层消息作用域逐级向外查找(包含 package_) + std::string cur = prefix; + while (!cur.empty()) { + std::string candidate = cur + "." + name; + if (st.FindMessage(candidate) || st.FindEnum(candidate)) { return candidate; } + auto dot = cur.rfind('.'); + if (dot == std::string::npos) { + cur.clear(); + } else { + cur.erase(dot); + } } // 在 package 下查找 if (!package_.empty()) { std::string candidate = package_ + "." + name; - if (GetProtobufState(s_).FindMessage(candidate) || GetProtobufState(s_).FindEnum(candidate)) { + if (st.FindMessage(candidate) || st.FindEnum(candidate)) { return candidate; } } - // 无法解析,返回原名(后续可能报错) + // 已是完全限定名或全局名 + if (st.FindMessage(name) || st.FindEnum(name)) { + return name; + } + // 尚未定义(可能是跨文件前向引用):简单名称归属当前 package + if (!package_.empty() && name.find('.') == std::string::npos) { + return package_ + "." + name; + } return name; } + void ResolvePendingMessages() { + auto &st = GetProtobufState(s_); + for (auto &pm: pending_messages_) { + for (const auto &ref: pm.refs) { + if (ref.field_index >= pm.def.fields.size()) continue; + FieldDef &field = pm.def.fields[ref.field_index]; + std::string resolved = ResolveTypeName(ref.raw_type_name, pm.scope); + if (ref.is_map_val) { + field.map_value_type_name = resolved; + if (st.FindEnum(resolved)) { + field.map_value_type = TYPE_ENUM; + } + } else { + field.type_name = resolved; + if (st.FindEnum(resolved)) { + field.type = TYPE_ENUM; + } + } + } + st.RegisterMessage(std::move(pm.def)); + } + } + // Message void ParseMessage(Lexer &lexer, const std::string &prefix) { + if (message_depth_ >= kMaxProtoNestingDepth) { + ThrowFakeluaException(std::format("proto parse error at line {}: message nesting too deep", current_.line)); + } + struct DepthGuard { + int &d; + explicit DepthGuard(int &depth) : d(depth) { + ++d; + } + ~DepthGuard() { + --d; + } + } depth_guard(message_depth_); + Advance(lexer);// 跳过 'message' if (current_.type != Token::T_IDENT) { ThrowFakeluaException(std::format("proto parse error at line {}: expected message name", current_.line)); @@ -412,24 +485,26 @@ class Parser { full_name = package_ + "." + msg_name; } - MessageDef def; - def.name = full_name; + PendingMessage pm; + pm.def.name = full_name; + pm.scope = full_name; ExpectSymbol(lexer, "{"); std::string nested_prefix = full_name; while (!(current_.type == Token::T_SYMBOL && current_.value == "}")) { - ParseMessageBody(lexer, def, nested_prefix); + ParseMessageBody(lexer, pm, nested_prefix); } ExpectSymbol(lexer, "}"); // 可选的尾随分号 if (current_.type == Token::T_SYMBOL && current_.value == ";") Advance(lexer); - GetProtobufState(s_).RegisterMessage(std::move(def)); + GetProtobufState(s_).RegisterMessage(pm.def); + pending_messages_.push_back(std::move(pm)); } - void ParseMessageBody(Lexer &lexer, MessageDef &def, const std::string &prefix) { + void ParseMessageBody(Lexer &lexer, PendingMessage &pm, const std::string &prefix) { if (current_.type == Token::T_KEYWORD) { switch (current_.keyword_id) { case 4:// 嵌套 message @@ -439,18 +514,18 @@ class Parser { ParseEnum(lexer, prefix); return; case 6:// oneof - ParseOneof(lexer, def, prefix); + ParseOneof(lexer, pm, prefix); return; case 7:// map - ParseMapField(lexer, def, prefix); + ParseMapField(lexer, pm, prefix); return; case 8: // repeated Advance(lexer);// 跳过 'repeated',指向类型名 - ParseField(lexer, def, prefix, true, false); + ParseField(lexer, pm, prefix, true, false); return; case 9: // optional Advance(lexer);// 跳过 'optional',指向类型名 - ParseField(lexer, def, prefix, false, true); + ParseField(lexer, pm, prefix, false, true); return; case 10:// reserved ParseReserved(lexer); @@ -470,25 +545,25 @@ class Parser { return; } // 普通字段(无 label) - ParseField(lexer, def, prefix, false, false); + ParseField(lexer, pm, prefix, false, false); } // Field - void ParseField(Lexer &lexer, MessageDef &def, const std::string &prefix, bool repeated, bool is_optional) { + void ParseField(Lexer &lexer, PendingMessage &pm, const std::string &prefix, bool repeated, bool is_optional) { + std::string raw_type_name; std::string type_name; FieldType type = TYPE_INT32; + bool is_non_scalar = false; - if (current_.type == Token::T_IDENT) { - type_name = ParseQualifiedName(lexer); - if (type_name.find('.') == std::string::npos && IsScalarType(type_name)) { - type = ParseScalarType(type_name); + if (current_.type == Token::T_IDENT || (current_.type == Token::T_SYMBOL && current_.value == ".")) { + raw_type_name = ParseQualifiedName(lexer); + if (raw_type_name.find('.') == std::string::npos && IsScalarType(raw_type_name)) { + type = ParseScalarType(raw_type_name); type_name.clear(); - } else if (GetProtobufState(s_).FindEnum(type_name)) { - type = TYPE_ENUM; - type_name = ResolveTypeName(type_name, prefix); } else { - type = TYPE_MESSAGE; - type_name = ResolveTypeName(type_name, prefix); + is_non_scalar = true; + type_name = ResolveTypeName(raw_type_name, prefix); + type = GetProtobufState(s_).FindEnum(type_name) ? TYPE_ENUM : TYPE_MESSAGE; } } else { ThrowFakeluaException(std::format("proto parse error at line {}: expected field type", current_.line)); @@ -515,6 +590,10 @@ class Parser { ExpectSymbol(lexer, ";"); + if (is_non_scalar) { + pm.refs.push_back({pm.def.fields.size(), raw_type_name, false}); + } + FieldDef field; field.name = field_name; field.number = field_number; @@ -522,11 +601,11 @@ class Parser { field.type_name = type_name; field.repeated = repeated; field.optional = is_optional; - def.fields.push_back(std::move(field)); + pm.def.fields.push_back(std::move(field)); } // Map field - void ParseMapField(Lexer &lexer, MessageDef &def, const std::string &prefix) { + void ParseMapField(Lexer &lexer, PendingMessage &pm, const std::string &prefix) { Advance(lexer);// 跳过 'map' ExpectSymbol(lexer, "<"); if (current_.type != Token::T_IDENT) { @@ -565,17 +644,18 @@ class Parser { field.type = TYPE_MESSAGE;// map 编码为 message field.is_map = true; field.map_key_type = ParseScalarType(key_type_name); - if (IsScalarType(val_type_name)) { + if (val_type_name.find('.') == std::string::npos && IsScalarType(val_type_name)) { field.map_value_type = ParseScalarType(val_type_name); } else { - field.map_value_type = TYPE_MESSAGE; + pm.refs.push_back({pm.def.fields.size(), val_type_name, true}); field.map_value_type_name = ResolveTypeName(val_type_name, prefix); + field.map_value_type = GetProtobufState(s_).FindEnum(field.map_value_type_name) ? TYPE_ENUM : TYPE_MESSAGE; } - def.fields.push_back(std::move(field)); + pm.def.fields.push_back(std::move(field)); } // Oneof - void ParseOneof(Lexer &lexer, MessageDef &def, const std::string &prefix) { + void ParseOneof(Lexer &lexer, PendingMessage &pm, const std::string &prefix) { Advance(lexer);// 跳过 'oneof' if (current_.type != Token::T_IDENT) { ThrowFakeluaException(std::format("proto parse error at line {}: expected oneof name", current_.line)); @@ -584,7 +664,7 @@ class Parser { Advance(lexer); ExpectSymbol(lexer, "{"); - int oneof_index = static_cast(def.fields.size());// 简单编号 + int oneof_index = static_cast(pm.def.fields.size());// 简单编号 while (!(current_.type == Token::T_SYMBOL && current_.value == "}")) { if (current_.type == Token::T_KEYWORD && current_.keyword_id == 12) { @@ -596,22 +676,25 @@ class Parser { continue; } // oneof 内字段 - ParseOneofField(lexer, def, prefix, oneof_index); + ParseOneofField(lexer, pm, prefix, oneof_index); } ExpectSymbol(lexer, "}"); } - void ParseOneofField(Lexer &lexer, MessageDef &def, const std::string &prefix, int oneof_index) { + void ParseOneofField(Lexer &lexer, PendingMessage &pm, const std::string &prefix, int oneof_index) { + std::string raw_type_name; std::string type_name; FieldType type = TYPE_INT32; + bool is_non_scalar = false; - type_name = ParseQualifiedName(lexer); - if (type_name.find('.') == std::string::npos && IsScalarType(type_name)) { - type = ParseScalarType(type_name); + raw_type_name = ParseQualifiedName(lexer); + if (raw_type_name.find('.') == std::string::npos && IsScalarType(raw_type_name)) { + type = ParseScalarType(raw_type_name); type_name.clear(); } else { - type = TYPE_MESSAGE; - type_name = ResolveTypeName(type_name, prefix); + is_non_scalar = true; + type_name = ResolveTypeName(raw_type_name, prefix); + type = GetProtobufState(s_).FindEnum(type_name) ? TYPE_ENUM : TYPE_MESSAGE; } if (current_.type != Token::T_IDENT) { @@ -635,13 +718,17 @@ class Parser { ExpectSymbol(lexer, ";"); + if (is_non_scalar) { + pm.refs.push_back({pm.def.fields.size(), raw_type_name, false}); + } + FieldDef field; field.name = field_name; field.number = field_number; field.type = type; field.type_name = type_name; field.oneof_index = oneof_index; - def.fields.push_back(std::move(field)); + pm.def.fields.push_back(std::move(field)); } // Enum diff --git a/src/native/random/native_random.cpp b/src/native/random/native_random.cpp index be13f661..6836ed67 100644 --- a/src/native/random/native_random.cpp +++ b/src/native/random/native_random.cpp @@ -4,6 +4,7 @@ #include "native/table/native_table.h" #include "var/var.h" +#include #include #include #include @@ -108,10 +109,13 @@ static CVar RngFloat(NativeObject *self, State *s, CVar *args, int n) { CVar a0 = inter::GetNativeArg(s, args, n, 0); CVar a1 = inter::GetNativeArg(s, args, n, 1); - double lo = inter::CVarToNumber(a0, 0.0); - double hi = inter::CVarToNumber(a1, 0.0); + CheckNumberArg(a0, 1, "rng:float"); + CheckNumberArg(a1, 2, "rng:float"); + double lo = inter::CVarToNumber(a0, std::numeric_limits::quiet_NaN()); + double hi = inter::CVarToNumber(a1, std::numeric_limits::quiet_NaN()); - if (lo >= hi) ThrowBadArgument(2, "rng:float", "max must be > min"); + if (!std::isfinite(lo)) ThrowBadArgument(1, "rng:float", "finite number expected"); + if (!std::isfinite(hi) || lo >= hi || !std::isfinite(hi - lo)) ThrowBadArgument(2, "rng:float", "max must be > min and finite"); double val = lo + RngNextUnit(self) * (hi - lo); return inter::NativeToFakeluaDouble(s, val); @@ -155,7 +159,9 @@ static CVar RngChance(NativeObject *self, State *s, CVar *args, int n) { if (n < 1) ThrowBadArgument(1, "rng:chance", "probability expected"); CVar a0 = inter::GetNativeArg(s, args, n, 0); - double prob = inter::CVarToNumber(a0, 0.0); + CheckNumberArg(a0, 1, "rng:chance"); + double prob = inter::CVarToNumber(a0, std::numeric_limits::quiet_NaN()); + if (std::isnan(prob)) ThrowBadArgument(1, "rng:chance", "number expected"); if (prob <= 0.0) return inter::NativeToFakeluaBool(s, false); if (prob >= 1.0) return inter::NativeToFakeluaBool(s, true); @@ -182,13 +188,19 @@ static CVar RngWeighted(NativeObject *self, State *s, CVar *args, int n) { double total = 0.0; for (int64_t i = 1; i <= len; i++) { CVar val = table::TableHelper::GetTableInt(s, tbl, i); - double w = inter::CVarToNumber(val, 0.0); + CheckNumberArg(val, 1, "rng:weighted"); + double w = inter::CVarToNumber(val, std::numeric_limits::quiet_NaN()); + if (!std::isfinite(w)) { + ThrowBadArgument(1, "rng:weighted", "weights must be finite numbers"); + } if (w < 0.0) w = 0.0; weights.push_back(w); total += w; } - if (total <= 0.0) return inter::NativeToFakeluaNil(s); + if (!std::isfinite(total) || total <= 0.0) { + ThrowBadArgument(1, "rng:weighted", "total weight must be positive and finite"); + } // 随机选取 double roll = RngNextUnit(self) * total; @@ -251,6 +263,14 @@ static CVar RngSetStateMethod(NativeObject *self, State *s, CVar *args, int n) { return inter::NativeToFakeluaNil(s); } +// rng:close() — 销毁当前 RNG 实例及其所属对象组 +static CVar RngClose(NativeObject *self, State *s, CVar * /*args*/, int /*n*/) { + if (self) { + s->GetNativeObjectManager().DestroyGroup(self->GetGroupId()); + } + return inter::NativeToFakeluaNil(s); +} + // 注册 void RegisterRandomLibraryApi(State *s) { @@ -277,6 +297,7 @@ void RegisterRandomLibraryApi(State *s) { obj->RegisterMethod("weighted", RngWeighted); obj->RegisterMethod("get_state", RngGetStateMethod); obj->RegisterMethod("set_state", RngSetStateMethod); + obj->RegisterMethod("close", RngClose); return obj->Wrap(state); }); diff --git a/src/native/redis/native_redis.cpp b/src/native/redis/native_redis.cpp index e2a88a63..01a7b16f 100644 --- a/src/native/redis/native_redis.cpp +++ b/src/native/redis/native_redis.cpp @@ -29,19 +29,10 @@ static std::string CVarToString(CVar v) { return inter::FakeluaToNativeString(nullptr, v); } -static void CallNamed(State *s, const std::string &name, CVar *args, int n) { +static void CallNamed(State *s, const std::string &name, CVar *args, int n, JITType preferred_jit) { if (!s || name.empty()) return; - auto func = s->GetVM().GetFunction(name); - if (func.Empty()) return; - void *addr = func.GetAddr(JIT_TCC); - JITType jit_type = JIT_TCC; - if (!addr) { - addr = func.GetAddr(JIT_GCC); - jit_type = JIT_GCC; - } - if (!addr) return; native::IoContext::DispatchScope scope(s->GetIoContext()); - inter::DispatchCall(s, addr, args, n, jit_type); + DispatchNamedLuaCallback(s, name, args, n, preferred_jit); } static constexpr int kMaxRedisReplyDepth = 64; @@ -122,6 +113,7 @@ struct TickDepthGuard { struct CmdOp { std::string cb; + JITType cb_jit = JIT_TCC; std::string err; redisReply *reply = nullptr; bool done = false; @@ -146,18 +138,16 @@ class RedisConnection { password_ = password; db_ = db; connecting_ = true; - const int ms = timeout_ms > 0 ? timeout_ms : 10000; - deadline_ = std::chrono::steady_clock::now() + std::chrono::milliseconds(ms); + timeout_ms_ = timeout_ms > 0 ? timeout_ms : 10000; + deadline_armed_ = false; redisOptions opt; std::memset(&opt, 0, sizeof(opt)); REDIS_OPTIONS_SET_TCP(&opt, host_.c_str(), port_); - timeval tv{}; - if (timeout_ms > 0) { - tv.tv_sec = timeout_ms / 1000; - tv.tv_usec = (timeout_ms % 1000) * 1000; - opt.connect_timeout = &tv; - } + // hiredis would arm its connect timer at SetConnectCallback, before the + // first runtime.tick(). A slow C++ error path can then expire that timer + // (or our wall-clock deadline) before Poll() observes a socket that is + // already writable. Count timeout only across ticks that actually poll. ac_ = redisAsyncConnectWithOptions(&opt); if (!ac_ || ac_->err) { std::string err = ac_ && ac_->errstr[0] ? ac_->errstr : "connect failed"; @@ -181,7 +171,7 @@ class RedisConnection { redisAsyncSetDisconnectCallback(ac_, &RedisConnection::OnDisconnect); } - void Command(std::vector parts, std::string cb) { + void Command(std::vector parts, std::string cb, JITType cb_jit) { if (parts.empty()) ThrowFakeluaException("redis command: empty argv"); // Pub/Sub 订阅族命令不能走一次性 RPC 通道:订阅成功后 hiredis 会对每条推送 // 都以同一个 privdata 回调 OnCommand,而该 CmdOp 在首条 ack 派发后即被弹出 @@ -198,6 +188,7 @@ class RedisConnection { } auto op = std::make_unique(); op->cb = std::move(cb); + op->cb_jit = cb_jit; auto *raw = op.get(); cmds_.push_back(std::move(op)); IssueArgv(std::move(parts), &RedisConnection::OnCommand, raw); @@ -206,6 +197,10 @@ class RedisConnection { void Tick() { if (tick_depth_ > 0) return; TickDepthGuard guard(tick_depth_); + if (connecting_ && !connect_notified_ && !deadline_armed_) { + deadline_ = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout_ms_); + deadline_armed_ = true; + } io_.Poll(); if (connecting_ && !connect_notified_ && std::chrono::steady_clock::now() >= deadline_) { connecting_ = false; @@ -218,28 +213,50 @@ class RedisConnection { DispatchConnect(); if (close_pending_) return; } - for (auto &op: cmds_) { - if (op && op->done && !op->cb.empty()) { - DispatchCmd(*op); - op->cb.clear(); + auto reap_completed = [this]() { + while (!cmds_.empty() && (!cmds_.front() || (cmds_.front()->done && cmds_.front()->cb.empty()))) { + if (cmds_.front() && cmds_.front()->reply) { + freeReplyObject(cmds_.front()->reply); + cmds_.front()->reply = nullptr; + } + cmds_.pop_front(); } - } - while (!cmds_.empty() && cmds_.front() && cmds_.front()->done && cmds_.front()->cb.empty()) { - if (cmds_.front()->reply) { - freeReplyObject(cmds_.front()->reply); - cmds_.front()->reply = nullptr; + }; + struct ReapGuard { + decltype(reap_completed) &fn; + ~ReapGuard() { + fn(); } - cmds_.pop_front(); + } reap_guard{reap_completed}; + + for (size_t i = 0; i < cmds_.size(); ++i) { + if (close_pending_) break; + CmdOp *op = cmds_[i].get(); + if (!op || !op->done || op->cb.empty()) continue; + std::string cb = std::move(op->cb); + op->cb.clear(); + const JITType cb_jit = op->cb_jit; + struct ReplyFreeGuard { + CmdOp *op; + ~ReplyFreeGuard() { + if (op && op->reply) { + freeReplyObject(op->reply); + op->reply = nullptr; + } + } + } reply_guard{op}; + DispatchCmd(*op, cb, cb_jit); } } void Close() { closed_ = true; if (!connect_notified_) NotifyConnect("closed"); - if (tick_depth_ > 0 || io_.InDispatch()) { + if (tick_depth_ > 0) { close_pending_ = true; return; } + close_pending_ = false; Teardown(); } @@ -251,13 +268,25 @@ class RedisConnection { return close_pending_; } + bool DeletePending() const { + return delete_on_unwind_; + } + void RequestClose() { closed_ = true; close_pending_ = true; } - void SetConnectCallback(std::string name) { + void RequestDelete() { + closed_ = true; + close_pending_ = true; + native_obj_ = nullptr; + delete_on_unwind_ = true; + } + + void SetConnectCallback(std::string name, JITType jit) { connect_cb_ = std::move(name); + connect_cb_jit_ = jit; } void SetNativeObject(NativeObject *obj) { @@ -457,14 +486,14 @@ class RedisConnection { args[1] = inter::NativeToFakeluaNil(lua_state_); args[2] = inter::NativeToFakeluaInt(lua_state_, 1); } - CallNamed(lua_state_, connect_cb_, args, 3); + CallNamed(lua_state_, connect_cb_, args, 3, connect_cb_jit_); } - void DispatchCmd(CmdOp &op) { + void DispatchCmd(CmdOp &op, const std::string &cb, JITType cb_jit) { TickDepthGuard guard(tick_depth_); native::IoContext::DispatchScope dispatch_scope(io_); if (close_pending_) return; - if (!lua_state_ || op.cb.empty()) return; + if (!lua_state_ || cb.empty()) return; CVar args[3]; args[0] = native_obj_ ? inter::NativeToFakeluaNativeObject(lua_state_, native_obj_) : inter::NativeToFakeluaNil(lua_state_); if (!op.err.empty()) { @@ -474,7 +503,7 @@ class RedisConnection { args[1] = inter::NativeToFakeluaNil(lua_state_); args[2] = ReplyToLua(lua_state_, op.reply); } - CallNamed(lua_state_, op.cb, args, 3); + CallNamed(lua_state_, cb, args, 3, cb_jit); } native::IoContext &io_; @@ -486,8 +515,11 @@ class RedisConnection { int db_ = 0; int hs_step_ = 0; std::chrono::steady_clock::time_point deadline_{}; + int timeout_ms_ = 10000; + bool deadline_armed_ = false; std::deque> cmds_; std::string connect_cb_; + JITType connect_cb_jit_ = JIT_TCC; std::string connect_err_; State *lua_state_ = nullptr; NativeObject *native_obj_ = nullptr; @@ -497,6 +529,7 @@ class RedisConnection { bool ready_ = false; bool closed_ = false; bool close_pending_ = false; + bool delete_on_unwind_ = false; int tick_depth_ = 0; native::LifeToken life_; }; @@ -526,13 +559,6 @@ static void UnregisterWrapper(NativeObject *nat) { ws->conns.erase(std::remove(ws->conns.begin(), ws->conns.end(), nat), ws->conns.end()); } -static void MaybeReleaseOwnedConn(NativeObject *self) { - if (!self) return; - auto *conn = Unwrap(self); - if (!conn || conn->TickDepth() > 0 || !conn->ClosePending()) return; - conn->Close(); -} - void TickAll(State *s) { if (!s) return; auto *ws = s->TryGetModuleState(); @@ -542,8 +568,28 @@ void TickAll(State *s) { auto *c = Unwrap(nat); if (!c) continue; if (c->TickDepth() > 0) continue; + struct AfterTickGuard { + NativeObject *nat; + RedisConnection *c; + ~AfterTickGuard() { + if (c->TickDepth() == 0) { + if (c->DeletePending()) { + c->Close(); + delete c; + return; + } + if (c->ClosePending()) { + c->Close(); + if (nat && nat->Alive()) { + UnregisterWrapper(nat); + nat->SetInt("__redis_conn__", 0); + } + delete c; + } + } + } + } after{nat, c}; c->Tick(); - MaybeReleaseOwnedConn(nat); } } @@ -582,7 +628,7 @@ static CVar ConnCommand(NativeObject *self, State *s, CVar *args, int n) { } else { ThrowBadArgument(1, "command", "argv table expected"); } - conn->Command(std::move(parts), std::move(cb)); + conn->Command(std::move(parts), std::move(cb), s->CurrentJit()); return inter::NativeToFakeluaNil(s); } @@ -593,7 +639,10 @@ static CVar ConnClose(NativeObject *self, State *s, CVar * /*args*/, int /*n*/) conn->RequestClose(); return inter::NativeToFakeluaNil(s); } + UnregisterWrapper(self); + self->SetInt("__redis_conn__", 0); conn->Close(); + delete conn; } return inter::NativeToFakeluaNil(s); } @@ -634,7 +683,7 @@ static CVar RedisConnect(State *s, CVar *args, int n) { int64_t gid = s->GetNativeObjectManager().CreateGroup(); auto *nat = s->GetNativeObjectManager().Create(gid, "redis_connection"); auto *conn = new RedisConnection(s); - conn->SetConnectCallback(std::move(cb)); + conn->SetConnectCallback(std::move(cb), s->CurrentJit()); conn->SetNativeObject(nat); nat->SetInt("__redis_conn__", reinterpret_cast(conn)); nat->RegisterMethod("command", ConnCommand); @@ -643,10 +692,11 @@ static CVar RedisConnect(State *s, CVar *args, int n) { UnregisterWrapper(self); auto *c = Unwrap(self); if (c) { + self->SetInt("__redis_conn__", 0); + c->SetNativeObject(nullptr); if (c->TickDepth() > 0) { - c->RequestClose(); + c->RequestDelete(); } else { - self->SetInt("__redis_conn__", 0); c->Close(); delete c; } diff --git a/src/native/serialize/native_serialize.cpp b/src/native/serialize/native_serialize.cpp index 6fba49f7..16a3e028 100644 --- a/src/native/serialize/native_serialize.cpp +++ b/src/native/serialize/native_serialize.cpp @@ -59,6 +59,9 @@ static CVar SerializeDecode(State *s, CVar *args, int n) { return result; } +static constexpr int kSerMaxDepth = 64; +static thread_local int g_ser_load_depth = 0; + // Boost.Serialization 树:不替换 encode/decode 的紧凑 wire,提供可读的 text/xml 往返。 // kind 用 int,避免 int8_t/signed char 被 Boost 当成字符写出。 struct SerNode { @@ -74,6 +77,28 @@ struct SerNode { template void serialize(Archive &ar, const unsigned int) { + if constexpr (Archive::is_loading::value) { + struct LoadDepthGuard { + int &d; + explicit LoadDepthGuard(int &depth) : d(depth) { + ++d; + } + ~LoadDepthGuard() { + --d; + } + } guard(g_ser_load_depth); + if (g_ser_load_depth > kSerMaxDepth) { + ThrowFakeluaException("serialize.decode: nesting too deep"); + } + ar &BOOST_SERIALIZATION_NVP(kind); + ar &BOOST_SERIALIZATION_NVP(b); + ar &BOOST_SERIALIZATION_NVP(i); + ar &BOOST_SERIALIZATION_NVP(f); + ar &BOOST_SERIALIZATION_NVP(s); + ar &BOOST_SERIALIZATION_NVP(keys); + ar &BOOST_SERIALIZATION_NVP(vals); + return; + } ar &BOOST_SERIALIZATION_NVP(kind); ar &BOOST_SERIALIZATION_NVP(b); ar &BOOST_SERIALIZATION_NVP(i); @@ -84,8 +109,6 @@ struct SerNode { } }; -static constexpr int kSerMaxDepth = 64; - static SerNode CVarToSerNode(CVar v, std::unordered_set &visited, int depth, const char *op) { SerNode n; switch (v.type_) { @@ -180,7 +203,9 @@ static CVar SerializeTextEncode(State *s, CVar *args, int n) { oa << root; } return inter::NativeToFakeluaString(s, oss.str()); - } catch (const boost::archive::archive_exception &e) { + } catch (const FakeluaException &) { + throw; + } catch (const std::exception &e) { ThrowFakeluaException(std::format("serialize.text_encode: {}", e.what())); } } @@ -195,7 +220,9 @@ static CVar SerializeTextDecode(State *s, CVar *args, int n) { ia >> root; } return SerNodeToCVar(root, s, 0); - } catch (const boost::archive::archive_exception &e) { + } catch (const FakeluaException &) { + throw; + } catch (const std::exception &e) { ThrowFakeluaException(std::format("serialize.text_decode: {}", e.what())); } } @@ -209,7 +236,9 @@ static CVar SerializeXmlEncode(State *s, CVar *args, int n) { oa << boost::serialization::make_nvp("value", root); } return inter::NativeToFakeluaString(s, oss.str()); - } catch (const boost::archive::archive_exception &e) { + } catch (const FakeluaException &) { + throw; + } catch (const std::exception &e) { ThrowFakeluaException(std::format("serialize.xml_encode: {}", e.what())); } } @@ -224,7 +253,9 @@ static CVar SerializeXmlDecode(State *s, CVar *args, int n) { ia >> boost::serialization::make_nvp("value", root); } return SerNodeToCVar(root, s, 0); - } catch (const boost::archive::archive_exception &e) { + } catch (const FakeluaException &) { + throw; + } catch (const std::exception &e) { ThrowFakeluaException(std::format("serialize.xml_decode: {}", e.what())); } } diff --git a/src/native/sqlite/native_sqlite.cpp b/src/native/sqlite/native_sqlite.cpp index ad6d9e15..e5b712c3 100644 --- a/src/native/sqlite/native_sqlite.cpp +++ b/src/native/sqlite/native_sqlite.cpp @@ -338,6 +338,7 @@ CVar StmtClose(NativeObject *self, State *s, CVar * /*args*/, int /*n*/) { obj->db = nullptr; delete obj; self->SetInt("__sqlite_stmt__", 0); + UnregisterSqliteWrapper(self); if (rc != SQLITE_OK) { error(std::string("stmt:close: ") + sqlite3_errstr(rc)); } @@ -368,6 +369,7 @@ CVar DbClose(NativeObject *self, State *s, CVar * /*args*/, int /*n*/) { } delete obj; self->SetInt("__sqlite_db__", 0); + UnregisterSqliteWrapper(self); } return inter::NativeToFakeluaNil(s); } diff --git a/src/native/string/native_string.cpp b/src/native/string/native_string.cpp index 0bb538fa..36e32e88 100644 --- a/src/native/string/native_string.cpp +++ b/src/native/string/native_string.cpp @@ -681,34 +681,36 @@ extern "C" CVar GMatchIterator(VarClosure *cl, CVar /*s*/, CVar /*var*/) { return inter::NativeToFakeluaNil(iter_state); } - const size_t slen = gs->text.size(); - size_t pos = (gs->prev == std::numeric_limits::max()) ? 0 : gs->prev; - // gmatch 不像 gsub/find 有锚定概念:模式里的 '^' 是普通字符。 - const char *src = gs->text.data(); - const char *pat = gs->pattern.c_str(); - while (pos <= slen) { - lua_pattern::MatchResult m; - if (lua_pattern::MatchAt(src, slen, pat, gs->pattern.size(), pos, m, /*leading_caret_is_anchor=*/false)) { - const size_t mend = static_cast(m.end - src); - // 零宽匹配只在「不是紧跟上一个产出位置」时产出,否则跳过一位, - // 避免重复空匹配(PUC-Rio gmatch_iter 语义)。 - if (mend != pos || pos != gs->prev) { - gs->prev = mend; - CheckCapturesFinished(m); - if (m.level > 0) { - CVar multi = inter::AllocMultiCVar(iter_state, m.level); - for (int i = 0; i < m.level; ++i) { - inter::SetMultiCVarElement(multi, i, CaptureToCVar(iter_state, src, m, i)); + return GuardJitEntry(iter_state, [&]() -> CVar { + const size_t slen = gs->text.size(); + size_t pos = (gs->prev == std::numeric_limits::max()) ? 0 : gs->prev; + // gmatch 不像 gsub/find 有锚定概念:模式里的 '^' 是普通字符。 + const char *src = gs->text.data(); + const char *pat = gs->pattern.c_str(); + while (pos <= slen) { + lua_pattern::MatchResult m; + if (lua_pattern::MatchAt(src, slen, pat, gs->pattern.size(), pos, m, /*leading_caret_is_anchor=*/false)) { + const size_t mend = static_cast(m.end - src); + // 零宽匹配只在「不是紧跟上一个产出位置」时产出,否则跳过一位, + // 避免重复空匹配(PUC-Rio gmatch_iter 语义)。 + if (mend != pos || pos != gs->prev) { + gs->prev = mend; + CheckCapturesFinished(m); + if (m.level > 0) { + CVar multi = inter::AllocMultiCVar(iter_state, m.level); + for (int i = 0; i < m.level; ++i) { + inter::SetMultiCVarElement(multi, i, CaptureToCVar(iter_state, src, m, i)); + } + return multi; } - return multi; + return inter::NativeToFakeluaStringView(iter_state, std::string_view(m.begin, static_cast(m.end - m.begin))); } - return inter::NativeToFakeluaStringView(iter_state, std::string_view(m.begin, static_cast(m.end - m.begin))); } + ++pos; } - ++pos; - } - gs->prev = std::numeric_limits::max();// 标记迭代结束 - return inter::NativeToFakeluaNil(iter_state); + gs->prev = std::numeric_limits::max();// 标记迭代结束 + return inter::NativeToFakeluaNil(iter_state); + }); } std::string_view GetStringArgView(CVar a, std::string &temp) { @@ -1525,13 +1527,20 @@ void RegisterStringLibraryApi(State *s) { } } - // 标准 Lua:gsub 的替换参数必须是 string/function/table,Bool 不合法 - if (repl_var.type_ == static_cast(VarType::Bool)) { - ThrowFakeluaException("bad argument #3 to 'string.gsub' (string/function/table expected, got boolean)"); - } + // 标准 Lua:gsub 的第 3 参数必须是 string/number/function/table const bool repl_is_table = (repl_var.type_ == static_cast(VarType::Table) && repl_var.data_.t); const bool repl_is_closure = (repl_var.type_ == static_cast(VarType::Closure) && repl_var.data_.cl); - const std::string repl_str = (repl_is_table || repl_is_closure) ? std::string() : std::string(KeyToStringView(repl_var)); + std::string repl_num_tmp; + if (!repl_is_table && !repl_is_closure) { + if (repl_var.type_ == static_cast(VarType::Bool)) { + ThrowFakeluaException("bad argument #3 to 'string.gsub' (string/function/table expected, got boolean)"); + } + if (repl_var.type_ != static_cast(VarType::String) && repl_var.type_ != static_cast(VarType::StringId) && + repl_var.type_ != static_cast(VarType::Int) && repl_var.type_ != static_cast(VarType::Float)) { + ThrowFakeluaException("bad argument #3 to 'string.gsub' (string/function/table expected)"); + } + } + const std::string repl_str = (repl_is_table || repl_is_closure) ? std::string() : std::string(GetStringArgView(repl_var, repl_num_tmp)); const bool anchored = !pat_view.empty() && pat_view[0] == '^'; const char *eff_pat = pat_view.data() + (anchored ? 1 : 0); @@ -1577,6 +1586,26 @@ void RegisterStringLibraryApi(State *s) { std::string replacement; bool keep_original = false; + const auto apply_repl_value = [&](CVar rv) { + while (rv.type_ == static_cast(VarType::Multi)) { + VarMulti *mm = rv.data_.m; + rv = (mm && mm->GetCount() > 0) ? mm->GetVars()[0] : CVar{static_cast(VarType::Nil)}; + } + if (rv.type_ == static_cast(VarType::Nil) || (rv.type_ == static_cast(VarType::Bool) && !rv.data_.b)) { + keep_original = true; + } else if (rv.type_ == static_cast(VarType::String) || rv.type_ == static_cast(VarType::StringId)) { + replacement = std::string(KeyToStringView(rv)); + } else if (rv.type_ == static_cast(VarType::Int) || rv.type_ == static_cast(VarType::Float)) { + replacement = AsVar(rv).ToString(/*has_quote=*/false, /*has_postfix=*/false); + } else if (rv.type_ == static_cast(VarType::Bool)) { + ThrowFakeluaException("invalid replacement value (a boolean)"); + } else if (rv.type_ == static_cast(VarType::Table)) { + ThrowFakeluaException("invalid replacement value (a table)"); + } else { + ThrowFakeluaException("invalid replacement value (a function)"); + } + }; + if (repl_is_closure) { VarClosure *cl = repl_var.data_.cl; const int call_arg_count = (m.level > 0) ? m.level : 1; @@ -1594,15 +1623,7 @@ void RegisterStringLibraryApi(State *s) { // 在发起 gsub 的引擎里同步调用替换函数(与 pool:with 同理)。 CVar fn_res = (cl->func_ptr != nullptr) ? inter::DispatchCallClosure(state, cl, call_args.data(), call_arg_count, state->CurrentJit()) : FlEvalLoadClosure(state, cl, call_arg_count, call_args.data()); - if (fn_res.type_ == static_cast(VarType::Nil) || (fn_res.type_ == static_cast(VarType::Bool) && !fn_res.data_.b)) { - keep_original = true; - } else if (fn_res.type_ == static_cast(VarType::Bool)) { - ThrowFakeluaException("invalid replacement value (a boolean)"); - } else if (fn_res.type_ == static_cast(VarType::Table)) { - ThrowFakeluaException("invalid replacement value (a table)"); - } else { - replacement = std::string(KeyToStringView(fn_res)); - } + apply_repl_value(fn_res); } else if (repl_is_table) { CVar val; if (m.level > 0) { @@ -1610,20 +1631,14 @@ void RegisterStringLibraryApi(State *s) { if (cap0.len == lua_pattern::kCapPosition) { val = table::TableHelper::GetTableInt(state, repl_var, static_cast(cap0.init - sv.data()) + 1); } else { - std::string key(cap0.init, static_cast(cap0.len)); - val = table::TableHelper::GetTableStrId(state, repl_var, key.c_str()); + CVar k_var = inter::NativeToFakeluaStringView(state, std::string_view(cap0.init, static_cast(cap0.len))); + val = table::TableHelper::GetTable(state, repl_var, k_var); } } else { - std::string key(whole); - val = table::TableHelper::GetTableStrId(state, repl_var, key.c_str()); - } - if (val.type_ == static_cast(VarType::Nil) || (val.type_ == static_cast(VarType::Bool) && !val.data_.b)) { - keep_original = true; - } else if (val.type_ == static_cast(VarType::Bool) || val.type_ == static_cast(VarType::Table)) { - ThrowFakeluaException("invalid replacement value (a boolean)"); - } else { - replacement = std::string(KeyToStringView(val)); + CVar k_var = inter::NativeToFakeluaStringView(state, whole); + val = table::TableHelper::GetTable(state, repl_var, k_var); } + apply_repl_value(val); } else { // 字符串替换:%0=整个匹配,%1-%9=捕获,%%=百分号,其余 %x 报错。 for (size_t i = 0; i < repl_str.size(); ++i) { @@ -1690,7 +1705,7 @@ void RegisterStringLibraryApi(State *s) { } VarClosure *cl = fn_var.data_.cl; std::string code; - if (cl->code_str && cl->code_str != reinterpret_cast(static_cast(1))) { + if (IsSourceLoadClosure(cl)) { code = cl->code_str; } std::string payload = "\x1bLua"; @@ -1772,7 +1787,8 @@ void RegisterStringLibraryApi(State *s) { if (len > sv.size() - idx) { uv.type_ = static_cast(VarType::Nil); } else { - uv = inter::NativeToFakeluaStringView(state, std::string_view(sv.data() + idx, len)); + uv.type_ = static_cast(VarType::StringId); + uv.data_.i = state->GetConstString().Alloc(std::string_view(sv.data() + idx, len)); idx += len; } } else if (type != static_cast(VarType::Nil)) { @@ -1787,7 +1803,6 @@ void RegisterStringLibraryApi(State *s) { } try { - CompileConfig config; std::string wrapper_code; if (!code.empty()) { if (code.find("function") == std::string::npos && code.find("return") == std::string::npos) { @@ -1797,11 +1812,15 @@ void RegisterStringLibraryApi(State *s) { } } - auto &alloc = state->GetValueAllocator(); + // load() 返回的闭包可能被脚本保存在模块/全局状态中跨 Call() 调用,分配在 const_heap 避免 Reset() 悬空。 + auto &alloc = state->GetHeap().GetAllocator(true); char *saved_code = nullptr; if (!wrapper_code.empty()) { saved_code = static_cast(alloc.Alloc(wrapper_code.size() + 1)); std::memcpy(saved_code, wrapper_code.c_str(), wrapper_code.size() + 1); + } else { + saved_code = static_cast(alloc.Alloc(1)); + saved_code[0] = '\0'; } VarClosure *cl = static_cast(alloc.Alloc(sizeof(VarClosure) + static_cast(upval_cnt) * sizeof(CVar *))); @@ -1846,10 +1865,15 @@ void RegisterStringLibraryApi(State *s) { std::string source((std::istreambuf_iterator(ifs)), std::istreambuf_iterator()); ifs.close(); - // 编译文件内容,顶层函数注册为全局,编译器自动执行 __fakelua_init + // 仅在当前活跃引擎上编译并执行 __fakelua_init,避免重复触发多遍初始化副作用与无谓的 GCC 编译。 try { CompileConfig config; - CompileString(state, source, config); + config.debug_mode = false; + const JITType active_jit = state->CurrentJit(); + for (int j = 0; j < JIT_MAX; ++j) { + config.disable_jit[j] = (j != static_cast(active_jit)); + } + CompileFile(state, std::string(filename_sv), config); } catch (...) { return inter::NativeToFakeluaNil(state); } @@ -1869,12 +1893,16 @@ void RegisterStringLibraryApi(State *s) { utf8_io::ifstream ifs(std::string(filename_sv), std::ios::in | std::ios::binary); if (!ifs.is_open()) return inter::NativeToFakeluaNil(state); - std::string source((std::istreambuf_iterator(ifs)), std::istreambuf_iterator()); ifs.close(); try { CompileConfig config; - CompileString(state, source, config); + config.debug_mode = false; + const JITType active_jit = state->CurrentJit(); + for (int j = 0; j < JIT_MAX; ++j) { + config.disable_jit[j] = (j != static_cast(active_jit)); + } + CompileFile(state, std::string(filename_sv), config); } catch (...) { return inter::NativeToFakeluaNil(state); } @@ -2441,7 +2469,7 @@ struct EvalCounter { }; extern "C" CVar FlEvalLoadClosure(State *state, VarClosure *cl, int arg_num, const CVar *args) { - if (!state || !cl || !cl->code_str) { + if (!state || !IsSourceLoadClosure(cl)) { return inter::NativeToFakeluaNil(state); } std::string code = cl->code_str; @@ -2451,38 +2479,65 @@ extern "C" CVar FlEvalLoadClosure(State *state, VarClosure *cl, int arg_num, con } // 每 State 一份:生成的函数名只需在本 State 的函数表里唯一(下面的 CompileString 和 - // FakeluaCallByName 都是按 State 查的),所以不需要一个全进程共享的发号器。 + // CallByNameArgs 都是按 State 查的),所以不需要一个全进程共享的发号器。 auto &eval_counter = state->GetModuleState(); std::string eval_fn_name = "__flua_eval_ld_" + std::to_string(++eval_counter.next); + auto escape_lua_str = [](std::string_view sv) -> std::string { + std::string out = "\""; + out.reserve(sv.size() + 2); + for (unsigned char ch: sv) { + if (ch == '\\') out += "\\\\"; + else if (ch == '"') out += "\\\""; + else if (ch == '\n') out += "\\n"; + else if (ch == '\r') out += "\\r"; + else if (ch == '\0') out += "\\000"; + else if (ch < 32 || ch >= 127) out += std::format("\\{:03d}", static_cast(ch)); + else out.push_back(static_cast(ch)); + } + out.push_back('"'); + return out; + }; + std::string upval_decls; for (int i = 0; i < cl->upvalue_count; ++i) { if (cl->upvalues[i]) { + const std::string uv_name = (i == 0) ? "x" : ("__fl_uv_" + std::to_string(i)); CVar uv = *cl->upvalues[i]; if (uv.type_ == static_cast(VarType::Int)) { - upval_decls += "local x = " + std::to_string(uv.data_.i) + "\n"; + upval_decls += "local " + uv_name + " = " + std::to_string(uv.data_.i) + "\n"; } else if (uv.type_ == static_cast(VarType::Float)) { - upval_decls += "local x = " + std::to_string(uv.data_.f) + "\n"; + upval_decls += "local " + uv_name + " = " + std::to_string(uv.data_.f) + "\n"; } else if (uv.type_ == static_cast(VarType::Bool)) { - upval_decls += "local x = " + std::string(uv.data_.b ? "true\n" : "false\n"); + upval_decls += "local " + uv_name + " = " + std::string(uv.data_.b ? "true\n" : "false\n"); + } else if (uv.type_ == static_cast(VarType::String) || uv.type_ == static_cast(VarType::StringId)) { + upval_decls += "local " + uv_name + " = " + escape_lua_str(KeyToStringView(uv)) + "\n"; } } } std::string full_code; if (code.find("function") == std::string::npos && code.find("return") == std::string::npos) { - full_code = upval_decls + "function " + eval_fn_name + "()\nreturn " + code + "\nend"; + full_code = upval_decls + "function " + eval_fn_name + "(...)\nreturn " + code + "\nend"; } else { - full_code = upval_decls + "function " + eval_fn_name + "()\n" + code + "\nend"; + full_code = upval_decls + "function " + eval_fn_name + "(...)\n" + code + "\nend"; } try { CompileConfig config; + config.debug_mode = false; + const JITType active_jit = state->CurrentJit(); + for (int j = 0; j < JIT_MAX; ++j) { + config.disable_jit[j] = (j != static_cast(active_jit)); + } CompileString(state, full_code, config); // 边界不能省:本函数要靠下面的 catch 把错误吞成 nil,若让错误直接跳到更外层的 // 边界,这里的 std::string 就不会析构,语义也从"返回 nil"变成了向上抛。 - CVar res = RunWithJitErrorBoundary(state, [&] { return FakeluaCallByName(state, JIT_TCC, eval_fn_name.c_str(), 0); }); - return res; + const int safe_n = (args && arg_num > 0) ? arg_num : 0; + if (active_jit == JIT_TCC) { + return RunWithJitErrorBoundary(state, [&] { return CallByNameArgs(state, static_cast(active_jit), eval_fn_name, safe_n, safe_n > 0 ? args : nullptr); }); + } + return CallByNameArgs(state, static_cast(active_jit), eval_fn_name, safe_n, safe_n > 0 ? args : nullptr); } catch (...) { return inter::NativeToFakeluaNil(state); } diff --git a/src/native/table/native_table.cpp b/src/native/table/native_table.cpp index 26628817..52ad5a87 100644 --- a/src/native/table/native_table.cpp +++ b/src/native/table/native_table.cpp @@ -1,5 +1,6 @@ #include "native/table/native_table.h" #include "compile/c_runtime_header.h" +#include "interp/func_proto.h" #include "native/native_common.h" #include "native/object/native_object.h" #include "native/string/native_string.h" @@ -569,6 +570,34 @@ void CheckConstTable(State *s, CVar tbl) { } } +template +void SafeMergeSort(std::vector &vec, Comp &&comp) { + const size_t n = vec.size(); + if (n <= 1) return; + std::vector tmp(n); + for (size_t width = 1; width < n; width *= 2) { + for (size_t left = 0; left < n; left += 2 * width) { + const size_t mid = std::min(left + width, n); + const size_t right = std::min(left + 2 * width, n); + size_t i = left; + size_t j = mid; + size_t k = left; + while (i < mid && j < right) { + if (comp(vec[j], vec[i])) { + tmp[k++] = vec[j++]; + } else { + tmp[k++] = vec[i++]; + } + } + while (i < mid) tmp[k++] = vec[i++]; + while (j < right) tmp[k++] = vec[j++]; + for (size_t p = left; p < right; ++p) { + vec[p] = tmp[p]; + } + } + } +} + }// namespace bool TableHelper::VarKeyEqualInt(CVar k, int64_t idx) { @@ -689,12 +718,15 @@ CVar TableHelper::GetTableInt(State *s, CVar tbl, int64_t idx) { CVar TableHelper::GetTable(State *s, CVar tbl, CVar key) { (void) s; - if (tbl.type_ != static_cast(VarType::Table) || !tbl.data_.t) return CVar{static_cast(VarType::Nil)}; - VarTable *t = tbl.data_.t; - key = NormalizeTableKey(key); - if (key.type_ == kFloatType && std::isnan(key.data_.f)) { + if (tbl.type_ != static_cast(VarType::Table) || !tbl.data_.t) return CVar{kNilType}; + if (key.type_ == kNilType) { + return CVar{kNilType}; + } + if (UNLIKELY(key.type_ == kFloatType && std::isnan(key.data_.f))) { ThrowFakeluaException("table index is NaN"); } + VarTable *t = tbl.data_.t; + key = NormalizeTableKey(key); if (t->spec_get) { using SpecGetFn = CVar (*)(VarTable *, CVar, bool *); @@ -718,17 +750,18 @@ CVar TableHelper::GetTable(State *s, CVar tbl, CVar key) { const auto &qd = t->quick_data_[i]; if (qd.hash == hash && VarKeyEqual(qd.key, key)) return qd.val; } - return CVar{static_cast(VarType::Nil)}; + return CVar{kNilType}; } - if (!t->nodes_) return CVar{static_cast(VarType::Nil)}; + if (!t->nodes_) return CVar{kNilType}; const uint32_t mask = t->bucket_count_ - 1; const auto *curr = &t->nodes_[hash & mask]; + if (curr->entry.key.type_ == kNilType) return CVar{kNilType}; while (true) { if (curr->entry.hash == hash && VarKeyEqual(curr->entry.key, key)) return curr->entry.val; if (curr->next == VarTable::INVALID_INDEX) break; curr = &t->nodes_[curr->next]; } - return CVar{static_cast(VarType::Nil)}; + return CVar{kNilType}; } CVar TableHelper::GetTableStrId(State *s, CVar tbl, const char *str_key) { @@ -834,7 +867,9 @@ void TableHelper::SetTable(State *s, CVar tbl, CVar key, CVar val) { VarTable *t = tbl.data_.t; key = NormalizeTableKey(key); - if (key.type_ == kNilType) return; + if (key.type_ == kNilType) { + ThrowFakeluaException("table index is nil"); + } if (key.type_ == kFloatType && std::isnan(key.data_.f)) { ThrowFakeluaException("table index is NaN"); } @@ -866,12 +901,21 @@ void TableHelper::SetTableStrId(State *s, CVar tbl, std::string_view str_key, CV CheckConstTable(s, tbl); VarTable *t = tbl.data_.t; const int64_t id = s->GetConstString().Alloc(str_key); - const auto *vs = reinterpret_cast(id); - const uint32_t hash = vs->Hash(); CVar key{static_cast(VarType::StringId)}; key.data_.i = id; + if (t->spec_set) { + using SpecSetFn = void (*)(VarTable *, CVar, CVar, bool *); + auto set_fn = reinterpret_cast(t->spec_set); + bool finish = false; + set_fn(t, key, val, &finish); + if (finish) return; + } + + const auto *vs = reinterpret_cast(id); + const uint32_t hash = vs->Hash(); + if (val.type_ == kNilType) { TableDelete(t, key, hash); } else { @@ -883,6 +927,13 @@ void TableHelper::SetTableStrId(State *s, CVar tbl, const char *str_key, CVar va SetTableStrId(s, tbl, std::string_view(str_key ? str_key : ""), val); } +void TableHelper::SetTableTempStr(State *s, CVar tbl, std::string_view key, CVar val) { + if (tbl.type_ != static_cast(VarType::Table) || !tbl.data_.t) return; + CVar key_cvar{kStringType}; + key_cvar.data_.s = VarString::AllocTemp(s, key); + SetTable(s, tbl, key_cvar, val); +} + // Use shared CheckNumberArg from native_common.h CVar TableHelper::CreateTable(State *state) { @@ -1197,61 +1248,71 @@ void RegisterTableLibraryApi(State *s) { ThrowBadArgument(2, "table.sort", "function expected"); } - if (comp.type_ == static_cast(VarType::Closure) && comp.data_.cl) { + if (comp.type_ == static_cast(VarType::Closure)) { VarClosure *cl = comp.data_.cl; - auto comp_func = [&](const CVar &a, const CVar &b) -> bool { - CVar res{static_cast(VarType::Nil)}; + if (!cl) { + ThrowFakeluaException("closure has no code"); + } + auto call_comp = [&](const CVar &a, const CVar &b) -> bool { + CVar res{kNilType}; if (cl->func_ptr) { CVar cmp_args[2] = {a, b}; - // DispatchCallClosure 走 JIT_TCC 边界,错误能穿过 stable_sort 回到这里 res = inter::DispatchCallClosure(state, cl, cmp_args, 2, JIT_TCC); - } else if (cl->code_str) { + } else if (IsSourceLoadClosure(cl)) { CVar args_arr[2] = {a, b}; res = FlEvalLoadClosure(state, cl, 2, args_arr); + } else { + ThrowFakeluaException("closure has no code"); } - bool is_true = !(res.type_ == static_cast(VarType::Nil) || (res.type_ == static_cast(VarType::Bool) && !res.data_.b)); - return is_true; + while (res.type_ == static_cast(VarType::Multi)) { + res = (res.data_.m && res.data_.m->GetCount() > 0) ? res.data_.m->GetVars()[0] : CVar{kNilType}; + } + return !(res.type_ == kNilType || (res.type_ == static_cast(VarType::Bool) && !res.data_.b)); + }; + if (call_comp(vec.front(), vec.front()) || call_comp(vec.back(), vec.back())) { + ThrowFakeluaException("invalid order function for sorting"); + } + auto comp_func = [&](const CVar &a, const CVar &b) -> bool { + if (call_comp(a, b)) { + if (call_comp(b, a)) { + ThrowFakeluaException("invalid order function for sorting"); + } + return true; + } + return false; }; - std::stable_sort(vec.begin(), vec.end(), comp_func); + SafeMergeSort(vec, comp_func); } else { auto default_comp = [](const CVar &a, const CVar &b) -> bool { - // NaN 对 < 双向都是 false,破坏 strict weak ordering,std::stable_sort 是 UB。 - // 对齐 Lua 5.4:报 invalid order function for sorting。 - if ((a.type_ == static_cast(VarType::Float) && std::isnan(a.data_.f)) || (b.type_ == static_cast(VarType::Float) && std::isnan(b.data_.f))) { + if ((a.type_ == kFloatType && std::isnan(a.data_.f)) || (b.type_ == kFloatType && std::isnan(b.data_.f))) { ThrowFakeluaException("invalid order function for sorting"); } - if (a.type_ == static_cast(VarType::Int) && b.type_ == static_cast(VarType::Int)) { - return a.data_.i < b.data_.i; + const bool a_is_num = (a.type_ == kIntType || a.type_ == kFloatType); + const bool b_is_num = (b.type_ == kIntType || b.type_ == kFloatType); + const bool a_is_str = (a.type_ == kStringType || a.type_ == kStringIdType); + const bool b_is_str = (b.type_ == kStringType || b.type_ == kStringIdType); + if ((!a_is_num && !a_is_str) || (!b_is_num && !b_is_str)) { + ThrowFakeluaException("attempt to compare two values"); } - if (a.type_ == static_cast(VarType::Float) && b.type_ == static_cast(VarType::Float)) { - return a.data_.f < b.data_.f; - } - if (a.type_ == static_cast(VarType::Int) && b.type_ == static_cast(VarType::Float)) { - return CompareInt64Double(a.data_.i, b.data_.f) < 0; - } - if (a.type_ == static_cast(VarType::Float) && b.type_ == static_cast(VarType::Int)) { + if (a_is_num && b_is_num) { + if (a.type_ == kIntType && b.type_ == kIntType) { + return a.data_.i < b.data_.i; + } + if (a.type_ == kFloatType && b.type_ == kFloatType) { + return a.data_.f < b.data_.f; + } + if (a.type_ == kIntType) { + return CompareInt64Double(a.data_.i, b.data_.f) < 0; + } return CompareInt64Double(b.data_.i, a.data_.f) > 0; } - // fakelua 扩展:允许 number 与 string 混合比较(转换为 string) - // 标准 Lua 5.3 只允许 string-string 或 number-number,但 fakelua 支持混合 - bool a_is_str = (a.type_ == static_cast(VarType::String) || a.type_ == static_cast(VarType::StringId)); - bool b_is_str = (b.type_ == static_cast(VarType::String) || b.type_ == static_cast(VarType::StringId)); - bool a_is_num = (a.type_ == static_cast(VarType::Int) || a.type_ == static_cast(VarType::Float)); - bool b_is_num = (b.type_ == static_cast(VarType::Int) || b.type_ == static_cast(VarType::Float)); if (a_is_str && b_is_str) { - return std::string(KeyToStringView(a)) < std::string(KeyToStringView(b)); - } - // number 与 string 混合:都转换为 string比较(fakelua 扩展) - if ((a_is_num && b_is_str) || (a_is_str && b_is_num)) { - std::string sa = a_is_str ? std::string(KeyToStringView(a)) : AsVar(a).ToString(/*has_quote=*/false, /*has_postfix=*/false); - std::string sb = b_is_str ? std::string(KeyToStringView(b)) : AsVar(b).ToString(/*has_quote=*/false, /*has_postfix=*/false); - return sa < sb; + return KeyToStringView(a) < KeyToStringView(b); } - // 其他类型组合(bool 等)抛出异常 - ThrowFakeluaException("attempt to compare two values"); - return false;// unreachable + // Deterministic strict weak ordering across mixed numbers and strings: numbers < strings. + return a_is_num; }; - std::stable_sort(vec.begin(), vec.end(), default_comp); + SafeMergeSort(vec, default_comp); } for (int64_t i = 0; i < len; ++i) { diff --git a/src/native/table/native_table.h b/src/native/table/native_table.h index a18edf5c..6a1c8390 100644 --- a/src/native/table/native_table.h +++ b/src/native/table/native_table.h @@ -24,6 +24,7 @@ class TableHelper { static void SetTableInt(State *s, CVar tbl, int64_t idx, CVar val); static void SetTableStrId(State *s, CVar tbl, const char *str_key, CVar val); static void SetTableStrId(State *s, CVar tbl, std::string_view str_key, CVar val); + static void SetTableTempStr(State *s, CVar tbl, std::string_view key, CVar val); // 任意类型键的写入。键会先做浮点归一化,再按与 JIT 侧一致的哈希布局落槽。 static void SetTable(State *s, CVar tbl, CVar key, CVar val); // 分配一张空表(init 期间走 const arena 并打 CONST_FLAG,其余时候走 temp arena)。 diff --git a/src/native/timer/native_timer.cpp b/src/native/timer/native_timer.cpp index 5884bd4d..b4c90718 100644 --- a/src/native/timer/native_timer.cpp +++ b/src/native/timer/native_timer.cpp @@ -6,29 +6,41 @@ #include "var/var.h" #include "var/var_string.h" +#include #include +#include #include #include #include -#include #include namespace fakelua::timer { // 每个 State 一份定时器状态(避免跨 VM 串数据) +struct TimerEntry { + std::string cb; + JITType cb_jit = JIT_TCC; +}; + +struct PendingTimer { + HeapTimer::TimerId id = 0; + TimerEntry entry; +}; + struct TimerState { HeapTimer heap; - // timer id → Lua 回调函数名(定时器到期时按函数名派发,不存闭包) - std::unordered_map callbacks; + // timer id → Lua 回调函数名及登记引擎(定时器到期时按函数名派发,不存闭包) + std::unordered_map callbacks; + std::deque ready_queue; // 心跳(周期性,永不自动删除) std::string heartbeat_cb; // 心跳回调函数名 + JITType heartbeat_jit = JIT_TCC; // 登记心跳时的脚本引擎 HeapTimer::TimePoint heartbeat_next{};// 下次触发时间 uint32_t heartbeat_interval_ms = 0; // 心跳间隔 bool heartbeat_active = false; // 是否已注册心跳 bool in_tick = false; - std::unordered_set cancelled_this_tick; }; // 每个 State 一份,随 State 销毁。放在 State 上而不是这里的 static map:后者是全进程 @@ -98,38 +110,12 @@ static CVar TimerRegisterObjMethods(State *s, CVar *args, int n) { // C++ → Lua 回调派发(核心:按函数名查找,不存闭包) // 与 net 模块 call_lua_event 同款机制,type = "timer" -static CVar CallLuaTimerEvent(State *state, const std::string &func_name, HeapTimer::TimerId id) { - if (func_name.empty()) return CVar{static_cast(VarType::Nil)}; - - // 优先查找 JIT 编译的 Lua 函数 - auto func = state->GetVM().GetFunction(func_name); - void *addr = nullptr; - JITType jit_type = JIT_TCC; - if (!func.Empty()) { - addr = func.GetAddr(JIT_TCC); - if (!addr) { - addr = func.GetAddr(JIT_GCC); - jit_type = JIT_GCC; - } - } - - if (addr) { - // 构造参数: (type="timer", timer_id) - CVar args[2]; - args[0] = inter::NativeToFakeluaString(state, "timer"); - args[1] = inter::NativeToFakeluaInt(state, static_cast(id)); - return inter::DispatchCall(state, addr, args, 2, jit_type); - } else { - // 回退:尝试原生函数 - auto *entry = state->GetVM().FindNativeFunction(func_name); - if (entry && entry->callback) { - CVar args[2]; - args[0] = inter::NativeToFakeluaString(state, "timer"); - args[1] = inter::NativeToFakeluaInt(state, static_cast(id)); - return entry->callback(state, args, 2); - } - } - return CVar{static_cast(VarType::Nil)}; +static CVar CallLuaTimerEvent(State *state, const std::string &func_name, HeapTimer::TimerId id, JITType preferred_jit) { + if (!state || func_name.empty()) return CVar{static_cast(VarType::Nil)}; + CVar args[2]; + args[0] = inter::NativeToFakeluaString(state, "timer"); + args[1] = inter::NativeToFakeluaInt(state, static_cast(id)); + return DispatchNamedLuaCallback(state, func_name, args, 2, preferred_jit); } // 原生函数实现 @@ -170,7 +156,7 @@ static CVar TimerSet(State *s, CVar *args, int n) { LOG_ERROR(s, "timer", "timer.set failed: heap full (delay_ms={})", delay_val); return inter::NativeToFakeluaNil(s); } - ts.callbacks[id] = std::move(fname); + ts.callbacks[id] = TimerEntry{std::move(fname), s->CurrentJit()}; LOG_DEBUG(s, "timer", "timer.set: id={} delay_ms={}", id, delay_val); return inter::NativeToFakeluaInt(s, static_cast(id)); } @@ -189,7 +175,13 @@ static CVar TimerDel(State *s, CVar *args, int n) { auto &ts = GetTimerState(s); bool ok = ts.heap.Del(id); if (ts.callbacks.erase(id) > 0) ok = true; - if (ts.in_tick) ts.cancelled_this_tick.insert(id); + for (auto it = ts.ready_queue.begin(); it != ts.ready_queue.end(); ++it) { + if (it->id == id) { + ts.ready_queue.erase(it); + ok = true; + break; + } + } LOG_DEBUG(s, "timer", "timer.del: id={} ok={}", id, ok); return inter::NativeToFakeluaBool(s, ok); } @@ -203,45 +195,41 @@ void TickAll(State *s) { auto &ts = *ts_ptr; if (ts.in_tick) return; - ts.in_tick = true; - ts.cancelled_this_tick.clear(); - - try { - // 1) 一次性定时器:先把本批到期回调全部摘掉再派发,避免迭代中改 map; - // 同一批里 timer.del 的 id 记入 cancelled,不再触发。 - auto expired = ts.heap.Update(); - std::vector> to_fire; - to_fire.reserve(expired.size()); - for (auto id: expired) { - auto it = ts.callbacks.find(id); - if (it != ts.callbacks.end()) { - to_fire.emplace_back(id, std::move(it->second)); - ts.callbacks.erase(it); - } - } - for (auto &[id, cb]: to_fire) { - if (ts.cancelled_this_tick.count(id)) continue; - LOG_DEBUG(s, "timer", "timer.fire: id={}", id); - CallLuaTimerEvent(s, cb, id); + struct InTickGuard { + bool &in_tick; + ~InTickGuard() { + in_tick = false; } + } guard{ts.in_tick}; + ts.in_tick = true; - // 2) 心跳:先推进下一跳再回调,避免回调里嵌套 runtime.tick() 栈溢出 - if (ts.heartbeat_active && now >= ts.heartbeat_next) { - std::string cb = ts.heartbeat_cb; - ts.heartbeat_next += std::chrono::milliseconds(ts.heartbeat_interval_ms); - if (ts.heartbeat_next < now) { - ts.heartbeat_next = now + std::chrono::milliseconds(ts.heartbeat_interval_ms); - } - CallLuaTimerEvent(s, cb, 0); + // 1) 一次性定时器:把本轮新到期的回调迁入持久 ready_queue,逐条弹出派发; + // 若某条回调抛异常(例如外层 pcall 捕获),未派发的到期定时器仍留在 ready_queue,不会静默丢失。 + auto expired = ts.heap.Update(); + for (auto id: expired) { + auto it = ts.callbacks.find(id); + if (it != ts.callbacks.end()) { + ts.ready_queue.push_back(PendingTimer{id, std::move(it->second)}); + ts.callbacks.erase(it); } - } catch (...) { - ts.in_tick = false; - ts.cancelled_this_tick.clear(); - throw; + } + while (!ts.ready_queue.empty()) { + PendingTimer cur = std::move(ts.ready_queue.front()); + ts.ready_queue.pop_front(); + LOG_DEBUG(s, "timer", "timer.fire: id={}", cur.id); + CallLuaTimerEvent(s, cur.entry.cb, cur.id, cur.entry.cb_jit); } - ts.in_tick = false; - ts.cancelled_this_tick.clear(); + // 2) 心跳:先推进下一跳再回调,避免回调里嵌套 runtime.tick() 栈溢出 + if (ts.heartbeat_active && now >= ts.heartbeat_next) { + std::string cb = ts.heartbeat_cb; + JITType cb_jit = ts.heartbeat_jit; + ts.heartbeat_next += std::chrono::milliseconds(ts.heartbeat_interval_ms); + if (ts.heartbeat_next < now) { + ts.heartbeat_next = now + std::chrono::milliseconds(ts.heartbeat_interval_ms); + } + CallLuaTimerEvent(s, cb, 0, cb_jit); + } } // timer.set_heartbeat(interval_ms, func_name) — 注册周期性心跳,永不自动删除 @@ -274,6 +262,7 @@ static CVar TimerSetHeartbeat(State *s, CVar *args, int n) { auto &ts = GetTimerState(s); ts.heartbeat_cb = std::move(fname); + ts.heartbeat_jit = s->CurrentJit(); ts.heartbeat_interval_ms = static_cast(interval_val); ts.heartbeat_next = HeapTimer::Clock::now() + std::chrono::milliseconds(ts.heartbeat_interval_ms); ts.heartbeat_active = true; diff --git a/src/native/tls_util.h b/src/native/tls_util.h index 235d5609..aeb7be97 100644 --- a/src/native/tls_util.h +++ b/src/native/tls_util.h @@ -2,8 +2,16 @@ #include #include +#include #include +#if defined(_WIN32) +#include +#include +#else +#include +#endif + namespace fakelua::tls { inline SSL_CTX *MakeClientContext(bool verify, const std::string &ca) { @@ -18,7 +26,10 @@ inline SSL_CTX *MakeClientContext(bool verify, const std::string &ca) { return nullptr; } } else { - SSL_CTX_set_default_verify_paths(ctx); + if (SSL_CTX_set_default_verify_paths(ctx) != 1) { + SSL_CTX_free(ctx); + return nullptr; + } } } else { SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, nullptr); @@ -41,11 +52,6 @@ inline SSL_CTX *MakeServerContext(const std::string &cert, const std::string &ke return ctx; } -inline bool SetSniHostname(SSL *ssl, const std::string &host) { - if (!ssl || host.empty()) return true; - return SSL_set_tlsext_host_name(ssl, host.c_str()) == 1; -} - inline std::string HostnameWithoutPort(std::string host) { if (!host.empty() && host.front() == '[') { auto rb = host.find(']'); @@ -58,4 +64,31 @@ inline std::string HostnameWithoutPort(std::string host) { return host; } +inline bool IsIpLiteral(const std::string &host) { + if (host.empty()) return false; + unsigned char buf[16]{}; + return inet_pton(AF_INET, host.c_str(), buf) == 1 || inet_pton(AF_INET6, host.c_str(), buf) == 1; +} + +inline bool SetSniHostname(SSL *ssl, const std::string &host) { + if (!ssl) return false; + const std::string clean = HostnameWithoutPort(host); + if (clean.empty() || IsIpLiteral(clean)) return true; + return SSL_set_tlsext_host_name(ssl, clean.c_str()) == 1; +} + +inline bool ConfigurePeerVerification(SSL *ssl, const std::string &host, bool verify) { + if (!ssl) return false; + const std::string clean = HostnameWithoutPort(host); + if (!SetSniHostname(ssl, clean)) return false; + if (!verify) return true; + if (clean.empty()) return false; + if (IsIpLiteral(clean)) { + X509_VERIFY_PARAM *param = SSL_get0_param(ssl); + return param != nullptr && X509_VERIFY_PARAM_set1_ip_asc(param, clean.c_str()) == 1; + } + SSL_set_hostflags(ssl, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS); + return SSL_set1_host(ssl, clean.c_str()) == 1; +} + }// namespace fakelua::tls diff --git a/src/native/toml/native_toml.cpp b/src/native/toml/native_toml.cpp index 133432be..6a57b42d 100644 --- a/src/native/toml/native_toml.cpp +++ b/src/native/toml/native_toml.cpp @@ -15,14 +15,88 @@ namespace fakelua::toml { +static constexpr int kMaxTomlDepth = 64; + +static void CheckTomlTextNesting(const std::string &str) { + int depth = 0; + enum class StrMode { None, Basic, Literal, MultiBasic, MultiLiteral }; + StrMode mode = StrMode::None; + for (size_t i = 0; i < str.size(); ++i) { + const char c = str[i]; + if (mode == StrMode::Basic) { + if (c == '\\' && i + 1 < str.size()) { + ++i; + } else if (c == '"' || c == '\n') { + mode = StrMode::None; + } + continue; + } + if (mode == StrMode::Literal) { + if (c == '\'' || c == '\n') { + mode = StrMode::None; + } + continue; + } + if (mode == StrMode::MultiBasic) { + if (c == '\\' && i + 1 < str.size()) { + ++i; + } else if (c == '"' && i + 2 < str.size() && str[i + 1] == '"' && str[i + 2] == '"') { + i += 2; + mode = StrMode::None; + } + continue; + } + if (mode == StrMode::MultiLiteral) { + if (c == '\'' && i + 2 < str.size() && str[i + 1] == '\'' && str[i + 2] == '\'') { + i += 2; + mode = StrMode::None; + } + continue; + } + if (c == '#') { + while (i + 1 < str.size() && str[i + 1] != '\n') ++i; + continue; + } + if (c == '"') { + if (i + 2 < str.size() && str[i + 1] == '"' && str[i + 2] == '"') { + i += 2; + mode = StrMode::MultiBasic; + } else { + mode = StrMode::Basic; + } + continue; + } + if (c == '\'') { + if (i + 2 < str.size() && str[i + 1] == '\'' && str[i + 2] == '\'') { + i += 2; + mode = StrMode::MultiLiteral; + } else { + mode = StrMode::Literal; + } + continue; + } + if (c == '[' || c == '{') { + ++depth; + if (depth > kMaxTomlDepth) { + ThrowFakeluaException("TOML decode: nesting too deep"); + } + } else if ((c == ']' || c == '}') && depth > 0) { + --depth; + } + } +} + // ::toml::node → CVar -static CVar NodeToLua(State *s, const ::toml::node &node) { +static CVar NodeToLua(State *s, const ::toml::node &node, int depth = 0) { + if (depth > kMaxTomlDepth) { + ThrowFakeluaException("TOML decode: nesting too deep"); + } if (node.is_table()) { CVar tbl = table::TableHelper::CreateTable(s); auto *t = node.as_table(); if (t) { for (auto it = t->begin(); it != t->end(); ++it) { - table::TableHelper::SetTableStrId(s, tbl, std::string(it->first.str()).c_str(), NodeToLua(s, it->second)); + table::TableHelper::SetTableTempStr(s, tbl, it->first.str(), NodeToLua(s, it->second, depth + 1)); } } return tbl; @@ -33,7 +107,7 @@ static CVar NodeToLua(State *s, const ::toml::node &node) { if (arr) { size_t idx = 1; for (auto it = arr->begin(); it != arr->end(); ++it, ++idx) { - table::TableHelper::SetTableInt(s, tbl, static_cast(idx), NodeToLua(s, *it)); + table::TableHelper::SetTableInt(s, tbl, static_cast(idx), NodeToLua(s, *it, depth + 1)); } } return tbl; @@ -78,7 +152,6 @@ static CVar NodeToLua(State *s, const ::toml::node &node) { } // CVar → ::toml::table/array -static const int kMaxTomlDepth = 64; static ::toml::value MakeTomlFloat(double f) { return ::toml::value(f); @@ -160,8 +233,9 @@ static CVar TomlDecode(State *s, CVar *args, int n) { CVar a0 = inter::GetNativeArg(s, args, n, 0); std::string str = inter::FakeluaToNativeString(s, a0); try { + CheckTomlTextNesting(str); auto result = ::toml::parse(str); - return NodeToLua(s, result); + return NodeToLua(s, result, 0); } catch (const ::toml::parse_error &e) { ThrowFakeluaException(std::format("TOML parse error: {}", e.description())); } diff --git a/src/native/url/native_url.cpp b/src/native/url/native_url.cpp index f421dd40..5f11e80e 100644 --- a/src/native/url/native_url.cpp +++ b/src/native/url/native_url.cpp @@ -21,8 +21,8 @@ static CVar TableGetStr(State *s, CVar tbl, const char *key) { return table::TableHelper::GetTableStrId(s, tbl, key); } -static void SetStr(State *s, CVar tbl, const char *key, std::string_view val) { - table::TableHelper::SetTableStrId(s, tbl, key, inter::NativeToFakeluaString(s, std::string(val))); +static void SetStr(State *s, CVar tbl, std::string_view key, std::string_view val) { + table::TableHelper::SetTableTempStr(s, tbl, key, inter::NativeToFakeluaString(s, std::string(val))); } static std::string EncodeView(std::string_view s) { @@ -44,10 +44,10 @@ static CVar ParamsToTable(State *s, urls::params_view params) { for (auto p: params) { std::string key(p.key); if (!p.has_value) { - SetStr(s, tbl, key.c_str(), ""); + SetStr(s, tbl, key, ""); continue; } - SetStr(s, tbl, key.c_str(), p.value); + SetStr(s, tbl, key, p.value); } return tbl; } @@ -70,13 +70,13 @@ static CVar UrlParse(State *s, CVar *args, int n) { if (u.has_password()) SetStr(s, tbl, "password", u.password()); if (u.has_authority()) SetStr(s, tbl, "host", u.host()); if (u.has_port()) { - table::TableHelper::SetTableStrId(s, tbl, "port", inter::NativeToFakeluaInt(s, static_cast(u.port_number()))); + table::TableHelper::SetTableTempStr(s, tbl, "port", inter::NativeToFakeluaInt(s, static_cast(u.port_number()))); SetStr(s, tbl, "port_str", u.port()); } SetStr(s, tbl, "path", u.path()); if (u.has_query()) { SetStr(s, tbl, "query", u.query()); - table::TableHelper::SetTableStrId(s, tbl, "params", ParamsToTable(s, u.params())); + table::TableHelper::SetTableTempStr(s, tbl, "params", ParamsToTable(s, u.params())); } if (u.has_fragment()) SetStr(s, tbl, "fragment", u.fragment()); SetStr(s, tbl, "href", u.buffer()); diff --git a/src/native/xml/native_xml.cpp b/src/native/xml/native_xml.cpp index da2d945b..bb2460b6 100644 --- a/src/native/xml/native_xml.cpp +++ b/src/native/xml/native_xml.cpp @@ -33,7 +33,7 @@ static CVar NodeToLua(State *s, pugi::xml_node node, int depth) { // Attributes → "_attr_attrname" (prefix avoids illegal C identifiers) for (auto attr = node.first_attribute(); attr; attr = attr.next_attribute()) { - table::TableHelper::SetTableStrId(s, tbl, std::format("_attr_{}", attr.name()).c_str(), inter::NativeToFakeluaString(s, std::string(attr.value()))); + table::TableHelper::SetTableTempStr(s, tbl, std::format("_attr_{}", attr.name()), inter::NativeToFakeluaString(s, std::string(attr.value()))); } // Children: group element children by tag name; text → "_text" @@ -77,16 +77,16 @@ static CVar NodeToLua(State *s, pugi::xml_node node, int depth) { // Concatenate all text fragments std::string combined; for (auto &n: g.nodes) combined += n.value(); - table::TableHelper::SetTableStrId(s, tbl, "_text", inter::NativeToFakeluaString(s, combined)); + table::TableHelper::SetTableTempStr(s, tbl, "_text", inter::NativeToFakeluaString(s, combined)); } else if (g.nodes.size() == 1) { - table::TableHelper::SetTableStrId(s, tbl, g.tag.c_str(), NodeToLua(s, g.nodes[0], depth + 1)); + table::TableHelper::SetTableTempStr(s, tbl, g.tag, NodeToLua(s, g.nodes[0], depth + 1)); } else { // Multiple same-tag siblings → array CVar arr = table::TableHelper::CreateTable(s); for (size_t i = 0; i < g.nodes.size(); i++) { table::TableHelper::SetTableInt(s, arr, static_cast(i + 1), NodeToLua(s, g.nodes[i], depth + 1)); } - table::TableHelper::SetTableStrId(s, tbl, g.tag.c_str(), arr); + table::TableHelper::SetTableTempStr(s, tbl, g.tag, arr); } } diff --git a/src/native/yaml/native_yaml.cpp b/src/native/yaml/native_yaml.cpp index c87f01c6..be34c2a5 100644 --- a/src/native/yaml/native_yaml.cpp +++ b/src/native/yaml/native_yaml.cpp @@ -79,63 +79,138 @@ static CVar ScalarToLua(State *s, const std::string &str) { } static constexpr int kMaxYamlDepth = 64; +static constexpr size_t kMaxYamlNodes = 100000; static void CheckYamlTextNesting(const std::string &str) { - int depth = 0; + int flow_depth = 0; bool in_single = false; bool in_double = false; + bool at_node_start = true; + size_t col = 0; + std::vector block_indents; + block_indents.reserve(static_cast(kMaxYamlDepth) + 4); + + auto push_block_indent = [&](size_t c_pos) { + while (!block_indents.empty() && block_indents.back() >= c_pos) { + block_indents.pop_back(); + } + block_indents.push_back(c_pos); + if (block_indents.size() + static_cast(flow_depth) > static_cast(kMaxYamlDepth * 2)) { + ThrowFakeluaException("yaml.decode: nesting too deep"); + } + }; + for (size_t i = 0; i < str.size(); ++i) { const char c = str[i]; if (in_single) { - if (c == '\'') { + if (c == '\n') { + col = 0; + } else if (c == '\'') { if (i + 1 < str.size() && str[i + 1] == '\'') { ++i; + col += 2; } else { in_single = false; + ++col; } + } else if (c != '\r') { + ++col; } continue; } if (in_double) { + if (c == '\n') { + col = 0; + continue; + } if (c == '\\' && i + 1 < str.size()) { ++i; + col += 2; continue; } if (c == '"') { in_double = false; } + if (c != '\r') { + ++col; + } + continue; + } + if (c == '\r') { + continue; + } + if (c == '\n') { + col = 0; + if (flow_depth == 0) { + at_node_start = true; + } continue; } if (c == '#') { - while (i < str.size() && str[i] != '\n') { + while (i + 1 < str.size() && str[i + 1] != '\n') { ++i; } continue; } + if (flow_depth == 0 && at_node_start) { + if (c == ' ' || c == '\t') { + ++col; + continue; + } + if ((c == '-' || c == '?') && + (i + 1 == str.size() || str[i + 1] == ' ' || str[i + 1] == '\t' || str[i + 1] == '\r' || str[i + 1] == '\n')) { + push_block_indent(col); + ++col; + continue; + } + if (c == '&' || c == '!') { + while (i + 1 < str.size() && str[i + 1] != ' ' && str[i + 1] != '\t' && str[i + 1] != '\r' && str[i + 1] != '\n' && + str[i + 1] != '[' && str[i + 1] != '{' && str[i + 1] != ',') { + ++i; + ++col; + } + ++col; + continue; + } + push_block_indent(col); + at_node_start = false; + } if (c == '\'') { in_single = true; + ++col; continue; } if (c == '"') { in_double = true; + ++col; + continue; + } + if (flow_depth == 0 && c == ':' && + (i + 1 == str.size() || str[i + 1] == ' ' || str[i + 1] == '\t' || str[i + 1] == '\r' || str[i + 1] == '\n')) { + at_node_start = true; + ++col; continue; } if (c == '[' || c == '{') { - ++depth; - if (depth > kMaxYamlDepth) { + ++flow_depth; + if (flow_depth > kMaxYamlDepth) { ThrowFakeluaException("yaml.decode: nesting too deep"); } - } else if ((c == ']' || c == '}') && depth > 0) { - --depth; + } else if ((c == ']' || c == '}') && flow_depth > 0) { + --flow_depth; } + ++col; } } // YAML::Node → CVar -static CVar NodeToLua(State *s, const YAML::Node &node, int depth, std::vector &stack) { +static CVar NodeToLua(State *s, const YAML::Node &node, int depth, std::vector &stack, size_t &visited_nodes) { if (depth > kMaxYamlDepth) { ThrowFakeluaException("yaml.decode: nesting too deep"); } + if (++visited_nodes > kMaxYamlNodes) { + ThrowFakeluaException("yaml.decode: node limit exceeded"); + } if (!node.IsDefined() || node.IsNull()) { return inter::NativeToFakeluaNil(s); } @@ -161,15 +236,18 @@ static CVar NodeToLua(State *s, const YAML::Node &node, int depth, std::vector(idx), NodeToLua(s, *it, depth + 1, stack)); + table::TableHelper::SetTableInt(s, tbl, static_cast(idx), NodeToLua(s, *it, depth + 1, stack, visited_nodes)); } return tbl; } if (node.IsMap()) { CVar tbl = table::TableHelper::CreateTable(s); for (auto it = node.begin(); it != node.end(); ++it) { + if (++visited_nodes > kMaxYamlNodes) { + ThrowFakeluaException("yaml.decode: node limit exceeded"); + } std::string key = it->first.as(); - table::TableHelper::SetTableStrId(s, tbl, key.c_str(), NodeToLua(s, it->second, depth + 1, stack)); + table::TableHelper::SetTableTempStr(s, tbl, key, NodeToLua(s, it->second, depth + 1, stack, visited_nodes)); } return tbl; } @@ -266,7 +344,8 @@ static CVar YamlDecode(State *s, CVar *args, int n) { CheckYamlTextNesting(str); YAML::Node root = YAML::Load(str); std::vector stack; - return NodeToLua(s, root, 0, stack); + size_t visited_nodes = 0; + return NodeToLua(s, root, 0, stack, visited_nodes); } catch (const YAML::Exception &e) { ThrowFakeluaException(std::format("YAML parse error: {}", e.what())); } diff --git a/src/state/fakelua.cpp b/src/state/fakelua.cpp index 98e7d94c..77aaeee9 100644 --- a/src/state/fakelua.cpp +++ b/src/state/fakelua.cpp @@ -8,6 +8,7 @@ #include "native/io/native_io.h" #include "native/mysql/native_mysql.h" #include "native/net/native_net.h" +#include "native/object/native_object.h" #include "native/redis/native_redis.h" #include "native/sqlite/native_sqlite.h" #include "native/table/native_table.h" @@ -284,9 +285,8 @@ std::string CVarToString(const CVar &v, const char *default_val) { return default_val != nullptr ? std::string(default_val) : std::string(); } -// VarToVi: read CVar into VarInterface* bridge type. Tables are read-only — -// no VarTable methods needed, just direct field access on the C struct. -static void VarToVi(State *state, const CVar &src, VarInterface *dst) { +// VarToVi: read CVar into VarInterface* bridge type. +static void VarToVi(State *state, const CVar &src, VarInterface *dst, std::unordered_set &active_tables) { const auto &var_val = AsVar(src); DEBUG_ASSERT(var_val.Type() >= VarType::Min && var_val.Type() <= VarType::Max); switch (var_val.Type()) { @@ -308,21 +308,52 @@ static void VarToVi(State *state, const CVar &src, VarInterface *dst) { break; case VarType::Table: { const auto table = var_val.GetTable(); + if (!table) { + dst->ViSetNil(); + break; + } + if (!active_tables.insert(table).second) { + ThrowFakeluaException("VarToVi failed: cyclic table is not supported"); + } + struct ActiveTableGuard { + std::unordered_set &set; + const VarTable *tbl; + ~ActiveTableGuard() { + set.erase(tbl); + } + } active_guard{active_tables, table}; + + EnsureNativeSpecSnapshot(table); + const uint32_t count = table->count_; std::vector> kvs; + struct KvsGuard { + std::vector> &items; + ~KvsGuard() { + for (auto &[k, v]: items) { + delete k; + delete v; + } + } + } kvs_guard{kvs}; kvs.reserve(table->spec_count + table->arr_size_ + count); const auto &new_func = GetVarInterfaceNewFunc(state); - auto alloc_vi = [&new_func]() -> VarInterface * { return new_func ? new_func() : new SimpleVarImpl(); }; + auto alloc_vi = [&new_func]() -> std::unique_ptr { + return std::unique_ptr(new_func ? new_func() : new SimpleVarImpl()); + }; - if (table->spec_count > 0) { + if (table->spec_count > 0 && table->spec_keys && table->spec_vals) { const auto *sk = reinterpret_cast(table->spec_keys); const auto *sv = reinterpret_cast(table->spec_vals); for (uint32_t i = 0; i < table->spec_count; ++i) { + if (sk[i].Type() == VarType::Nil || sv[i].Type() == VarType::Nil) { + continue; + } auto key_item = alloc_vi(); auto val_item = alloc_vi(); - VarToVi(state, sk[i], key_item); - VarToVi(state, sv[i], val_item); - kvs.emplace_back(key_item, val_item); + VarToVi(state, sk[i], key_item.get(), active_tables); + VarToVi(state, sv[i], val_item.get(), active_tables); + kvs.emplace_back(key_item.release(), val_item.release()); } } for (uint32_t i = 0; i < table->arr_size_; ++i) { @@ -333,33 +364,29 @@ static void VarToVi(State *state, const CVar &src, VarInterface *dst) { auto key_item = alloc_vi(); auto val_item = alloc_vi(); key_item->ViSetInt(static_cast(i) + 1); - VarToVi(state, table->arr_[i], val_item); - kvs.emplace_back(key_item, val_item); + VarToVi(state, table->arr_[i], val_item.get(), active_tables); + kvs.emplace_back(key_item.release(), val_item.release()); } if (const uint32_t *al = table->active_list_; al == nullptr) { for (uint32_t i = 0; i < count; ++i) { const auto &e = table->quick_data_[i]; auto key_item = alloc_vi(); auto val_item = alloc_vi(); - VarToVi(state, e.key, key_item); - VarToVi(state, e.val, val_item); - kvs.emplace_back(key_item, val_item); + VarToVi(state, e.key, key_item.get(), active_tables); + VarToVi(state, e.val, val_item.get(), active_tables); + kvs.emplace_back(key_item.release(), val_item.release()); } } else { for (uint32_t i = 0; i < count; ++i) { const auto &e = table->nodes_[al[i]].entry; auto key_item = alloc_vi(); auto val_item = alloc_vi(); - VarToVi(state, e.key, key_item); - VarToVi(state, e.val, val_item); - kvs.emplace_back(key_item, val_item); + VarToVi(state, e.key, key_item.get(), active_tables); + VarToVi(state, e.val, val_item.get(), active_tables); + kvs.emplace_back(key_item.release(), val_item.release()); } } dst->ViSetTable(kvs); - for (auto &[k, v]: kvs) { - delete k; - delete v; - } break; } case VarType::Closure: @@ -373,9 +400,10 @@ static void VarToVi(State *state, const CVar &src, VarInterface *dst) { VarInterface *FakeluaToNativeObj(State *state, CVar val) { const auto &new_func = GetVarInterfaceNewFunc(state); - const auto ret = new_func ? new_func() : new SimpleVarImpl(); - VarToVi(state, val, ret); - return ret; + std::unique_ptr ret(new_func ? new_func() : new SimpleVarImpl()); + std::unordered_set active_tables; + VarToVi(state, val, ret.get(), active_tables); + return ret.release(); } CVar NativeToFakeluaNativeObject(State *state, const NativeObject *obj) { @@ -472,18 +500,21 @@ void RegisterNativeVarFunction(State *s, const std::string &name, int arg_count, return inter::NativeToFakeluaNil(state); } std::vector vi_args; + struct ViArgsGuard { + std::vector &items; + ~ViArgsGuard() { + for (auto *vi: items) { + delete vi; + } + } + } args_guard{vi_args}; vi_args.reserve(n); for (int i = 0; i < n; ++i) { CVar arg_i = inter::GetNativeArg(state, args, n, i); vi_args.push_back(inter::FakeluaToNativeObj(state, arg_i)); } - VarInterface *res_vi = safe_cb(state, vi_args); - for (auto *vi: vi_args) { - delete vi; - } - CVar ret = inter::NativeToFakeluaVarInterface(state, res_vi); - delete res_vi; - return ret; + std::unique_ptr res_vi(safe_cb(state, vi_args)); + return inter::NativeToFakeluaVarInterface(state, res_vi.get()); }); } @@ -535,24 +566,23 @@ void ThrowIfMultiCVar(const CVar &v) { static CVar DispatchCallRaw(void *addr, const CVar *arg_arr, int arg_count, VarClosure *cl); CVar DispatchCall(State *s, void *addr, const CVar *arg_arr, int arg_count, JITType type, VarClosure *cl) { - // 进入目标引擎代码:切换当前引擎上下文,使本次执行过程中调起的 native 函数 - // (含 native 对象方法桥接)能登记派回本引擎的异步回调。嵌套调用逐层保存恢复。 - State::JitContextScope jit_scope(s, type); + State::ActiveDispatchScope active_dispatch_scope(s); + const bool use_interp = cl ? IsInterpClosure(cl) : (type == JIT_INTERP); + const JITType effective_type = use_interp ? JIT_INTERP : (IsGccClosure(cl) ? JIT_GCC : type); + // 进入目标引擎代码:按闭包真实的创建引擎切换上下文(例如 table.sort / xpcall 借用 + // JIT_TCC 标记请求 setjmp 边界,但被调若是 GCC/解释器闭包,CurrentJit 仍应是真实引擎)。 + State::JitContextScope jit_scope(s, effective_type); // 本次调用期间才承认「位置槽里是当前位置」,返回后恢复主叫方的值。 LuaLocScope loc_scope(s); // 生成代码出错时 FL_LUA_POP 不会执行。深度在这里恢复;调用栈文本已留在异常里。 LuaStackScope stack_scope(s); - // 解释器闭包用 code_str magic 识别,不能看函数指针最低位:GCC 的函数指针可以是奇数。 - // type==JIT_INTERP 且 cl 为空:Call()/CallByName 直接调注册的解释器原型。 - // cl 是 TCC/GCC 闭包时即使 type 是 JIT_INTERP 也必须走 C 函数指针(解释器回调 JIT 闭包)。 - const bool use_interp = cl ? IsInterpClosure(cl) : (type == JIT_INTERP); if (use_interp) { void *proto = (cl && cl->func_ptr) ? cl->func_ptr : addr; return InterpreterExecute(s, AsInterpProto(proto), arg_arr, arg_count, cl); } - // GCC 后端产出的动态库带 .eh_frame,C++ 异常能正常穿过它的帧,不必付边界的代价。 - // TCC 把代码生成在自己的内存代码页里,没有展开表,错误只能靠边界跳回来。 - if (type == JIT_GCC) { + // GCC 后端产出的动态库带 .eh_frame,C++ 异常能正常穿过它的帧; + // 若调用方显式传 JIT_TCC 请求边界,或闭包本身来自 TCC,则保留 setjmp 边界。 + if (effective_type == JIT_GCC && type == JIT_GCC) { return DispatchCallRaw(addr, arg_arr, arg_count, cl); } return RunWithJitErrorBoundary(s, [&] { return DispatchCallRaw(addr, arg_arr, arg_count, cl); }); @@ -564,7 +594,7 @@ CVar DispatchCallClosure(State *state, VarClosure *cl, const CVar *args, int arg } // load() 返回的是源码闭包:func_ptr 为空,code_str 指向待编译文本。 if (!cl->func_ptr) { - if (cl->code_str && cl->code_str != kInterpClosureMagic) { + if (IsSourceLoadClosure(cl)) { return FlEvalLoadClosure(state, cl, arg_count, args); } ThrowFakeluaException("closure has no code"); @@ -691,6 +721,38 @@ int GetMultiCVarCount(const CVar &multi) { return static_cast(multi.data_.m->GetCount()); } +CVar GetReturnElement(State *s, const CVar &ret_var, std::size_t idx) { + if (ret_var.type_ == static_cast(VarType::Multi)) { + VarMulti *m = ret_var.data_.m; + if (m && idx < m->GetCount()) { + return m->GetVars()[idx]; + } + return NativeToFakeluaNil(s); + } + return idx == 0 ? ret_var : NativeToFakeluaNil(s); +} + +CVar UnboxFirstReturn(State *s, const CVar &ret_var) { + return GetReturnElement(s, ret_var, 0); +} + +PreservedCVarArg PreserveCVarBeforeReset(const CVar &v, bool will_reset) { + PreservedCVarArg out; + out.raw = v; + if (will_reset && v.type_ == static_cast(VarType::String) && v.data_.s != nullptr) { + out.has_saved_str = true; + out.saved_str.assign(v.data_.s->Str()); + } + return out; +} + +CVar MaterializePreservedCVar(State *s, const PreservedCVarArg &p) { + if (p.has_saved_str) { + return NativeToFakeluaStringView(s, p.saved_str); + } + return p.raw; +} + CVar GetNativeArg(State *s, CVar *args, int n, int idx) { (void) s; CVar res{static_cast(VarType::Nil)}; @@ -758,4 +820,138 @@ bool HasEntryFunction(State *s, JITType type, const std::string_view &name) { return inter::GetFuncAddr(s, type, name, argc, is_vararg) != nullptr; } +namespace { + +constexpr int kPromoteConstFlagBit = 0x1; +constexpr int kPromoteConstBoxFlagBit = 0x2; + +struct ConstPromoteMemo { + std::unordered_map tables; + std::unordered_map closures; + std::unordered_map boxes; +}; + +CVar PromoteConstBoxValueImpl(State *s, CVar val, ConstPromoteMemo &memo) { + if (!s) { + val.flag_ &= ~kPromoteConstBoxFlagBit; + return val; + } + switch (static_cast(val.type_)) { + case VarType::Nil: + case VarType::Bool: + case VarType::Int: + case VarType::Float: + case VarType::StringId: + val.flag_ &= ~kPromoteConstBoxFlagBit; + return val; + case VarType::String: { + if (!val.data_.s) { + return CVar{static_cast(VarType::Nil)}; + } + State::ConstAllocScope const_alloc(s); + CVar out{}; + out.type_ = static_cast(VarType::String); + out.flag_ = 0; + out.data_.s = VarString::AllocTemp(s, val.data_.s->Str()); + return out; + } + case VarType::Table: { + if (!val.data_.t) { + return CVar{static_cast(VarType::Nil)}; + } + if ((val.flag_ & kPromoteConstFlagBit) != 0) { + val.flag_ &= ~kPromoteConstBoxFlagBit; + return val; + } + if (NativeObject *nobj = NativeObject::Unwrap(val)) { + State::ConstAllocScope const_alloc(s); + CVar wrapped = nobj->Wrap(s); + wrapped.flag_ &= ~kPromoteConstBoxFlagBit; + return wrapped; + } + if (const auto it = memo.tables.find(val.data_.t); it != memo.tables.end()) { + return it->second; + } + State::ConstAllocScope const_alloc(s); + CVar cloned = table::TableHelper::CreateTable(s); + memo.tables.emplace(val.data_.t, cloned); + table::TableHelper::ForEachKV(val, [&](CVar k, CVar elem) { + CVar pk = PromoteConstBoxValueImpl(s, k, memo); + CVar pv = PromoteConstBoxValueImpl(s, elem, memo); + table::TableHelper::SetTable(s, cloned, pk, pv); + }); + return cloned; + } + case VarType::Closure: { + VarClosure *cl = val.data_.cl; + if (!cl) { + return CVar{static_cast(VarType::Nil)}; + } + if (const auto it = memo.closures.find(cl); it != memo.closures.end()) { + return it->second; + } + if (cl->func_ptr != nullptr && !IsInterpClosure(cl)) { + s->GetVM().RetainHandleForCodeAddr(cl->func_ptr); + } + auto &const_arena = s->GetHeap().GetAllocator(true); + const int uv_cnt = cl->upvalue_count > 0 ? cl->upvalue_count : 0; + auto *new_cl = static_cast(const_arena.Alloc(sizeof(VarClosure) + static_cast(uv_cnt) * sizeof(CVar *))); + new_cl->func_ptr = cl->func_ptr; + new_cl->upvalue_count = cl->upvalue_count; + new_cl->expected_arg_count = cl->expected_arg_count; + new_cl->is_vararg = cl->is_vararg; + new_cl->code_str = cl->code_str; + for (int i = 0; i < uv_cnt; ++i) { + new_cl->upvalues[i] = nullptr; + } + CVar out{}; + out.type_ = static_cast(VarType::Closure); + out.flag_ = 0; + out.data_.cl = new_cl; + memo.closures.emplace(cl, out); + for (int i = 0; i < uv_cnt; ++i) { + CVar *orig_box = cl->upvalues[i]; + if (!orig_box) { + continue; + } + if ((orig_box->flag_ & kPromoteConstBoxFlagBit) != 0) { + new_cl->upvalues[i] = orig_box; + continue; + } + if (const auto bit = memo.boxes.find(orig_box); bit != memo.boxes.end()) { + new_cl->upvalues[i] = bit->second; + continue; + } + auto *promoted_box = static_cast(const_arena.Alloc(sizeof(CVar))); + *promoted_box = CVar{static_cast(VarType::Nil)}; + promoted_box->flag_ = kPromoteConstBoxFlagBit; + memo.boxes.emplace(orig_box, promoted_box); + CVar inner = PromoteConstBoxValueImpl(s, *orig_box, memo); + inner.flag_ |= kPromoteConstBoxFlagBit; + *promoted_box = inner; + new_cl->upvalues[i] = promoted_box; + } + return out; + } + default: + val.flag_ &= ~kPromoteConstBoxFlagBit; + return val; + } +} + +}// namespace + +CVar PromoteConstBoxValue(State *state, CVar val) { + ConstPromoteMemo memo; + return PromoteConstBoxValueImpl(state, val, memo); +} + +#if defined(__GNUC__) || defined(__clang__) +extern "C" __attribute__((used)) CVar FakeluaPromoteConstBoxValue(State *state, CVar val) { +#else +extern "C" CVar FakeluaPromoteConstBoxValue(State *state, CVar val) { +#endif + return GuardJitEntry(state, [&] { return PromoteConstBoxValue(state, val); }); +} + }// namespace fakelua diff --git a/src/state/heap.cpp b/src/state/heap.cpp index 31b444e9..befa0ced 100644 --- a/src/state/heap.cpp +++ b/src/state/heap.cpp @@ -37,15 +37,17 @@ void *HeapAllocator::Alloc(size_t size) { } } - // 仅检查 size 本身是否超出块容量。padding 在同一块内才有意义, - // 跨块时 offset 会重置为 0 导致 padding 为 0,因此不参与上限判断。 - if (UNLIKELY(size > BLOCK_SIZE)) { + // 保持 current_block_offset_ 与 slot_->curr 始终按 alignment(16 字节)对齐, + // 否则 C++ 侧分配任意非 16 倍数字节后,JIT 快速路径 FlFastAlloc 直接使用 hs->curr + // 会发出非对齐的 VarTable / CVar / VarClosure 指针。 + const size_t aligned_size = ((size == 0 ? 1 : size) + alignment - 1) & ~(alignment - 1); + if (UNLIKELY(aligned_size > BLOCK_SIZE)) { ThrowFakeluaException(std::format("Alloc failed, requested size {} exceeds block size {}", size, BLOCK_SIZE)); } size_t padding = (alignment - (current_block_offset_ % alignment)) % alignment; - if (UNLIKELY(current_block_offset_ + padding + size > BLOCK_SIZE)) { + if (UNLIKELY(current_block_offset_ + padding + aligned_size > BLOCK_SIZE)) { current_block_offset_ = 0; current_block_index_++; padding = 0; @@ -68,7 +70,7 @@ void *HeapAllocator::Alloc(size_t size) { current_block_offset_ += padding; void *ptr = static_cast(blocks_[current_block_index_]) + current_block_offset_; - current_block_offset_ += size; + current_block_offset_ += aligned_size; if (slot_) { slot_->curr = static_cast(blocks_[current_block_index_]) + current_block_offset_; slot_->end = static_cast(blocks_[current_block_index_]) + BLOCK_SIZE; @@ -95,7 +97,15 @@ void HeapAllocator::Reset() { } size_t HeapAllocator::Size() const { - return current_block_index_ * BLOCK_SIZE + current_block_offset_; + size_t offset = current_block_offset_; + if (slot_ && slot_->curr && current_block_index_ < blocks_.size()) { + const char *base = static_cast(blocks_[current_block_index_]); + const char *end = base + BLOCK_SIZE; + if (slot_->curr >= base && slot_->curr <= end) { + offset = static_cast(slot_->curr - base); + } + } + return current_block_index_ * BLOCK_SIZE + offset; } }// namespace fakelua diff --git a/src/state/state.h b/src/state/state.h index 358fe56c..8670b29f 100644 --- a/src/state/state.h +++ b/src/state/state.h @@ -81,9 +81,53 @@ class State { lua_depth_ = 0; lua_frames_[kMaxLuaStack] = LuaFrame{}; ClearSpecThrow(); + ++arena_epoch_; // 函数地址表跟着已加载的 JIT 镜像走,由镜像卸载时按 owner 清理;顶层 Call 的 Reset 不能清空。 } + [[nodiscard]] uint64_t ArenaEpoch() const { + return arena_epoch_; + } + + void RetainJitHandle(JITHandlePtr handle) { + if (handle) { + retained_jit_handles_.push_back(std::move(handle)); + } + } + + [[nodiscard]] bool InActiveDispatch() const { + return active_dispatch_depth_ > 0; + } + + void DeferJitHandleUnload(JITHandlePtr handle) { + if (handle) { + deferred_unload_handles_.push_back(std::move(handle)); + } + } + + uint64_t NextAnonFnSeq() { + return ++next_anon_fn_seq_; + } + + struct ActiveDispatchScope { + explicit ActiveDispatchScope(State *s) : s_(s) { + if (s_) { + ++s_->active_dispatch_depth_; + } + } + ~ActiveDispatchScope() { + if (s_ && --s_->active_dispatch_depth_ == 0 && !s_->deferred_unload_handles_.empty()) { + auto to_release = std::move(s_->deferred_unload_handles_); + s_->deferred_unload_handles_.clear(); + } + } + ActiveDispatchScope(const ActiveDispatchScope &) = delete; + ActiveDispatchScope &operator=(const ActiveDispatchScope &) = delete; + + private: + State *s_; + }; + [[nodiscard]] const StateConfig &GetStateConfig() const { return config_; } @@ -284,6 +328,10 @@ class State { return interp_const_alloc_; } + [[nodiscard]] const bool *InterpConstAllocPtr() const { + return &interp_const_alloc_; + } + // 分配会跨帧存活的 Lua 值(表、字符串、闭包等)。init 期间切到常量堆。 HeapAllocator &GetValueAllocator() { return heap_.GetAllocator(interp_const_alloc_); @@ -412,6 +460,7 @@ class State { FlHeapSlot temp_heap_slot_; FlHeapSlot const_heap_slot_; bool interp_const_alloc_ = false; + uint64_t arena_epoch_ = 1; // 当前执行引擎,初值 TCC(无 Lua 调用栈的边界场景,与 kNativeCallbackJit 一致)。 JITType current_jit_ = JIT_TCC; int reentrant_count_ = 0; @@ -419,7 +468,11 @@ class State { Compiler compiler_; Heap heap_; ConstString const_string_; - Vm vm_; + Vm vm_{this}; + std::vector retained_jit_handles_; + std::vector deferred_unload_handles_; + int active_dispatch_depth_ = 0; + uint64_t next_anon_fn_seq_ = 0; InterpState interp_state_; // 下面三个的声明顺序是有讲究的:销毁是声明的逆序,而它们之间有依赖,写反会在 diff --git a/src/util/file_util.cpp b/src/util/file_util.cpp index a6f186af..ccffd79c 100644 --- a/src/util/file_util.cpp +++ b/src/util/file_util.cpp @@ -8,6 +8,7 @@ #if defined(_WIN32) #include #else +#include #include #endif @@ -15,12 +16,20 @@ namespace fakelua { std::string GetTmpDirectory() { boost::system::error_code ec; - auto tmpdir = boost::filesystem::temp_directory_path(ec); + auto base = boost::filesystem::temp_directory_path(ec); if (ec) { - tmpdir = boost::filesystem::path("."); + base = boost::filesystem::path("."); } - tmpdir /= "fakelua"; + auto tmpdir = base / "fakelua"; boost::filesystem::create_directories(tmpdir, ec); +#if !defined(_WIN32) + struct stat st{}; + if (ec || ::lstat(tmpdir.c_str(), &st) != 0 || !S_ISDIR(st.st_mode) || st.st_uid != ::getuid()) { + tmpdir = base / ("fakelua-" + std::to_string(static_cast(::getuid()))); + ec.clear(); + (void) ::mkdir(tmpdir.c_str(), 0700); + } +#endif return tmpdir.string(); } diff --git a/src/util/logging.cpp b/src/util/logging.cpp index d95eca92..62eff1cb 100644 --- a/src/util/logging.cpp +++ b/src/util/logging.cpp @@ -67,15 +67,20 @@ std::string CurrentTime() { // 滚动日志文件 void RotateLogs(const std::string &path, size_t max_files) { + std::error_code ec; + if (max_files == 0) { + std::filesystem::remove(path, ec); + return; + } + // 删除最旧的文件 std::string oldest = std::format("{}.{}", path, max_files); - std::error_code ec; std::filesystem::remove(oldest, ec); - // 将现有文件向后移动 - for (size_t i = max_files - 1; i >= 1; --i) { - std::string old_name = std::format("{}.{}", path, i); - std::string new_name = std::format("{}.{}", path, i + 1); + // 将现有文件向后移动(用 i > 1 避免无符号下溢) + for (size_t i = max_files; i > 1; --i) { + std::string old_name = std::format("{}.{}", path, i - 1); + std::string new_name = std::format("{}.{}", path, i); std::filesystem::rename(old_name, new_name, ec); } @@ -122,7 +127,8 @@ class LogSink { file_.flush(); // 检查文件大小,超过限制则滚动 - if (static_cast(file_.tellp()) >= max_size_) { + const auto pos = file_.tellp(); + if (pos != std::streampos(-1) && static_cast(pos) >= max_size_) { file_.close(); RotateLogs(file_path_, max_files_); file_.open(file_path_, std::ios::app); @@ -231,7 +237,7 @@ extern "C" void FakeluaLogLua(State *s, int level, CVar msg, const char *file, i msg_str = "nil"; break; case VarType::Bool: - msg_str = (msg.data_.i != 0) ? "true" : "false"; + msg_str = msg.data_.b ? "true" : "false"; break; case VarType::Int: msg_str = std::to_string(msg.data_.i); diff --git a/src/var/var.cpp b/src/var/var.cpp index 931276fb..2a9eac7b 100644 --- a/src/var/var.cpp +++ b/src/var/var.cpp @@ -6,6 +6,7 @@ #include "util/number_util.h" #include "var_multi.h" #include "var_string.h" +#include namespace fakelua { @@ -99,13 +100,13 @@ size_t Var::Hash() const { return static_cast(data_.i ^ (data_.i >> 32)); } case VarType::Float: { - union { - double d; - uint64_t u; - } bits; - - bits.d = data_.f; - return static_cast(bits.u ^ (bits.u >> 32)); + if (auto iv = TryConvertDoubleToInt64(data_.f)) { + const int64_t i = *iv; + return static_cast(i ^ (i >> 32)); + } + uint64_t u = 0; + std::memcpy(&u, &data_.f, sizeof(u)); + return static_cast(u ^ (u >> 32)); } case VarType::String: case VarType::StringId: { @@ -118,7 +119,13 @@ size_t Var::Hash() const { return static_cast(reinterpret_cast(data_.cl) ^ (reinterpret_cast(data_.cl) >> 32)); } case VarType::Multi: { - return static_cast(reinterpret_cast(data_.m) ^ (reinterpret_cast(data_.m) >> 32)); + VarMulti *m = data_.m; + if (!m) return 0; + uint32_t h = 2166136261u ^ m->GetCount(); + for (uint32_t i = 0; i < m->GetCount(); ++i) { + h = (h ^ static_cast(static_cast(m->GetVars()[i]).Hash())) * 16777619u; + } + return h ? h : 1u; } default: { return 0; diff --git a/src/var/var_closure.h b/src/var/var_closure.h index 596df695..dd62f71a 100644 --- a/src/var/var_closure.h +++ b/src/var/var_closure.h @@ -1,6 +1,7 @@ #pragma once #include "fakelua.h" +#include namespace fakelua { @@ -17,4 +18,16 @@ class VarClosure { CVar *upvalues[0]; }; +// code_str 在 func_ptr 非空时借用低地址标记创建该闭包的引擎(1=INTERP,2=GCC,0=TCC/原生); +// 仅当 func_ptr 为空且指针值 > 2 时才是指向 load() 源码文本的字符串指针。 +inline const char *const kGccClosureMagic = reinterpret_cast(static_cast(2)); + +inline bool IsGccClosure(const VarClosure *cl) { + return cl != nullptr && cl->func_ptr != nullptr && cl->code_str == kGccClosureMagic; +} + +inline bool IsSourceLoadClosure(const VarClosure *cl) { + return cl != nullptr && cl->func_ptr == nullptr && reinterpret_cast(cl->code_str) > 2; +} + }// namespace fakelua diff --git a/test/test_infer.cpp b/test/test_infer.cpp index 466e95f9..65577b37 100644 --- a/test/test_infer.cpp +++ b/test/test_infer.cpp @@ -367,8 +367,8 @@ TEST(infer, test_infer_shadowing) { // Outer val and res must be int64_t (int literal, never mutated). ASSERT_NE(code.find("int64_t val = 100;"), std::string::npos); ASSERT_NE(code.find("int64_t res = "), std::string::npos); - // Inner val (inside do...end block) is a string → CVar. - ASSERT_NE(code.find("CVar val = "), std::string::npos); + // Inner val (inside do...end block) is a string → CVar. Shadowed decls get a distinct C name. + ASSERT_TRUE(code.find("CVar val = ") != std::string::npos || code.find("CVar flua_s_val_") != std::string::npos); InferRunHelper([](State *s, JITType type, bool debug_mode) { CompileFile(s, "./infer/test_infer_shadowing.lua", {.debug_mode = debug_mode}); @@ -470,7 +470,7 @@ TEST(infer, test_infer_for_shadow_case1) { const auto code = InferGetCCode("./infer/test_infer_for_shadow_case1.lua"); ASSERT_NE(code.find("CVar a = "), std::string::npos);// outer a ASSERT_NE(code.find("int64_t sum = 0;"), std::string::npos); - ASSERT_NE(code.find("int64_t a = flua_for_ctrl_"), std::string::npos);// loop cursor + ASSERT_TRUE(code.find("int64_t a = flua_for_ctrl_") != std::string::npos || code.find("int64_t flua_s_a_") != std::string::npos); InferRunHelper([](State *s, JITType type, bool debug_mode) { CompileFile(s, "./infer/test_infer_for_shadow_case1.lua", {.debug_mode = debug_mode}); @@ -499,9 +499,9 @@ TEST(infer, test_infer_for_shadow_case2) { // typed after loop and support native numeric assignment. TEST(infer, test_infer_for_shadow_case3) { const auto code = InferGetCCode("./infer/test_infer_for_shadow_case3.lua"); - ASSERT_NE(code.find("int64_t a = 2;"), std::string::npos); // outer a - ASSERT_NE(code.find("int64_t a = flua_for_ctrl_"), std::string::npos);// cursor a - ASSERT_NE(code.find("a = FL_INT_ADD((a), (1));"), std::string::npos); // outer post-loop assign + ASSERT_NE(code.find("int64_t a = 2;"), std::string::npos);// outer a + ASSERT_TRUE(code.find("int64_t a = flua_for_ctrl_") != std::string::npos || code.find("int64_t flua_s_a_") != std::string::npos); + ASSERT_NE(code.find("a = FL_INT_ADD((a), (1));"), std::string::npos);// outer post-loop assign InferRunHelper([](State *s, JITType type, bool debug_mode) { CompileFile(s, "./infer/test_infer_for_shadow_case3.lua", {.debug_mode = debug_mode}); @@ -515,9 +515,10 @@ TEST(infer, test_infer_for_shadow_case3) { // outer a remains int64_t and is still used natively after loop. TEST(infer, test_infer_for_shadow_case4) { const auto code = InferGetCCode("./infer/test_infer_for_shadow_case4.lua"); - ASSERT_NE(code.find("int64_t a = 2;"), std::string::npos); // outer a - ASSERT_NE(code.find("CVar a = (CVar){.type_ = VAR_INT, .data_.i = (int64_t)(flua_for_ctrl_"), std::string::npos);// cursor a - ASSERT_NE(code.find("a = FL_INT_ADD((a), (1));"), std::string::npos); // outer post-loop assign + ASSERT_NE(code.find("int64_t a = 2;"), std::string::npos);// outer a + ASSERT_TRUE(code.find("CVar a = (CVar){.type_ = VAR_INT, .data_.i = (int64_t)(flua_for_ctrl_") != std::string::npos || + code.find("CVar flua_s_a_") != std::string::npos); + ASSERT_NE(code.find("a = FL_INT_ADD((a), (1));"), std::string::npos);// outer post-loop assign InferRunHelper([](State *s, JITType type, bool debug_mode) { CompileFile(s, "./infer/test_infer_for_shadow_case4.lua", {.debug_mode = debug_mode}); @@ -531,8 +532,8 @@ TEST(infer, test_infer_for_shadow_case4) { // outer dynamic `a` declaration/assignments after leaving do...end scope. TEST(infer, test_infer_do_shadow_typed_over_dynamic) { const auto code = InferGetCCode("./infer/test_infer_do_shadow_typed_over_dynamic.lua"); - ASSERT_NE(code.find("CVar a = "), std::string::npos); // outer a - ASSERT_NE(code.find("int64_t a = "), std::string::npos);// inner a + ASSERT_NE(code.find("CVar a = "), std::string::npos);// outer a + ASSERT_TRUE(code.find("int64_t a = ") != std::string::npos || code.find("int64_t flua_s_a_") != std::string::npos); InferRunHelper([](State *s, JITType type, bool debug_mode) { CompileFile(s, "./infer/test_infer_do_shadow_typed_over_dynamic.lua", {.debug_mode = debug_mode}); @@ -1114,7 +1115,7 @@ TEST(infer, test_infer_typed_int_for_neg_step_1) { const auto code = InferGetCCode("./infer/test_infer_typed_int_for_neg_step_1.lua"); ASSERT_NE(code.find("int64_t sum = "), std::string::npos); ASSERT_NE(code.find("for (; flua_for_ctrl_"), std::string::npos); - ASSERT_TRUE(code.find("FlForIntAdvance(") != std::string::npos || code.find("INT64_MIN") != std::string::npos); + ASSERT_TRUE(code.find("FlForIntAdvance(") != std::string::npos || code.find("INT64_MIN") != std::string::npos || code.find("(-9223372036854775807LL - 1LL)") != std::string::npos); ASSERT_EQ(code.find("int64_t flua_for_step_"), std::string::npos); InferRunHelper([](State *s, JITType type, bool debug_mode) { @@ -1129,7 +1130,7 @@ TEST(infer, test_infer_typed_int_for_neg_step_2) { const auto code = InferGetCCode("./infer/test_infer_typed_int_for_neg_step_2.lua"); ASSERT_NE(code.find("int64_t sum = "), std::string::npos); ASSERT_NE(code.find("for (; flua_for_ctrl_"), std::string::npos); - ASSERT_TRUE(code.find("FlForIntAdvance(") != std::string::npos || code.find("INT64_MIN") != std::string::npos); + ASSERT_TRUE(code.find("FlForIntAdvance(") != std::string::npos || code.find("INT64_MIN") != std::string::npos || code.find("(-9223372036854775807LL - 1LL)") != std::string::npos); ASSERT_EQ(code.find("int64_t flua_for_step_"), std::string::npos); InferRunHelper([](State *s, JITType type, bool debug_mode) { diff --git a/test/test_jitter.cpp b/test/test_jitter.cpp index 76daf9b4..59c892f7 100644 --- a/test/test_jitter.cpp +++ b/test/test_jitter.cpp @@ -4137,7 +4137,6 @@ TEST(jitter, gcc_cache_rejects_open_toolchains_and_disabled_configuration) { EXPECT_TRUE(f.dir.Entries().empty()); } } - TEST(jitter, gcc_cache_manifest_validation_and_republication) { CacheArtifactFixture f; const std::vector manifests{ @@ -4324,8 +4323,6 @@ TEST(jitter, nested_multivalue_returns_preserve_arity_when_math_specialization_i EXPECT_EQ(result, 1) << JitTypeName(backend); } } - - #if !defined(_WIN32) TEST(jitter, gcc_cache_makefile_dependencies_with_escaped_names_and_line_endings) { CacheArtifactFixture fixture; @@ -4507,4 +4504,118 @@ TEST(jitter, captured_int_var_or_param_reassigned_to_float_never_reads_int_bits) } } +TEST(jitter, top_level_iife_mutable_upvalue_survives_reset_across_backends) { + for (auto backend: AllJitTypes()) { + FakeluaStateGuard guard; + State *s = guard.GetState(); + CompileConfig cfg{}; + cfg.disable_jit[JIT_TCC] = (backend != JIT_TCC); + cfg.disable_jit[JIT_GCC] = (backend != JIT_GCC); + cfg.disable_jit[JIT_INTERP] = (backend != JIT_INTERP); + + CompileString(s, R"( + local store, load_val = (function() + local box = { tag = "init", n = 0 } + return function(v) box = v end, function() return box end + end)() + + function save_runtime_table(prefix, num) + local nested = { label = prefix .. "_inner", val = num + 10 } + local fn = function(delta) + return nested.val + delta + end + store({ msg = prefix .. "_outer", sub = nested, cb = fn }) + return 1 + end + + function read_saved_table() + local t = load_val() + return t.msg .. ":" .. t.sub.label .. ":" .. tostring(t.cb(5)) + end + )", cfg); + + int64_t ok = 0; + Call(s, backend, "save_runtime_table", ok, std::string("frame1"), int64_t{32}); + EXPECT_EQ(ok, 1) << JitTypeName(backend); + + // Allocate churn in another top-level Call (which triggers Reset() on temp_heap) + CompileString(s, R"( + function churn_arena() + local acc = "" + for i = 1, 64 do + local tmp = { a = tostring(i) .. "_overwrite_temp_arena", b = i * 3 } + acc = tmp.a + end + return #acc + end + )", cfg); + int64_t churn_len = 0; + Call(s, backend, "churn_arena", churn_len); + EXPECT_GT(churn_len, 0) << JitTypeName(backend); + + std::string out; + Call(s, backend, "read_saved_table", out); + EXPECT_EQ(out, "frame1_outer:frame1_inner:47") << JitTypeName(backend); + } +} + +TEST(jitter, active_self_reload_and_anon_closure_module_keep_code_alive) { + for (auto backend: AllJitTypes()) { + FakeluaStateGuard guard; + State *s = guard.GetState(); + CompileConfig cfg{}; + cfg.debug_mode = false; + cfg.disable_jit[JIT_TCC] = (backend != JIT_TCC); + cfg.disable_jit[JIT_GCC] = (backend != JIT_GCC); + cfg.disable_jit[JIT_INTERP] = (backend != JIT_INTERP); + + // 1) Anonymous-closure-only file exported via NativeObject must survive subsequent module loads + NativeObject *holder = GetNativeObjectManager(s).GlobalCreate("closure_holder", "Holder", 100); + ASSERT_NE(holder, nullptr); + holder->SetId(202); + EXPECT_EQ(GetNativeObjectManager(s).Get("Holder", 100), nullptr); + EXPECT_EQ(GetNativeObjectManager(s).Get("Holder", 202), holder); + + CompileString(s, R"( + local secret = 70 + local exported = function(x) return x + secret end + function install_exported() + return exported(7) + end + )", cfg); + + // Second file also defines __fl_func_1 and overwrites install_exported while running via host callback + RegisterNativeFunction(s, "host_reload_fn", false, std::function([cfg](State *st) -> int64_t { + CompileString(st, R"( + local other = 1000 + local f = function(y) return y + other end + function self_reloader() + return f(9) + end + )", cfg); + return 5; + })); + + CompileString(s, R"( + function self_reloader() + local before = 40 + local added = host_reload_fn() + return before + added + end + )", cfg); + + int64_t first = 0; + Call(s, backend, "self_reloader", first); + EXPECT_EQ(first, 45) << JitTypeName(backend); + + int64_t second = 0; + Call(s, backend, "self_reloader", second); + EXPECT_EQ(second, 1009) << JitTypeName(backend); + + EXPECT_TRUE(GetNativeObjectManager(s).DestroySingle("Holder", 202)); + EXPECT_EQ(GetNativeObjectManager(s).Get("Holder", 202), nullptr); + } +} + +