#include "dl_json_config.h" namespace dl { std::string JsonConfig::GenerateCode(const GenerateParam& param) { std::string str; std::size_t tab_num = 0;// 当前tab数 // 读写数据 struct RwData { std::string _type; std::vector _vec; }; // 类型定义变量 -> std::unordered_map rw_data; std::string rw_data_root;// 根类型 // 写入换行 auto endl = [&]() { str.push_back('\n'); }; // 写入tab auto tab = [&]() { for (std::size_t i = 0; i < tab_num; ++i) str += '\t'; }; // 生成读json代码 auto fn_read = [&]() { tab(); str += "bool Load(json& j_root)"; endl(); tab(); str += "{"; endl(); ++tab_num; for (auto& iter : rw_data) { std::string var_name = iter.first; RwData& rw = iter.second; tab(); str += "{"; endl(); ++tab_num; tab(); str += fmt::format("json j;", var_name); endl(); tab(); str += fmt::format("Json::AutoGet(j_root, \"{}\", j);", var_name); endl(); for (auto& iter1 : rw._vec) { tab(); str += fmt::format("Json::AutoGet(j, \"{1}\", {0}.{1});", var_name, iter1); endl(); } --tab_num; tab(); str += "}"; endl(); } tab(); str += "return true;"; endl(); --tab_num; tab(); str += "}"; endl(); }; // 生成写json代码 auto fn_write = [&]() { tab(); str += "json Save()"; endl(); tab(); str += "{"; endl(); ++tab_num; tab(); str += "json j;"; endl(); for (auto& iter : rw_data) { std::string var_name = iter.first; RwData& rw = iter.second; tab(); str += "{"; endl(); ++tab_num; tab(); str += fmt::format("json& j_{} = j[{}];", var_name, String::AddQuotes(var_name)); endl(); for (auto& iter1 : rw._vec) { tab(); str += fmt::format("j_{0}[\"{1}\"] = {0}.{1};", var_name, iter1); endl(); } --tab_num; tab(); str += "}"; endl(); } tab(); str += "return j;"; endl(); --tab_num; tab(); str += "}"; endl(); }; // 生成lua绑定代码 auto fn_register_lua = [&]() { tab(); str += fmt::format("void RegisterLua(lua_State* L, const std::string& lua_name)", rw_data_root); endl(); tab(); str += "{"; endl(); ++tab_num; for (auto& iter : rw_data) { std::string var_name = iter.first; RwData& rw = iter.second; tab(); str += "luabridge::getGlobalNamespace(L)"; endl(); ++tab_num; tab(); str += fmt::format(".beginClass<{}>({})", rw._type, String::AddQuotes(var_name)); endl(); tab(); str += ".addConstructor()"; endl(); for (auto& iter1 : rw._vec) { tab(); str += fmt::format(".addProperty({}, &{}::{})", String::AddQuotes(iter1), rw._type, iter1); endl(); } tab(); str += ".endClass();"; endl(); tab(); str += ""; endl(); --tab_num; } // 根类 tab(); str += "luabridge::getGlobalNamespace(L)"; endl(); ++tab_num; tab(); str += fmt::format(".beginClass<{}>(lua_name.c_str())", rw_data_root); endl(); tab(); str += ".addConstructor()"; endl(); for (auto& iter : rw_data) { std::string var_name = iter.first; RwData& rw = iter.second; tab(); str += fmt::format(".addProperty({}, &{}::{})", String::AddQuotes(var_name), rw_data_root, var_name); endl(); } tab(); str += ".endClass();"; endl(); tab(); str += ""; endl(); --tab_num; tab(); str += "auto result = luabridge::push(L, this);"; endl(); tab(); str += "lua_setglobal(L, lua_name.c_str());"; endl(); --tab_num; tab(); str += "}"; endl(); }; auto fn_struct = [&](auto&& fn_value, Value& v, RwData& rw)->void { ValueStruct s = v.ToStruct(); for (auto& iter : s.GetMemberAll()) { fn_value(fn_value, iter.second, rw); } }; auto fn_value = [&](auto&& fn_value, Value& v, RwData& rw)->void { if (v.GetType() == ValueType::NONE) return; if (v.GetType() == ValueType::STRUCT) { ValueStruct s = v.ToStruct(); std::string type = s.GetMember("type").ToString(); ValueType v_type = String2ValueType(type); std::string str_name = s["name"].ToString(); std::string str_desc = s["desc"].ToString(); std::string str_div = str_desc.empty() ? "" : " -> "; if (v_type == ValueType::NONE) { return; } else if (v_type == ValueType::STRUCT) { tab(); str += fmt::format("//! {}{}{}", str_name, str_div, str_desc); endl(); tab(); str += fmt::format("struct {}", type); endl(); tab(); str += "{"; endl(); ++tab_num; // 生成rw RwData& rw = rw_data[s.GetName()]; rw._type = type; fn_struct(fn_value, s["value"], rw); if (tab_num == 1) { // 结束代码 rw_data_root = rw_data["__root"]._type; rw_data.erase("__root"); fn_read(); fn_write(); if (param._bRegisterLua) fn_register_lua(); } --tab_num; if (tab_num != 0) { tab(); str += fmt::format("}}{};", s.GetName()); endl(); } else { tab(); str += "};"; endl(); } } else if(v_type == ValueType::VECTOR || v_type == ValueType::ARRAY) { ValueTypeInfo type_info = String2ValueTypeEx(type); tab(); str += fmt::format("{} {} = {};//! {}{}{}", Type2CppTypeEx(v_type, type_info._type1, type_info._length), s.GetName(), s["value"].GetString(), str_name, str_div, str_desc); endl(); rw._vec.push_back(s.GetName()); } else { tab(); str += fmt::format("{} {} = {};//! {}{}{}", Type2CppType(v_type), s.GetName(), s["value"].GetString(), str_name, str_div, str_desc); endl(); rw._vec.push_back(s.GetName()); } } }; // 标头 str += fmt::format(R"(/** * @file {0} * @brief 客户端自动生成配置代码 * * * @version 1.0 * @author {1} * @date 24-12-11 * * @note 自动生成的配置代码 */ #pragma once #include #include #include #include #include using json = nlohmann::json; )", param._filename, param._author); // lua头 if (param._bRegisterLua) { str += fmt::format(R"( #define LUA_USE_APICHECK #include #include )"); } // json get函数 str += fmt::format(R"( namespace Json {{ /** * @brief 从json返回值,不存在则返回false */ template bool AutoGet(const json& j, const std::string& name, T& t) {{ auto iter = j.find(name); if (iter == j.end()) {{ {0}(std::string("未加载到配置:") + name); return false; }} try {{ json v = *iter; if (v.find("value") != v.end()) t = (v["value"]).get(); else t = v.get(); return true; }} catch (nlohmann::detail::exception& e) {{ {0}(std::string("配置取值失败:") + name + " " + e.what()); }} return false; }} }} )", param._logFunction); fn_value(fn_value, _root, rw_data["__root"]); return str; } std::string JsonConfig::GenerateConfigUser(const std::unordered_map& map_type) { json j; auto fn_struct = [&](auto&& fn_value, json& j_this, Value& v)->void { ValueStruct s = v.ToStruct(); for (auto& iter : s.GetMemberAll()) { fn_value(fn_value, j_this, iter.second); } }; auto fn_value = [&](auto&& fn_value, json& j_parent, Value& v)->void { if (v.GetType() == ValueType::NONE) return; if (v.GetType() == ValueType::STRUCT) { ValueStruct s = v.ToStruct(); std::string type = s.GetMember("type").ToString(); ValueType v_type = String2ValueType(type); if (v_type == ValueType::NONE) { return; } else if (v_type == ValueType::STRUCT) { std::string str_name = s["name"].ToString(); std::string str_desc = s["desc"].ToString(); json& j_this = j_parent[s.GetName()]; //log_msg("构造 {}", s.GetName()); j_this["__name"] = str_name; j_this["__desc"] = str_desc; fn_struct(fn_value, j_this, s["value"]); } else { std::string str_name = s["name"].ToString(); std::string str_desc = s["desc"].ToString(); json& j_this = j_parent[s.GetName()]; //log_msg("构造 {}", s.GetName()); j_this["__name"] = str_name; j_this["__desc"] = str_desc; // 类型替换 std::string out_type; auto iter_type = map_type.find(type); if (iter_type == map_type.end()) out_type = type; else out_type = iter_type->second; j_this["type"] = out_type;// Type2CppType(v_type); j_this["value"] = s["value"].GetJson(); } } }; fn_value(fn_value, j, _root); return j["__root"].dump(4); } dl::Value JsonConfig::_parse_node(json& j, std::string_view var) { Node node; node._var = var; Json::DisableLog l; Json::Get(j, "name", node._name); Json::Get(j, "desc", node._desc); std::string type; Json::Get(j, "type", type); json j_value; Json::Get(j, "value", j_value); node._value = _parse_value(j_value, type); ValueStruct s{ var }; s["type"] = type; s["name"] = node._name; s["desc"] = node._desc; s["value"] = node._value; return s; } dl::Value JsonConfig::_parse_value(json& j, std::string_view type) { ValueType value_type = String2ValueType(type); try { switch (value_type) { case dl::ValueType::BOOL: return j.get(); case dl::ValueType::CHAR: return j.get(); case dl::ValueType::UCHAR: return j.get(); case dl::ValueType::SHORT: return j.get(); case dl::ValueType::USHORT: return j.get(); case dl::ValueType::INT: return j.get(); case dl::ValueType::UINT: return j.get(); case dl::ValueType::INT64: return j.get(); case dl::ValueType::UINT64: return j.get(); case dl::ValueType::FLOAT: return j.get(); case dl::ValueType::DOUBLE: return j.get(); case dl::ValueType::STRUCT: { g_value.RegisterStruct(type); ValueStruct s{ type }; std::string str = j.dump(4); for (auto& iter : j.items()) { if(String::IsBegin(iter.key(), "//")) continue; Value v = _parse_node(iter.value(), iter.key()); s[iter.key()] = v; } return s; } break; case dl::ValueType::STRING: return j.get(); case dl::ValueType::ARRAY: { ValueTypeInfo type_info = String2ValueTypeEx(type); ValueVector vec{ type_info._type1 }; size_t i = 0; for (auto& iter : j.items()) { Value v = _parse_value(iter.value(), type_info._strType1); vec.PushBack(v); ++i; if (i >= type_info._length) break; } for (; i < type_info._length; ++i) { Value v{ type_info._type1}; vec.PushBack(v); } return vec; } case dl::ValueType::VECTOR: { ValueTypeInfo type_info = String2ValueTypeEx(type); ValueVector vec{ type_info._type1 }; for (auto& iter : j.items()) { Value v = _parse_value(iter.value(), type_info._strType1); vec.PushBack(v); } return vec; } case dl::ValueType::MAP: break; case dl::ValueType::NONE: default: assert(0); break; } } catch (nlohmann::detail::exception& e) { log_err("json类型转换失败,请检查配置:({})\n" "{}\n" "{}", type, j.dump(4), e.what()); } return {}; } }