diff --git a/src/Luban.Job.Cfg/Source/DataVisitors/BinaryExportor.cs b/src/Luban.Job.Cfg/Source/DataExporters/BinaryExportor.cs similarity index 98% rename from src/Luban.Job.Cfg/Source/DataVisitors/BinaryExportor.cs rename to src/Luban.Job.Cfg/Source/DataExporters/BinaryExportor.cs index 66fe3d6..80d2ba9 100644 --- a/src/Luban.Job.Cfg/Source/DataVisitors/BinaryExportor.cs +++ b/src/Luban.Job.Cfg/Source/DataExporters/BinaryExportor.cs @@ -1,10 +1,11 @@ using Bright.Serialization; using Luban.Job.Cfg.Datas; +using Luban.Job.Cfg.DataVisitors; using Luban.Job.Cfg.Defs; using Luban.Job.Common.TypeVisitors; using System.Collections.Generic; -namespace Luban.Job.Cfg.DataVisitors +namespace Luban.Job.Cfg.DataExporters { class BinaryExportor : IDataActionVisitor { diff --git a/src/Luban.Job.Cfg/Source/DataVisitors/JsonExportor.cs b/src/Luban.Job.Cfg/Source/DataExporters/JsonExportor.cs similarity index 98% rename from src/Luban.Job.Cfg/Source/DataVisitors/JsonExportor.cs rename to src/Luban.Job.Cfg/Source/DataExporters/JsonExportor.cs index cb58a3c..ebd475e 100644 --- a/src/Luban.Job.Cfg/Source/DataVisitors/JsonExportor.cs +++ b/src/Luban.Job.Cfg/Source/DataExporters/JsonExportor.cs @@ -1,10 +1,11 @@ using Luban.Job.Cfg.Datas; +using Luban.Job.Cfg.DataVisitors; using Luban.Job.Cfg.Defs; using System; using System.Collections.Generic; using System.Text.Json; -namespace Luban.Job.Cfg.DataVisitors +namespace Luban.Job.Cfg.DataExporters { class JsonExportor : IDataActionVisitor { diff --git a/src/Luban.Job.Cfg/Source/DataVisitors/LuaExportor.cs b/src/Luban.Job.Cfg/Source/DataExporters/LuaExportor.cs similarity index 98% rename from src/Luban.Job.Cfg/Source/DataVisitors/LuaExportor.cs rename to src/Luban.Job.Cfg/Source/DataExporters/LuaExportor.cs index 5cce981..f81202c 100644 --- a/src/Luban.Job.Cfg/Source/DataVisitors/LuaExportor.cs +++ b/src/Luban.Job.Cfg/Source/DataExporters/LuaExportor.cs @@ -1,11 +1,12 @@ using Luban.Job.Cfg.Datas; +using Luban.Job.Cfg.DataVisitors; using Luban.Job.Cfg.Defs; using System; using System.Collections.Generic; using System.Linq; using System.Text; -namespace Luban.Job.Cfg.DataVisitors +namespace Luban.Job.Cfg.DataExporters { class LuaExportor : IDataActionVisitor { diff --git a/src/Luban.Job.Cfg/Source/Defs/DefBean.cs b/src/Luban.Job.Cfg/Source/Defs/DefBean.cs index 311dd7a..0d8e6a9 100644 --- a/src/Luban.Job.Cfg/Source/Defs/DefBean.cs +++ b/src/Luban.Job.Cfg/Source/Defs/DefBean.cs @@ -31,7 +31,7 @@ namespace Luban.Job.Cfg.Defs return DeepCompareTypeDefine.Ins.Compare(this, b, new Dictionary(), new HashSet()); } - public string GoImport + public string GoBinImport { get { @@ -42,7 +42,24 @@ namespace Luban.Job.Cfg.Defs } foreach (var f in Fields) { - f.CType.Apply(CollectGoImport.Ins, imports); + f.CType.Apply(TypeVisitors.GoBinImport.Ins, imports); + } + return string.Join('\n', imports.Select(im => $"import \"{im}\"")); + } + } + + public string GoJsonImport + { + get + { + var imports = new HashSet(); + if (IsAbstractType) + { + imports.Add("errors"); + } + foreach (var f in Fields) + { + f.CType.Apply(TypeVisitors.GoJsonImport.Ins, imports); } return string.Join('\n', imports.Select(im => $"import \"{im}\"")); } diff --git a/src/Luban.Job.Cfg/Source/Defs/DefTable.cs b/src/Luban.Job.Cfg/Source/Defs/DefTable.cs index 87e0de9..c566499 100644 --- a/src/Luban.Job.Cfg/Source/Defs/DefTable.cs +++ b/src/Luban.Job.Cfg/Source/Defs/DefTable.cs @@ -49,9 +49,9 @@ namespace Luban.Job.Cfg.Defs public bool NeedExport => Assembly.NeedExport(this.Groups); - public string OutputDataFile => $"{FullName}.bin"; + public string OutputDataFile => FullName; - public string JsonOutputDataFile => $"{FullName}.json"; + public string OutputDataFileEscapeDot => FullName.Replace('.', '_'); public List GetBranchInputFiles(string branchName) { diff --git a/src/Luban.Job.Cfg/Source/Defs/TTypeTemplateExtends.cs b/src/Luban.Job.Cfg/Source/Defs/TTypeTemplateExtends.cs index e89e623..f90f001 100644 --- a/src/Luban.Job.Cfg/Source/Defs/TTypeTemplateExtends.cs +++ b/src/Luban.Job.Cfg/Source/Defs/TTypeTemplateExtends.cs @@ -80,12 +80,12 @@ namespace Luban.Job.Cfg.Defs public static string GoDeserializeType(TBean type, string bufName) { - return type.Bean.IsAbstractType ? $"NewChild{type.Bean.GoFullName}({bufName})" : $"New{ type.Bean.GoFullName} ({ bufName})"; + return $"New{type.Bean.GoFullName}({bufName})"; } public static string GoDeserializeField(TType type, string name, string bufName) { - return type.Apply(GoDeserializeVisitor.Ins, name, bufName); + return type.Apply(GoDeserializeBinVisitor.Ins, name, bufName); } public static string GoDeserializeJsonField(TType type, string name, string fieldName, string bufName) diff --git a/src/Luban.Job.Cfg/Source/Generate/CodeRenderBase.cs b/src/Luban.Job.Cfg/Source/Generate/CodeRenderBase.cs index 9dd75a6..62fbba1 100644 --- a/src/Luban.Job.Cfg/Source/Generate/CodeRenderBase.cs +++ b/src/Luban.Job.Cfg/Source/Generate/CodeRenderBase.cs @@ -5,7 +5,7 @@ using System.Collections.Generic; namespace Luban.Job.Cfg.Generate { - public abstract class CodeRenderBase : ICodeRender + public abstract class CodeRenderBase : ICfgCodeRender { public abstract string Render(DefConst c); public abstract string Render(DefEnum c); @@ -13,7 +13,7 @@ namespace Luban.Job.Cfg.Generate public abstract string Render(DefTable c); public abstract string RenderService(string name, string module, List tables); - public string RenderAny(object o) + public string RenderAny(DefTypeBase o) { switch (o) { diff --git a/src/Luban.Job.Cfg/Source/Generate/CppBinCodeRender.cs b/src/Luban.Job.Cfg/Source/Generate/CppCodeBinRender.cs similarity index 99% rename from src/Luban.Job.Cfg/Source/Generate/CppBinCodeRender.cs rename to src/Luban.Job.Cfg/Source/Generate/CppCodeBinRender.cs index 3e3fa67..bed3a35 100644 --- a/src/Luban.Job.Cfg/Source/Generate/CppBinCodeRender.cs +++ b/src/Luban.Job.Cfg/Source/Generate/CppCodeBinRender.cs @@ -7,7 +7,7 @@ using System.Collections.Generic; namespace Luban.Job.Cfg.Generate { - class CppBinCodeRender : CodeRenderBase + class CppCodeBinRender : CodeRenderBase { public override string Render(DefConst c) { diff --git a/src/Luban.Job.Cfg/Source/Generate/CsBinCodeRender.cs b/src/Luban.Job.Cfg/Source/Generate/CsCodeBinRender.cs similarity index 99% rename from src/Luban.Job.Cfg/Source/Generate/CsBinCodeRender.cs rename to src/Luban.Job.Cfg/Source/Generate/CsCodeBinRender.cs index f6cdeb5..178d788 100644 --- a/src/Luban.Job.Cfg/Source/Generate/CsBinCodeRender.cs +++ b/src/Luban.Job.Cfg/Source/Generate/CsCodeBinRender.cs @@ -5,7 +5,7 @@ using System.Collections.Generic; namespace Luban.Job.Cfg.Generate { - class CsBinCodeRender : CsCodeRenderBase + class CsCodeBinRender : CsCodeRenderBase { [ThreadStatic] private static Template t_beanRender; diff --git a/src/Luban.Job.Cfg/Source/Generate/CsJsonCodeRender.cs b/src/Luban.Job.Cfg/Source/Generate/CsCodeJsonRender.cs similarity index 99% rename from src/Luban.Job.Cfg/Source/Generate/CsJsonCodeRender.cs rename to src/Luban.Job.Cfg/Source/Generate/CsCodeJsonRender.cs index ccef599..db4348b 100644 --- a/src/Luban.Job.Cfg/Source/Generate/CsJsonCodeRender.cs +++ b/src/Luban.Job.Cfg/Source/Generate/CsCodeJsonRender.cs @@ -5,7 +5,7 @@ using System.Collections.Generic; namespace Luban.Job.Cfg.Generate { - class CsJsonCodeRender : CsCodeRenderBase + class CsCodeJsonRender : CsCodeRenderBase { [ThreadStatic] private static Template t_beanRender; @@ -233,7 +233,7 @@ public sealed partial class {{name}} { var tables = new System.Collections.Generic.Dictionary(); {{~for table in tables ~}} - {{table.name}} = new {{table.full_name}}(loader(""{{table.json_output_data_file}}"")); + {{table.name}} = new {{table.full_name}}(loader(""{{table.output_data_file}}"")); tables.Add(""{{table.full_name}}"", {{table.name}}); {{~end~}} diff --git a/src/Luban.Job.Cfg/Source/Generate/EditorCppRender.cs b/src/Luban.Job.Cfg/Source/Generate/EditorCppRender.cs index 220972f..556321e 100644 --- a/src/Luban.Job.Cfg/Source/Generate/EditorCppRender.cs +++ b/src/Luban.Job.Cfg/Source/Generate/EditorCppRender.cs @@ -5,43 +5,31 @@ using System.Collections.Generic; namespace Luban.Job.Cfg.Generate { - class EditorCppRender + class EditorCppRender : CodeRenderBase { - public string RenderAny(object o) - { - switch (o) - { - case DefConst c: return Render(c); - case DefEnum e: return Render(e); - case DefBean b: return Render(b); - case DefTable r: return Render(r); - default: throw new Exception($"unknown render type:{o}"); - } - } - - public string Render(DefConst c) + public override string Render(DefConst c) { return "// const"; } - public string Render(DefEnum e) + public override string Render(DefEnum e) { return "// enum"; } - public string Render(DefBean b) + public override string Render(DefBean b) { return "// bean"; } - public string Render(DefTable p) + public override string Render(DefTable p) { return "// table"; } - public string RenderStubs(string name, string module, List protos) + public override string RenderService(string name, string module, List tables) { - return "// stubs"; + return "// service"; } } } diff --git a/src/Luban.Job.Cfg/Source/Generate/EditorCsRender.cs b/src/Luban.Job.Cfg/Source/Generate/EditorCsRender.cs index 4f08c18..6f5316e 100644 --- a/src/Luban.Job.Cfg/Source/Generate/EditorCsRender.cs +++ b/src/Luban.Job.Cfg/Source/Generate/EditorCsRender.cs @@ -8,33 +8,21 @@ using System.Linq; namespace Luban.Job.Cfg.Generate { - class EditorCsRender + class EditorCsRender : CodeRenderBase { - public string RenderAny(object o) - { - switch (o) - { - case DefConst c: return Render(c); - case DefEnum e: return Render(e); - // case DefBean b: return Render(b); editor 不需要生成 table 的定义 - // case CTable r: return Render(r); - default: throw new Exception($"unknown render type:{o}"); - } - } - - public string Render(DefConst c) + public override string Render(DefConst c) { return RenderUtil.RenderCsConstClass(c); } - public string Render(DefEnum e) + public override string Render(DefEnum e) { return RenderUtil.RenderCsEnumClass(e); } [ThreadStatic] private static Template t_beanRender; - public string Render(DefBean b) + public override string Render(DefBean b) { var template = t_beanRender ??= Template.Parse(@" using Bright.Serialization; @@ -136,7 +124,7 @@ public {{cs_class_modifier}} class {{name}} : {{if parent_def_type}} {{parent}} [ThreadStatic] private static Template t_tableRender; - public string Render(DefTable p) + public override string Render(DefTable p) { var template = t_tableRender ??= Template.Parse(@" using Bright.Serialization; @@ -211,7 +199,7 @@ public sealed class {{name}} : Bright.Net.Protocol [ThreadStatic] private static Template t_stubRender; - public string RenderStubs(string name, string module, List protos) + public override string RenderService(string name, string module, List tables) { var template = t_stubRender ??= Template.Parse(@" using Bright.Serialization; @@ -236,7 +224,7 @@ public static class {{name}} { Name = name, Namespace = module, - Tables = protos.Where(p => p is DefTable).ToList(), + Tables = tables, }); return result; diff --git a/src/Luban.Job.Cfg/Source/Generate/GoBinCodeRender.cs b/src/Luban.Job.Cfg/Source/Generate/GoCodeBinRender.cs similarity index 87% rename from src/Luban.Job.Cfg/Source/Generate/GoBinCodeRender.cs rename to src/Luban.Job.Cfg/Source/Generate/GoCodeBinRender.cs index 50e2fc7..c79fcde 100644 --- a/src/Luban.Job.Cfg/Source/Generate/GoBinCodeRender.cs +++ b/src/Luban.Job.Cfg/Source/Generate/GoCodeBinRender.cs @@ -6,11 +6,11 @@ using System.Collections.Generic; namespace Luban.Job.Cfg.Generate { - class GoBinCodeRender : GoCodeRenderBase + class GoCodeBinRender : GoCodeRenderBase { [ThreadStatic] private static Template t_beanRender; - protected override string Render(DefBean b) + public override string Render(DefBean b) { string package = "cfg"; @@ -27,12 +27,9 @@ package {{package}} import ( ""bright/serialization"" -{{~if is_abstract_type~}} - ""errors"" -{{~end~}} ) -{{x.go_import}} +{{x.go_bin_import}} type {{go_full_name}} struct { {{~if parent_def_type~}} @@ -49,20 +46,8 @@ func ({{go_full_name}}) GetTypeId() int { } {{~end~}} -func New{{go_full_name}}(_buf *serialization.ByteBuf) (_v *{{go_full_name}}, err error) { - _v = &{{go_full_name}}{} -{{~if parent_def_type~}} - var _p *{{parent_def_type.go_full_name}} - if _p, err = New{{parent_def_type.go_full_name}}(_buf) ; err != nil { return } - _v.{{parent_def_type.go_full_name}} = *_p -{{~end~}} - {{~for field in export_fields ~}} - {{go_deserialize_field field.ctype (""_v."" + field.go_style_name) '_buf'}} - {{~end~}} - return -} {{~if is_abstract_type~}} -func NewChild{{go_full_name}}(_buf *serialization.ByteBuf) (_v interface{}, err error) { +func New{{go_full_name}}(_buf *serialization.ByteBuf) (_v interface{}, err error) { var id int32 if id, err = _buf.ReadInt() ; err != nil { return @@ -75,6 +60,33 @@ func NewChild{{go_full_name}}(_buf *serialization.ByteBuf) (_v interface{}, err } return } + +func New{{go_full_name}}_Body(_buf *serialization.ByteBuf) (_v *{{go_full_name}}, err error) { + _v = &{{go_full_name}}{} +{{~if parent_def_type~}} + var _p *{{parent_def_type.go_full_name}} + if _p, err = New{{parent_def_type.go_full_name}}_Body(_buf) ; err != nil { return } + _v.{{parent_def_type.go_full_name}} = *_p +{{~end~}} + {{~for field in export_fields ~}} + {{go_deserialize_field field.ctype (""_v."" + field.go_style_name) '_buf'}} + {{~end~}} + return +} + +{{~else~}} +func New{{go_full_name}}(_buf *serialization.ByteBuf) (_v *{{go_full_name}}, err error) { + _v = &{{go_full_name}}{} +{{~if parent_def_type~}} + var _p *{{parent_def_type.go_full_name}} + if _p, err = New{{parent_def_type.go_full_name}}_Body(_buf) ; err != nil { return } + _v.{{parent_def_type.go_full_name}} = *_p +{{~end~}} + {{~for field in export_fields ~}} + {{go_deserialize_field field.ctype (""_v."" + field.go_style_name) '_buf'}} + {{~end~}} + return +} {{~end~}} "); @@ -85,7 +97,7 @@ func NewChild{{go_full_name}}(_buf *serialization.ByteBuf) (_v interface{}, err [ThreadStatic] private static Template t_tableRender; - protected override string Render(DefTable p) + public override string Render(DefTable p) { // TODO Ŀǰֶֻ֧̬ͨ. ˫key֧ string package = "cfg"; diff --git a/src/Luban.Job.Cfg/Source/Generate/GoJsonCodeRender.cs b/src/Luban.Job.Cfg/Source/Generate/GoCodeJsonRender.cs similarity index 85% rename from src/Luban.Job.Cfg/Source/Generate/GoJsonCodeRender.cs rename to src/Luban.Job.Cfg/Source/Generate/GoCodeJsonRender.cs index 9a97140..0d4b80d 100644 --- a/src/Luban.Job.Cfg/Source/Generate/GoJsonCodeRender.cs +++ b/src/Luban.Job.Cfg/Source/Generate/GoCodeJsonRender.cs @@ -6,11 +6,11 @@ using System.Collections.Generic; namespace Luban.Job.Cfg.Generate { - class GoJsonCodeRender : GoCodeRenderBase + class GoCodeJsonRender : GoCodeRenderBase { [ThreadStatic] private static Template t_beanRender; - protected override string Render(DefBean b) + public override string Render(DefBean b) { string package = "cfg"; @@ -25,7 +25,7 @@ namespace Luban.Job.Cfg.Generate package {{package}} -{{x.go_import}} +{{x.go_json_import}} type {{go_full_name}} struct { {{~if parent_def_type~}} @@ -42,20 +42,8 @@ func ({{go_full_name}}) GetTypeId() int { } {{~end~}} -func New{{go_full_name}}(_buf map[string]interface{}) (_v *{{go_full_name}}, err error) { - _v = &{{go_full_name}}{} -{{~if parent_def_type~}} - var _p *{{parent_def_type.go_full_name}} - if _p, err = New{{parent_def_type.go_full_name}}(_buf) ; err != nil { return } - _v.{{parent_def_type.go_full_name}} = *_p -{{~end~}} - {{~for field in export_fields ~}} - {{go_deserialize_json_field field.ctype (""_v."" + field.go_style_name) field.name '_buf'}} - {{~end~}} - return -} {{~if is_abstract_type~}} -func NewChild{{go_full_name}}(_buf map[string]interface{}) (_v interface{}, err error) { +func New{{go_full_name}}(_buf map[string]interface{}) (_v interface{}, err error) { var id string var _ok_ bool if id, _ok_ = _buf[""__type__""].(string) ; !_ok_ { @@ -69,6 +57,32 @@ func NewChild{{go_full_name}}(_buf map[string]interface{}) (_v interface{}, err } return } + +func New{{go_full_name}}_Body(_buf map[string]interface{}) (_v *{{go_full_name}}, err error) { + _v = &{{go_full_name}}{} +{{~if parent_def_type~}} + var _p *{{parent_def_type.go_full_name}} + if _p, err = New{{parent_def_type.go_full_name}}_Body(_buf) ; err != nil { return } + _v.{{parent_def_type.go_full_name}} = *_p +{{~end~}} + {{~for field in export_fields ~}} + {{go_deserialize_json_field field.ctype (""_v."" + field.go_style_name) field.name '_buf'}} + {{~end~}} + return +} +{{~else~}} +func New{{go_full_name}}(_buf map[string]interface{}) (_v *{{go_full_name}}, err error) { + _v = &{{go_full_name}}{} +{{~if parent_def_type~}} + var _p *{{parent_def_type.go_full_name}} + if _p, err = New{{parent_def_type.go_full_name}}_Body(_buf) ; err != nil { return } + _v.{{parent_def_type.go_full_name}} = *_p +{{~end~}} + {{~for field in export_fields ~}} + {{go_deserialize_json_field field.ctype (""_v."" + field.go_style_name) field.name '_buf'}} + {{~end~}} + return +} {{~end~}} "); @@ -79,7 +93,7 @@ func NewChild{{go_full_name}}(_buf map[string]interface{}) (_v interface{}, err [ThreadStatic] private static Template t_tableRender; - protected override string Render(DefTable p) + public override string Render(DefTable p) { // TODO Ŀǰֶֻ֧̬ͨ. ˫key֧ string package = "cfg"; @@ -194,7 +208,7 @@ func NewTables(loader JsonLoader) (*{{name}}, error) { tables := &{{name}}{} {{~for table in tables ~}} - if buf, err = loader(""{{table.json_output_data_file}}"") ; err != nil { + if buf, err = loader(""{{table.output_data_file}}"") ; err != nil { return nil, err } if tables.{{table.name}}, err = New{{table.go_full_name}}(buf) ; err != nil { diff --git a/src/Luban.Job.Cfg/Source/Generate/GoCodeRenderBase.cs b/src/Luban.Job.Cfg/Source/Generate/GoCodeRenderBase.cs index dc412ff..323fa6b 100644 --- a/src/Luban.Job.Cfg/Source/Generate/GoCodeRenderBase.cs +++ b/src/Luban.Job.Cfg/Source/Generate/GoCodeRenderBase.cs @@ -9,24 +9,12 @@ using System.Threading.Tasks; namespace Luban.Job.Cfg.Generate { - abstract class GoCodeRenderBase + abstract class GoCodeRenderBase : CodeRenderBase { - public string RenderAny(object o) - { - switch (o) - { - case DefConst c: return Render(c); - case DefEnum e: return Render(e); - case DefBean b: return Render(b); - case DefTable r: return Render(r); - default: throw new Exception($"unknown render type:{o}"); - } - } - [ThreadStatic] private static Template t_constRender; - private string Render(DefConst c) + public override string Render(DefConst c) { string package = "cfg"; @@ -48,7 +36,7 @@ const ( [ThreadStatic] private static Template t_enumRender; - private string Render(DefEnum e) + public override string Render(DefEnum e) { string package = "cfg"; @@ -68,11 +56,5 @@ const ( return result; } - - protected abstract string Render(DefBean b); - - protected abstract string Render(DefTable p); - - public abstract string RenderService(string name, string module, List tables); } } diff --git a/src/Luban.Job.Cfg/Source/Generate/ICfgCodeRender.cs b/src/Luban.Job.Cfg/Source/Generate/ICfgCodeRender.cs new file mode 100644 index 0000000..6857324 --- /dev/null +++ b/src/Luban.Job.Cfg/Source/Generate/ICfgCodeRender.cs @@ -0,0 +1,14 @@ +using Luban.Job.Cfg.Defs; +using Luban.Job.Common.Defs; +using Luban.Job.Common.Generate; +using System.Collections.Generic; + +namespace Luban.Job.Cfg.Generate +{ + interface ICfgCodeRender : ICodeRender + { + string Render(DefBean b); + + string Render(DefTable c); + } +} diff --git a/src/Luban.Job.Cfg/Source/Generate/ICodeRender.cs b/src/Luban.Job.Cfg/Source/Generate/ICodeRender.cs deleted file mode 100644 index c55fd18..0000000 --- a/src/Luban.Job.Cfg/Source/Generate/ICodeRender.cs +++ /dev/null @@ -1,21 +0,0 @@ -using Luban.Job.Cfg.Defs; -using Luban.Job.Common.Defs; -using System.Collections.Generic; - -namespace Luban.Job.Cfg.Generate -{ - interface ICodeRender - { - string RenderAny(object o); - - string Render(DefConst c); - - string Render(DefEnum c); - - string Render(DefBean b); - - string Render(DefTable c); - - string RenderService(string name, string module, List tables); - } -} diff --git a/src/Luban.Job.Cfg/Source/Generate/JavaBinCodeRender.cs b/src/Luban.Job.Cfg/Source/Generate/JavaCodeBinRender.cs similarity index 96% rename from src/Luban.Job.Cfg/Source/Generate/JavaBinCodeRender.cs rename to src/Luban.Job.Cfg/Source/Generate/JavaCodeBinRender.cs index 4021d25..bab6dd8 100644 --- a/src/Luban.Job.Cfg/Source/Generate/JavaBinCodeRender.cs +++ b/src/Luban.Job.Cfg/Source/Generate/JavaCodeBinRender.cs @@ -7,18 +7,8 @@ using System.Collections.Generic; namespace Luban.Job.Cfg.Generate { - class JavaBinCodeRender : CodeRenderBase + class JavaCodeBinRender : JavaCodeRenderBase { - public override string Render(DefConst c) - { - return RenderUtil.RenderJavaConstClass(c); - } - - public override string Render(DefEnum c) - { - return RenderUtil.RenderJavaEnumClass(c); - } - [ThreadStatic] private static Template t_beanRender; diff --git a/src/Luban.Job.Cfg/Source/Generate/JavaCodeRenderBase.cs b/src/Luban.Job.Cfg/Source/Generate/JavaCodeRenderBase.cs new file mode 100644 index 0000000..11c5ce5 --- /dev/null +++ b/src/Luban.Job.Cfg/Source/Generate/JavaCodeRenderBase.cs @@ -0,0 +1,22 @@ +using Luban.Job.Cfg.Defs; +using Luban.Job.Common.Defs; +using Luban.Job.Common.Utils; +using Scriban; +using System; +using System.Collections.Generic; + +namespace Luban.Job.Cfg.Generate +{ + abstract class JavaCodeRenderBase : CodeRenderBase + { + public override string Render(DefConst c) + { + return RenderUtil.RenderJavaConstClass(c); + } + + public override string Render(DefEnum c) + { + return RenderUtil.RenderJavaEnumClass(c); + } + } +} diff --git a/src/Luban.Job.Cfg/Source/Generate/LuaRender.cs b/src/Luban.Job.Cfg/Source/Generate/LuaCodeBinRender.cs similarity index 62% rename from src/Luban.Job.Cfg/Source/Generate/LuaRender.cs rename to src/Luban.Job.Cfg/Source/Generate/LuaCodeBinRender.cs index 854422b..936b664 100644 --- a/src/Luban.Job.Cfg/Source/Generate/LuaRender.cs +++ b/src/Luban.Job.Cfg/Source/Generate/LuaCodeBinRender.cs @@ -1,53 +1,24 @@ using Luban.Job.Cfg.Defs; using Luban.Job.Common.Defs; +using Luban.Job.Common.Utils; using Scriban; +using System; using System.Collections.Generic; using System.Linq; namespace Luban.Job.Cfg.Generate { - class LuaRender + class LuaCodeBinRender : LuaCodeRenderBase { - - public string RenderAll(List types) + [ThreadStatic] + private static Template t_allRender; + public override string RenderAll(List types) { var consts = types.Where(t => t is DefConst).ToList(); var enums = types.Where(t => t is DefEnum).ToList(); var beans = types.Where(t => t is DefBean).ToList(); var tables = types.Where(t => t is DefTable).ToList(); - var template = Template.Parse(@" -{{ - consts = x.consts - enums = x.enums - beans = x.beans - tables = x.tables -}} -local setmetatable = setmetatable -local pairs = pairs -local ipairs = ipairs -local tinsert = table.insert - -local function SimpleClass() - local class = {} - class.__index = class - class.New = function(...) - local ctor = class.ctor - local o = ctor and ctor(...) or {} - setmetatable(o, class) - return o - end - return class -end - - -local function get_map_size(m) - local n = 0 - for _ in pairs(m) do - n = n + 1 - end - return n -end - + var template = t_allRender ??= Template.Parse(LuaStringTemplate.BaseDefines + @" local consts = { {{~ for c in consts ~}} @@ -185,74 +156,6 @@ local function InitTypes(methods) return { InitTypes = InitTypes } -"); - return template.RenderCode(new { Consts = consts, Enums = enums, Beans = beans, Tables = tables }); - } - - public string RenderDefines(List types) - { - var consts = types.Where(t => t is DefConst).ToList(); - var enums = types.Where(t => t is DefEnum).ToList(); - var beans = types.Where(t => t is DefBean).ToList(); - var tables = types.Where(t => t is DefTable).ToList(); - var template = Template.Parse(@" -{{ - consts = x.consts - enums = x.enums - beans = x.beans - tables = x.tables -}} - -local consts = -{ - {{~ for c in consts ~}} - ---@class {{c.full_name}} - {{~ for item in c.items ~}} - ---@field public {{item.name}} {{item.type}} - {{~end~}} - ['{{c.full_name}}'] = { {{ for item in c.items }} {{item.name}}={{lua_const_value item.ctype item.value}}, {{end}} }; - {{~end~}} -} - -local enums = -{ - {{~ for c in enums ~}} - ---@class {{c.full_name}} - {{~ for item in c.items ~}} - ---@field public {{item.name}} int - {{~end~}} - ['{{c.full_name}}'] = { {{ for item in c.items }} {{item.name}}={{item.int_value}}, {{end}} }; - {{~end~}} -} - -local beans = {} -{{~ for bean in beans ~}} ----@class {{bean.full_name}} {{if bean.parent_def_type}}:{{bean.parent}} {{end}} -{{~ for field in bean.export_fields~}} ----@field public {{field.name}} {{lua_comment_type field.ctype}} -{{~end~}} -beans['{{bean.full_name}}'] = -{ -{{~ for field in bean.hierarchy_export_fields ~}} - { name='{{field.name}}', type='{{lua_comment_type field.ctype}}'}, -{{~end~}} -} - -{{~end~}} - -local tables = -{ -{{~for table in tables ~}} - {{~if table.is_map_table ~}} - { name='{{table.name}}', file='{{table.output_data_file}}', mode='map', index='{{table.index}}', value_type='{{table.value_ttype.bean.full_name}}' }, - {{~else~}} - { name='{{table.name}}', file='{{table.output_data_file}}', mode='one', value_type='{{table.value_ttype.bean.full_name}}'}, - {{end}} -{{~end~}} -} - -return { consts = consts, enums = enums, beans = beans, tables = tables } - "); return template.RenderCode(new { Consts = consts, Enums = enums, Beans = beans, Tables = tables }); } diff --git a/src/Luban.Job.Cfg/Source/Generate/LuaCodeLuaRender.cs b/src/Luban.Job.Cfg/Source/Generate/LuaCodeLuaRender.cs new file mode 100644 index 0000000..ea1a981 --- /dev/null +++ b/src/Luban.Job.Cfg/Source/Generate/LuaCodeLuaRender.cs @@ -0,0 +1,77 @@ +using Luban.Job.Cfg.Defs; +using Luban.Job.Common.Defs; +using Luban.Job.Common.Utils; +using Scriban; +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Luban.Job.Cfg.Generate +{ + class LuaCodeLuaRender : LuaCodeRenderBase + { + [ThreadStatic] + private static Template t_allRender; + + public override string RenderAll(List types) + { + var consts = types.Where(t => t is DefConst).ToList(); + var enums = types.Where(t => t is DefEnum).ToList(); + var beans = types.Where(t => t is DefBean).ToList(); + var tables = types.Where(t => t is DefTable).ToList(); + var template = t_allRender ??= Template.Parse(LuaStringTemplate.BaseDefines + @" +local consts = +{ + {{~ for c in consts ~}} + ---@class {{c.full_name}} + {{~ for item in c.items ~}} + ---@field public {{item.name}} {{item.type}} + {{~end~}} + ['{{c.full_name}}'] = { {{ for item in c.items }} {{item.name}}={{lua_const_value item.ctype item.value}}, {{end}} }; + {{~end~}} +} + +local enums = +{ + {{~ for c in enums ~}} + ---@class {{c.full_name}} + {{~ for item in c.items ~}} + ---@field public {{item.name}} int + {{~end~}} + ['{{c.full_name}}'] = { {{ for item in c.items }} {{item.name}}={{item.int_value}}, {{end}} }; + {{~end~}} +} + +local beans = {} +{{~ for bean in beans ~}} +---@class {{bean.full_name}} {{if bean.parent_def_type}}:{{bean.parent}} {{end}} +{{~ for field in bean.export_fields~}} +---@field public {{field.name}} {{lua_comment_type field.ctype}} +{{~end~}} +beans['{{bean.full_name}}'] = +{ +{{~ for field in bean.hierarchy_export_fields ~}} + { name='{{field.name}}', type='{{lua_comment_type field.ctype}}'}, +{{~end~}} +} + +{{~end~}} + +local tables = +{ +{{~for table in tables ~}} + {{~if table.is_map_table ~}} + { name='{{table.name}}', file='{{table.output_data_file_escape_dot}}', mode='map', index='{{table.index}}', value_type='{{table.value_ttype.bean.full_name}}' }, + {{~else~}} + { name='{{table.name}}', file='{{table.output_data_file_escape_dot}}', mode='one', value_type='{{table.value_ttype.bean.full_name}}'}, + {{end}} +{{~end~}} +} + +return { consts = consts, enums = enums, beans = beans, tables = tables } + +"); + return template.RenderCode(new { Consts = consts, Enums = enums, Beans = beans, Tables = tables }); + } + } +} diff --git a/src/Luban.Job.Cfg/Source/Generate/LuaCodeRenderBase.cs b/src/Luban.Job.Cfg/Source/Generate/LuaCodeRenderBase.cs new file mode 100644 index 0000000..23a6a3d --- /dev/null +++ b/src/Luban.Job.Cfg/Source/Generate/LuaCodeRenderBase.cs @@ -0,0 +1,42 @@ +using Luban.Job.Cfg.Defs; +using Luban.Job.Common.Defs; +using Scriban; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Luban.Job.Cfg.Generate +{ + abstract class LuaCodeRenderBase : CodeRenderBase + { + + public override string Render(DefConst c) + { + throw new System.NotImplementedException(); + } + + public override string Render(DefEnum e) + { + throw new System.NotImplementedException(); + } + + public override string Render(DefTable c) + { + throw new System.NotImplementedException(); + } + + public override string Render(DefBean b) + { + throw new NotImplementedException(); + } + + public override string RenderService(string name, string module, List tables) + { + throw new System.NotImplementedException(); + } + + public abstract string RenderAll(List types); + } +} diff --git a/src/Luban.Job.Cfg/Source/Generate/Python27JsonCodeRender.cs b/src/Luban.Job.Cfg/Source/Generate/Python27CodeJsonRender.cs similarity index 61% rename from src/Luban.Job.Cfg/Source/Generate/Python27JsonCodeRender.cs rename to src/Luban.Job.Cfg/Source/Generate/Python27CodeJsonRender.cs index 6da7500..d96e8a2 100644 --- a/src/Luban.Job.Cfg/Source/Generate/Python27JsonCodeRender.cs +++ b/src/Luban.Job.Cfg/Source/Generate/Python27CodeJsonRender.cs @@ -6,53 +6,8 @@ using System.Collections.Generic; namespace Luban.Job.Cfg.Generate { - class Python27JsonCodeRender : CodeRenderBase + class Python27CodeJsonRender : PythonCodeRenderBase { - [ThreadStatic] - private static Template t_tsConstRender; - public override string Render(DefConst c) - { - var ctx = new TemplateContext(); - var env = new TTypeTemplateCommonExtends - { - ["x"] = c - }; - ctx.PushGlobal(env); - - - var template = t_tsConstRender ??= Template.Parse(@" - -class {{x.py_full_name}}: - {{~ for item in x.items ~}} - {{item.name}} = {{py_const_value item.ctype item.value}} - {{~end~}} - {{~if (x.items == empty)~}} - pass - {{~end~}} - -"); - var result = template.Render(ctx); - - return result; - } - - [ThreadStatic] - private static Template t_tsEnumRender; - public override string Render(DefEnum e) - { - var template = t_tsEnumRender ??= Template.Parse(@" -class {{py_full_name}}: - {{~ for item in items ~}} - {{item.name}} = {{item.value}} - {{~end~}} - {{~if (items == empty)~}} - pass - {{~end~}} -"); - var result = template.Render(e); - - return result; - } [ThreadStatic] private static Template t_beanRender; @@ -155,37 +110,5 @@ class {{name}}: return result; } - - [ThreadStatic] - private static Template t_serviceRender; - public override string RenderService(string name, string module, List tables) - { - var template = t_serviceRender ??= Template.Parse(@" -{{ - name = x.name - namespace = x.namespace - tables = x.tables -}} - -class {{name}}: - {{~ for table in tables ~}} - #def {{table.name}} : return self._{{table.name}} - {{~end~}} - - def __init__(self, loader): - {{~for table in tables ~}} - self.{{table.name}} = {{table.py_full_name}}(loader('{{table.json_output_data_file}}')); - {{~end~}} - -"); - var result = template.RenderCode(new - { - Name = name, - Namespace = module, - Tables = tables, - }); - - return result; - } } } diff --git a/src/Luban.Job.Cfg/Source/Generate/Python3JsonCodeRender.cs b/src/Luban.Job.Cfg/Source/Generate/Python3CodeJsonRender.cs similarity index 61% rename from src/Luban.Job.Cfg/Source/Generate/Python3JsonCodeRender.cs rename to src/Luban.Job.Cfg/Source/Generate/Python3CodeJsonRender.cs index cd780a5..295b0c1 100644 --- a/src/Luban.Job.Cfg/Source/Generate/Python3JsonCodeRender.cs +++ b/src/Luban.Job.Cfg/Source/Generate/Python3CodeJsonRender.cs @@ -6,54 +6,8 @@ using System.Collections.Generic; namespace Luban.Job.Cfg.Generate { - class Python3JsonCodeRender : CodeRenderBase + class Python3CodeJsonRender : PythonCodeRenderBase { - [ThreadStatic] - private static Template t_tsConstRender; - public override string Render(DefConst c) - { - var ctx = new TemplateContext(); - var env = new TTypeTemplateCommonExtends - { - ["x"] = c - }; - ctx.PushGlobal(env); - - - var template = t_tsConstRender ??= Template.Parse(@" - -class {{x.py_full_name}}: - {{~ for item in x.items ~}} - {{item.name}} = {{py_const_value item.ctype item.value}} - {{~end~}} - {{~if (x.items == empty)~}} - pass - {{~end~}} - -"); - var result = template.Render(ctx); - - return result; - } - - [ThreadStatic] - private static Template t_tsEnumRender; - public override string Render(DefEnum e) - { - var template = t_tsEnumRender ??= Template.Parse(@" -class {{py_full_name}}(Enum): - {{~ for item in items ~}} - {{item.name}} = {{item.value}} - {{~end~}} - {{~if (items == empty)~}} - pass - {{~end~}} -"); - var result = template.Render(e); - - return result; - } - [ThreadStatic] private static Template t_beanRender; public override string Render(DefBean b) @@ -155,37 +109,5 @@ class {{name}}: return result; } - - [ThreadStatic] - private static Template t_serviceRender; - public override string RenderService(string name, string module, List tables) - { - var template = t_serviceRender ??= Template.Parse(@" -{{ - name = x.name - namespace = x.namespace - tables = x.tables -}} - -class {{name}}: - {{~ for table in tables ~}} - #def {{table.name}} : return self._{{table.name}} - {{~end~}} - - def __init__(self, loader): - {{~for table in tables ~}} - self.{{table.name}} = {{table.py_full_name}}(loader('{{table.json_output_data_file}}')); - {{~end~}} - -"); - var result = template.RenderCode(new - { - Name = name, - Namespace = module, - Tables = tables, - }); - - return result; - } } } diff --git a/src/Luban.Job.Cfg/Source/Generate/PythonCodeRenderBase.cs b/src/Luban.Job.Cfg/Source/Generate/PythonCodeRenderBase.cs new file mode 100644 index 0000000..5d602f4 --- /dev/null +++ b/src/Luban.Job.Cfg/Source/Generate/PythonCodeRenderBase.cs @@ -0,0 +1,89 @@ +using Luban.Job.Cfg.Defs; +using Luban.Job.Common.Defs; +using Scriban; +using System; +using System.Collections.Generic; + +namespace Luban.Job.Cfg.Generate +{ + abstract class PythonCodeRenderBase : CodeRenderBase + { + [ThreadStatic] + private static Template t_tsConstRender; + public override string Render(DefConst c) + { + var ctx = new TemplateContext(); + var env = new TTypeTemplateCommonExtends + { + ["x"] = c + }; + ctx.PushGlobal(env); + + + var template = t_tsConstRender ??= Template.Parse(@" + +class {{x.py_full_name}}: + {{~ for item in x.items ~}} + {{item.name}} = {{py_const_value item.ctype item.value}} + {{~end~}} + {{~if (x.items == empty)~}} + pass + {{~end~}} + +"); + var result = template.Render(ctx); + + return result; + } + + [ThreadStatic] + private static Template t_tsEnumRender; + public override string Render(DefEnum e) + { + var template = t_tsEnumRender ??= Template.Parse(@" +class {{py_full_name}}: + {{~ for item in items ~}} + {{item.name}} = {{item.value}} + {{~end~}} + {{~if (items == empty)~}} + pass + {{~end~}} +"); + var result = template.Render(e); + + return result; + } + + [ThreadStatic] + private static Template t_serviceRender; + public override string RenderService(string name, string module, List tables) + { + var template = t_serviceRender ??= Template.Parse(@" +{{ + name = x.name + namespace = x.namespace + tables = x.tables +}} + +class {{name}}: + {{~ for table in tables ~}} + #def {{table.name}} : return self._{{table.name}} + {{~end~}} + + def __init__(self, loader): + {{~for table in tables ~}} + self.{{table.name}} = {{table.py_full_name}}(loader('{{table.output_data_file}}')); + {{~end~}} + +"); + var result = template.RenderCode(new + { + Name = name, + Namespace = module, + Tables = tables, + }); + + return result; + } + } +} diff --git a/src/Luban.Job.Cfg/Source/Generate/TypeScriptBinCodeRender.cs b/src/Luban.Job.Cfg/Source/Generate/TypescriptCodeBinRender.cs similarity index 94% rename from src/Luban.Job.Cfg/Source/Generate/TypeScriptBinCodeRender.cs rename to src/Luban.Job.Cfg/Source/Generate/TypescriptCodeBinRender.cs index c1221e0..5c927ed 100644 --- a/src/Luban.Job.Cfg/Source/Generate/TypeScriptBinCodeRender.cs +++ b/src/Luban.Job.Cfg/Source/Generate/TypescriptCodeBinRender.cs @@ -7,18 +7,8 @@ using System.Collections.Generic; namespace Luban.Job.Cfg.Generate { - class TypeScriptBinCodeRender : CodeRenderBase + class TypescriptCodeBinRender : TypescriptCodeRenderBase { - public override string Render(DefConst c) - { - return RenderUtil.RenderTypescriptConstClass(c); - } - - public override string Render(DefEnum e) - { - return RenderUtil.RenderTypescriptEnumClass(e); - } - [ThreadStatic] private static Template t_beanRender; public override string Render(DefBean b) diff --git a/src/Luban.Job.Cfg/Source/Generate/TypeScriptJsonCodeRender.cs b/src/Luban.Job.Cfg/Source/Generate/TypescriptCodeJsonRender.cs similarity index 94% rename from src/Luban.Job.Cfg/Source/Generate/TypeScriptJsonCodeRender.cs rename to src/Luban.Job.Cfg/Source/Generate/TypescriptCodeJsonRender.cs index 1eada37..b3246ca 100644 --- a/src/Luban.Job.Cfg/Source/Generate/TypeScriptJsonCodeRender.cs +++ b/src/Luban.Job.Cfg/Source/Generate/TypescriptCodeJsonRender.cs @@ -7,18 +7,8 @@ using System.Collections.Generic; namespace Luban.Job.Cfg.Generate { - class TypeScriptJsonCodeRender : CodeRenderBase + class TypescriptCodeJsonRender : TypescriptCodeRenderBase { - public override string Render(DefConst c) - { - return RenderUtil.RenderTypescriptConstClass(c); - } - - public override string Render(DefEnum e) - { - return RenderUtil.RenderTypescriptEnumClass(e); - } - [ThreadStatic] private static Template t_beanRender; public override string Render(DefBean b) @@ -175,7 +165,7 @@ export class {{name}} { constructor(loader: JsonLoader) { let tables = new Map() {{~for table in tables ~}} - this._{{table.name}} = new {{table.full_name}}(loader('{{table.json_output_data_file}}')) + this._{{table.name}} = new {{table.full_name}}(loader('{{table.output_data_file}}')) tables.set('{{table.full_name}}', this._{{table.name}}) {{~end~}} diff --git a/src/Luban.Job.Cfg/Source/Generate/TypescriptCodeRenderBase.cs b/src/Luban.Job.Cfg/Source/Generate/TypescriptCodeRenderBase.cs new file mode 100644 index 0000000..31d86d9 --- /dev/null +++ b/src/Luban.Job.Cfg/Source/Generate/TypescriptCodeRenderBase.cs @@ -0,0 +1,22 @@ +using Luban.Job.Cfg.Defs; +using Luban.Job.Common.Defs; +using Luban.Job.Common.Utils; +using Scriban; +using System; +using System.Collections.Generic; + +namespace Luban.Job.Cfg.Generate +{ + abstract class TypescriptCodeRenderBase : CodeRenderBase + { + public override string Render(DefConst c) + { + return RenderUtil.RenderTypescriptConstClass(c); + } + + public override string Render(DefEnum e) + { + return RenderUtil.RenderTypescriptEnumClass(e); + } + } +} diff --git a/src/Luban.Job.Cfg/Source/Generate/UE4BpCppRender.cs b/src/Luban.Job.Cfg/Source/Generate/UE4BpCppRender.cs index b6fd578..2923274 100644 --- a/src/Luban.Job.Cfg/Source/Generate/UE4BpCppRender.cs +++ b/src/Luban.Job.Cfg/Source/Generate/UE4BpCppRender.cs @@ -2,25 +2,15 @@ using Luban.Job.Cfg.Defs; using Luban.Job.Common.Defs; using Scriban; using System; +using System.Collections.Generic; namespace Luban.Job.Cfg.Generate { - class UE4BpCppRender + class UE4BpCppRender : CodeRenderBase { - public string RenderAny(object o) - { - switch (o) - { - case DefEnum e: return Render(e); - case DefBean b: return Render(b); - //case CTable r: return Render(r); - default: throw new Exception($"unknown render type:{o}"); - } - } - [ThreadStatic] private static Template t_enumRender; - public string Render(DefEnum e) + public override string Render(DefEnum e) { // ue 不允许 UEnum 为这 // ue 强制枚举underling type 为 uint8, 意味着不能超过255 @@ -53,7 +43,7 @@ enum class {{ue_bp_full_name}} : uint8 [ThreadStatic] private static Template t_beanRender; - public string Render(DefBean b) + public override string Render(DefBean b) { var template = t_beanRender ??= Template.Parse(@" #pragma once @@ -86,6 +76,19 @@ public: return result; } + public override string Render(DefConst c) + { + throw new NotImplementedException(); + } + public override string Render(DefTable c) + { + throw new NotImplementedException(); + } + + public override string RenderService(string name, string module, List tables) + { + throw new NotImplementedException(); + } } } diff --git a/src/Luban.Job.Cfg/Source/Generate/UE4EditorCppRender.cs b/src/Luban.Job.Cfg/Source/Generate/UE4EditorCppRender.cs index c3fd1f2..fe91d65 100644 --- a/src/Luban.Job.Cfg/Source/Generate/UE4EditorCppRender.cs +++ b/src/Luban.Job.Cfg/Source/Generate/UE4EditorCppRender.cs @@ -6,22 +6,11 @@ using System.Collections.Generic; namespace Luban.Job.Cfg.Generate { - class UE4EditorCppRender + class UE4EditorCppRender : CodeRenderBase { - public string RenderAny(object o) - { - switch (o) - { - case DefEnum e: return Render(e); - case DefBean b: return Render(b); - //case CTable r: return Render(r); - default: throw new Exception($"unknown render type:{o}"); - } - } - [ThreadStatic] private static Template t_enumRender; - public string Render(DefEnum e) + public override string Render(DefEnum e) { var template = t_enumRender ??= Template.Parse(@" #pragma once @@ -53,7 +42,7 @@ namespace editor [ThreadStatic] private static Template t_beanRender; - public string Render(DefBean b) + public override string Render(DefBean b) { var template = t_beanRender ??= Template.Parse(@" #pragma once @@ -229,5 +218,20 @@ bool {{type.ue_fname}}FromString(const FString& s, {{type.ue_fname}}& value) return result; } + + public override string Render(DefConst c) + { + throw new NotImplementedException(); + } + + public override string Render(DefTable c) + { + throw new NotImplementedException(); + } + + public override string RenderService(string name, string module, List tables) + { + throw new NotImplementedException(); + } } } diff --git a/src/Luban.Job.Cfg/Source/JobController.cs b/src/Luban.Job.Cfg/Source/JobController.cs index b22bd1f..395d273 100644 --- a/src/Luban.Job.Cfg/Source/JobController.cs +++ b/src/Luban.Job.Cfg/Source/JobController.cs @@ -72,14 +72,25 @@ namespace Luban.Job.Cfg public string BranchInputDataDir { get; set; } } - private ICodeRender CreateCodeRender(string genType) + private ICfgCodeRender CreateCodeRender(string genType) { switch (genType) { - case "code_cs_bin": return new CsBinCodeRender(); - case "code_cs_json": return new CsJsonCodeRender(); - case "code_java_bin": return new JavaBinCodeRender(); - case "code_cpp_bin": return new CppBinCodeRender(); + case "code_cs_bin": return new CsCodeBinRender(); + case "code_cs_json": return new CsCodeJsonRender(); + case "code_java_bin": return new JavaCodeBinRender(); + case "code_go_bin": return new GoCodeBinRender(); + case "code_go_json": return new GoCodeJsonRender(); + case "code_cpp_bin": return new CppCodeBinRender(); + case "code_lua_bin": return new LuaCodeBinRender(); + case "code_lua_lua": return new LuaCodeLuaRender(); + case "code_python27_json": return new Python27CodeJsonRender(); + case "code_python3_json": return new Python3CodeJsonRender(); + case "code_typescript_bin": return new TypescriptCodeBinRender(); + case "code_typescript_json": return new TypescriptCodeJsonRender(); + case "code_cpp_ue_editor": return new UE4EditorCppRender(); + case "code_cpp_ue_bp": return new UE4BpCppRender(); + case "code_cs_unity_editor": return new EditorCsRender(); default: throw new ArgumentException($"not support gen type:{genType}"); } } @@ -91,13 +102,37 @@ namespace Luban.Job.Cfg case "code_cs_bin": case "code_cs_json": return ELanguage.CS; case "code_java_bin": return ELanguage.JAVA; + case "code_go_bin": + case "code_go_json": return ELanguage.GO; case "code_cpp_bin": return ELanguage.CPP; - case "code_go_bin": return ELanguage.GO; - case "code_lua_bin": return ELanguage.LUA; + case "code_lua_bin": + case "code_lua_lua": return ELanguage.LUA; + case "code_python27_json": + case "code_python3_json": return ELanguage.PYTHON; + case "code_typescript_bin": + case "code_typescript_json": return ELanguage.TYPESCRIPT; + case "code_cpp_ue_editor": + case "code_cpp_ue_bp": return ELanguage.CPP; + case "code_cs_unity_editor": return ELanguage.CS; default: throw new ArgumentException($"not support output data type:{genType}"); } } + private string GetOutputFileSuffix(string genType) + { + switch (genType) + { + case "data_bin": return "bin"; + case "data_json": return "json"; + case "data_lua": return "lua"; + default: throw new Exception($"not support output data type:{genType}"); + } + } + + private string GetOutputFileName(string genType, string fileName) + { + return $"{(genType.EndsWith("lua") ? fileName.Replace('.', '_') : fileName)}.{GetOutputFileSuffix(genType)}"; + } private static bool TryParseArg(List args, out GenArgs options, out string errMsg) { @@ -174,6 +209,27 @@ namespace Luban.Job.Cfg } } + + class GenContext + { + public GenArgs GenArgs { get; init; } + public DefAssembly Assembly { get; init; } + public string GenType { get; set; } + public ICfgCodeRender Render { get; set; } + public ELanguage Lan { get; set; } + + public string TopModule => Assembly.TopModule; + public Service TargetService => Assembly.CfgTargetService; + + + public List ExportTypes { get; init; } + public List ExportTables { get; init; } + public ConcurrentBag GenCodeFilesInOutputCodeDir { get; init; } + public ConcurrentBag GenDataFilesInOutputDataDir { get; init; } + public ConcurrentBag GenScatteredFiles { get; init; } + public List Tasks { get; init; } + } + public async Task GenAsync(RemoteAgent agent, GenJob rpc) { var res = new GenJobRes() @@ -255,568 +311,84 @@ namespace Luban.Job.Cfg foreach (var genType in genTypes) { + var ctx = new GenContext() + { + GenType = genType, + Assembly = ass, + GenArgs = args, + ExportTypes = exportTypes, + ExportTables = exportTables, + GenCodeFilesInOutputCodeDir = genCodeFilesInOutputCodeDir, + GenDataFilesInOutputDataDir = genDataFilesInOutputDataDir, + GenScatteredFiles = genScatteredFiles, + Tasks = tasks, + }; switch (genType) { case "code_cs_bin": case "code_cs_json": case "code_java_bin": - { - ICodeRender render = CreateCodeRender(genType); - ELanguage lan = GetLanguage(genType); - - foreach (var c in exportTypes) - { - tasks.Add(Task.Run(() => - { - var content = FileHeaderUtil.ConcatAutoGenerationHeader(render.RenderAny(c), lan); - var file = RenderFileUtil.GetDefTypePath(c.FullName, lan); - var md5 = CacheFileUtil.GenMd5AndAddCache(file, content); - genCodeFilesInOutputCodeDir.Add(new FileInfo() { FilePath = file, MD5 = md5 }); - })); - } - - tasks.Add(Task.Run(() => - { - var module = ass.TopModule; - var name = targetService.Manager; - var content = FileHeaderUtil.ConcatAutoGenerationHeader(render.RenderService(name, module, exportTables), lan); - var file = RenderFileUtil.GetDefTypePath(name, lan); - var md5 = CacheFileUtil.GenMd5AndAddCache(file, content); - genCodeFilesInOutputCodeDir.Add(new FileInfo() { FilePath = file, MD5 = md5 }); - })); - - break; - } - case "code_lua_bin": - { - tasks.Add(Task.Run(() => - { - var render = new LuaRender(); - var content = FileHeaderUtil.ConcatAutoGenerationHeader(render.RenderAll(ass.Types.Values.ToList()), ELanguage.LUA); - var file = "Types.lua"; - var md5 = CacheFileUtil.GenMd5AndAddCache(file, content); - genCodeFilesInOutputCodeDir.Add(new FileInfo() { FilePath = file, MD5 = md5 }); - })); - break; - } case "code_go_bin": case "code_go_json": { - GoCodeRenderBase render = genType == "code_go_bin" ? new GoBinCodeRender() : new GoJsonCodeRender(); - foreach (var c in exportTypes) - { - tasks.Add(Task.Run(() => - { - var content = FileHeaderUtil.ConcatAutoGenerationHeader(render.RenderAny(c), ELanguage.GO); - var file = RenderFileUtil.GetDefTypePath(c.FullName, ELanguage.GO); - var md5 = CacheFileUtil.GenMd5AndAddCache(file, content); - genCodeFilesInOutputCodeDir.Add(new FileInfo() { FilePath = file, MD5 = md5 }); - })); - } - - tasks.Add(Task.Run(() => - { - var module = ass.TopModule; - var name = targetService.Manager; - var content = FileHeaderUtil.ConcatAutoGenerationHeader(render.RenderService(name, module, exportTables), ELanguage.GO); - var file = RenderFileUtil.GetDefTypePath(name, ELanguage.GO); - var md5 = CacheFileUtil.GenMd5AndAddCache(file, content); - genCodeFilesInOutputCodeDir.Add(new FileInfo() { FilePath = file, MD5 = md5 }); - })); + GenerateCodeScatter(ctx); + break; + } + case "code_lua_bin": + case "code_lua_lua": + { + GenLuaCode(ctx); + break; + } + case "code_typescript_bin": + case "code_typescript_json": + { + GenTypescriptCode(ctx); + break; + } + case "code_python27_json": + { + GenPythonCodes(ctx); break; } case "code_cpp_bin": { - var render = new CppBinCodeRender(); - - - // 将所有 头文件定义 生成到一个文件 - // 按照 const,enum,bean,table, service 的顺序生成 - - tasks.Add(Task.Run(() => - { - var headerFileContent = new List - { - @$" -#pragma once -#include - -#include ""bright/serialization/ByteBuf.h"" -#include ""bright/CfgBean.hpp"" - -using ByteBuf = bright::serialization::ByteBuf; - -namespace {ass.TopModule} -{{ - -" - }; - - foreach (var type in exportTypes) - { - if (type is DefEnum e) - { - headerFileContent.Add(render.Render(e)); - } - } - - foreach (var type in exportTypes) - { - if (type is DefConst c) - { - headerFileContent.Add(render.Render(c)); - } - } - - foreach (var type in exportTypes) - { - if (type is DefBean e) - { - headerFileContent.Add(render.RenderForwardDefine(e)); - } - } - - foreach (var type in exportTypes) - { - if (type is DefBean e) - { - headerFileContent.Add(render.Render(e)); - } - } - - foreach (var type in exportTables) - { - headerFileContent.Add(render.Render(type)); - } - - headerFileContent.Add(render.RenderService("Tables", ass.TopModule, exportTables)); - - headerFileContent.Add("}"); // end of topmodule - - var content = FileHeaderUtil.ConcatAutoGenerationHeader(string.Join('\n', headerFileContent), ELanguage.CPP); - var file = "gen_types.h"; - var md5 = CacheFileUtil.GenMd5AndAddCache(file, content); - genCodeFilesInOutputCodeDir.Add(new FileInfo() { FilePath = file, MD5 = md5 }); - })); - - var beanTypes = exportTypes.Where(c => c is DefBean).ToList(); - - int TYPE_PER_STUB_FILE = 100; - - for (int i = 0, n = (beanTypes.Count + TYPE_PER_STUB_FILE - 1) / TYPE_PER_STUB_FILE; i < n; i++) - { - int index = i; - tasks.Add(Task.Run(() => - { - int startIndex = index * TYPE_PER_STUB_FILE; - var content = FileHeaderUtil.ConcatAutoGenerationHeader( - render.RenderStub(ass.TopModule, beanTypes.GetRange(startIndex, Math.Min(TYPE_PER_STUB_FILE, beanTypes.Count - startIndex))), - ELanguage.CPP); - var file = $"gen_stub_{index}.cpp"; - var md5 = CacheFileUtil.GenMd5AndAddCache(file, content); - genCodeFilesInOutputCodeDir.Add(new FileInfo() { FilePath = file, MD5 = md5 }); - })); - } + GenCppCode(ctx); break; } - - case "code_typescript_bin": - case "code_typescript_json": - { - bool isGenBinary = genType.EndsWith("bin"); - CodeRenderBase render = isGenBinary ? new TypeScriptBinCodeRender() : new TypeScriptJsonCodeRender(); - var brightRequirePath = args.TypescriptBrightRequirePath; - tasks.Add(Task.Run(() => - { - var fileContent = new List(); - if (isGenBinary) - { - if (args.UsePuertsByteBuf) - { - fileContent.Add(TypescriptBrightTypeTemplates.PuertsByteBufImports); - } - else - { - fileContent.Add(string.Format(TypescriptBrightTypeTemplates.BrightByteBufImportsFormat, brightRequirePath)); - } - } - - if (args.EmbedBrightTypes) - { - fileContent.Add(isGenBinary ? TypescriptBrightTypeTemplates.VectorTypesByteBuf : TypescriptBrightTypeTemplates.VectorTypesJson); - if (isGenBinary) - { - fileContent.Add(TypescriptBrightTypeTemplates.SerializeTypes); - } - } - else - { - if (isGenBinary) - { - fileContent.Add(string.Format(TypescriptBrightTypeTemplates.SerializeImportsFormat, brightRequirePath)); - } - fileContent.Add(string.Format(TypescriptBrightTypeTemplates.VectorImportsFormat, brightRequirePath)); - } - - fileContent.Add(@$"export namespace {ass.TopModule} {{"); - - foreach (var type in exportTypes) - { - fileContent.Add(render.RenderAny(type)); - } - - fileContent.Add(render.RenderService("Tables", ass.TopModule, exportTables)); - - fileContent.Add("}"); // end of topmodule - - var content = FileHeaderUtil.ConcatAutoGenerationHeader(string.Join('\n', fileContent), ELanguage.TYPESCRIPT); - var file = "Types.ts"; - var md5 = CacheFileUtil.GenMd5AndAddCache(file, content); - genCodeFilesInOutputCodeDir.Add(new FileInfo() { FilePath = file, MD5 = md5 }); - })); - break; - } - - //case "code_typescript_bin": - //{ - // var render = new TypeScriptBinCodeRender(); - // var brightRequirePath = args.TypescriptBrightRequirePath; - // tasks.Add(Task.Run(() => - // { - // var fileContent = new List(); - // if (args.UsePuertsByteBuf) - // { - // fileContent.Add(TypescriptBrightTypeTemplates.PuertsByteBufImports); - // } - // else - // { - // fileContent.Add(string.Format(TypescriptBrightTypeTemplates.BrightByteBufImportsFormat, brightRequirePath)); - // } - // if (args.EmbedBrightTypes) - // { - // fileContent.Add(TypescriptBrightTypeTemplates.VectorTypes); - // fileContent.Add(TypescriptBrightTypeTemplates.SerializeTypes); - // } - // else - // { - // fileContent.Add(string.Format(TypescriptBrightTypeTemplates.SerializeImportsFormat, brightRequirePath)); - // fileContent.Add(string.Format(TypescriptBrightTypeTemplates.VectorImportsFormat, brightRequirePath)); - // } - - // fileContent.Add(@$"export namespace {ass.TopModule} {{"); - - // foreach (var type in exportTypes) - // { - // fileContent.Add(render.RenderAny(type)); - // } - - // fileContent.Add(render.RenderService("Tables", ass.TopModule, exportTables)); - - // fileContent.Add("}"); // end of topmodule - - // var content = FileHeaderUtil.ConcatAutoGenerationHeader(string.Join('\n', fileContent), ELanguage.TYPESCRIPT); - // var file = "Types.ts"; - // var md5 = CacheFileUtil.GenMd5AndAddCache(file, content); - // genCodeFilesInOutputCodeDir.Add(new FileInfo() { FilePath = file, MD5 = md5 }); - // })); - // break; - //} - - case "code_python27_json": - { - var render = new Python27JsonCodeRender(); - - tasks.Add(Task.Run(() => - { - var fileContent = new List - { - PYTHON_VECTOR_DEFINES - }; - - foreach (var type in exportTypes) - { - if (type is DefEnum e) - { - fileContent.Add(render.Render(e)); - } - } - - foreach (var type in exportTypes) - { - if (type is DefConst c) - { - fileContent.Add(render.Render(c)); - } - } - - foreach (var type in exportTypes) - { - if (type is DefBean e) - { - fileContent.Add(render.Render(e)); - } - } - - foreach (var type in exportTables) - { - fileContent.Add(render.Render(type)); - } - - fileContent.Add(render.RenderService("Tables", ass.TopModule, exportTables)); - - var content = FileHeaderUtil.ConcatAutoGenerationHeader(string.Join('\n', fileContent), ELanguage.PYTHON); - var file = "Types.py"; - var md5 = CacheFileUtil.GenMd5AndAddCache(file, content); - genCodeFilesInOutputCodeDir.Add(new FileInfo() { FilePath = file, MD5 = md5 }); - - - { - var moduleInitContent = ""; - var initFile = "__init__.py"; - - var initMd5 = CacheFileUtil.GenMd5AndAddCache(initFile, moduleInitContent); - genCodeFilesInOutputCodeDir.Add(new FileInfo() { FilePath = initFile, MD5 = initMd5 }); - } - })); - break; - } - - case "code_python3_json": - { - var render = new Python3JsonCodeRender(); - - tasks.Add(Task.Run(() => - { - var fileContent = new List - { - @" -from enum import Enum -import abc -", - PYTHON_VECTOR_DEFINES, - }; - - foreach (var type in exportTypes) - { - if (type is DefEnum e) - { - fileContent.Add(render.Render(e)); - } - } - - foreach (var type in exportTypes) - { - if (type is DefConst c) - { - fileContent.Add(render.Render(c)); - } - } - - foreach (var type in exportTypes) - { - if (type is DefBean e) - { - fileContent.Add(render.Render(e)); - } - } - - foreach (var type in exportTables) - { - fileContent.Add(render.Render(type)); - } - - fileContent.Add(render.RenderService("Tables", ass.TopModule, exportTables)); - - var content = FileHeaderUtil.ConcatAutoGenerationHeader(string.Join('\n', fileContent), ELanguage.PYTHON); - var file = "Types.py"; - var md5 = CacheFileUtil.GenMd5AndAddCache(file, content); - genCodeFilesInOutputCodeDir.Add(new FileInfo() { FilePath = file, MD5 = md5 }); - })); - break; - } - case "code_cpp_ue_editor": { - var render = new UE4EditorCppRender(); - - var renderTypes = ass.Types.Values.Where(c => c is DefEnum || c is DefBean).ToList(); - - foreach (var c in renderTypes) - { - tasks.Add(Task.Run(() => - { - var content = FileHeaderUtil.ConcatAutoGenerationHeader(render.RenderAny(c), ELanguage.CPP); - var file = "editor_" + RenderFileUtil.GetUeCppDefTypeHeaderFilePath(c.FullName); - var md5 = CacheFileUtil.GenMd5AndAddCache(file, content); - genCodeFilesInOutputCodeDir.Add(new FileInfo() { FilePath = file, MD5 = md5 }); - })); - } - - int TYPE_PER_STUB_FILE = 200; - - for (int i = 0, n = (renderTypes.Count + TYPE_PER_STUB_FILE - 1) / TYPE_PER_STUB_FILE; i < n; i++) - { - int index = i; - tasks.Add(Task.Run(() => - { - int startIndex = index * TYPE_PER_STUB_FILE; - var content = FileHeaderUtil.ConcatAutoGenerationHeader( - render.RenderStub(renderTypes.GetRange(startIndex, Math.Min(TYPE_PER_STUB_FILE, renderTypes.Count - startIndex))), - ELanguage.CPP); - var file = $"stub_{index}.cpp"; - var md5 = CacheFileUtil.GenMd5AndAddCache(file, content); - genCodeFilesInOutputCodeDir.Add(new FileInfo() { FilePath = file, MD5 = md5 }); - })); - } + GenCppUeEditor(ctx); break; } case "code_cs_unity_editor": { - var render = new EditorCsRender(); - foreach (var c in ass.Types.Values) - { - tasks.Add(Task.Run(() => - { - var content = FileHeaderUtil.ConcatAutoGenerationHeader(render.RenderAny(c), ELanguage.CS); - var file = RenderFileUtil.GetDefTypePath(c.FullName, ELanguage.CS); - var md5 = CacheFileUtil.GenMd5AndAddCache(file, content); - genCodeFilesInOutputCodeDir.Add(new FileInfo() { FilePath = file, MD5 = md5 }); - })); - } + GenCsUnityEditor(ctx); break; } case "code_cpp_ue_bp": { - var render = new UE4BpCppRender(); - foreach (var c in exportTypes) - { - if (!(c is DefEnum || c is DefBean)) - { - continue; - } - - tasks.Add(Task.Run(() => - { - var content = FileHeaderUtil.ConcatAutoGenerationHeader(render.RenderAny(c), ELanguage.CPP); - var file = "bp_" + RenderFileUtil.GetUeCppDefTypeHeaderFilePath(c.FullName); - var md5 = CacheFileUtil.GenMd5AndAddCache(file, content); - genCodeFilesInOutputCodeDir.Add(new FileInfo() { FilePath = file, MD5 = md5 }); - })); - } + GenCppUeBp(ctx); break; } case "data_bin": case "data_json": + case "data_lua": { await CheckLoadCfgDataAsync(); - foreach (var c in exportTables) - { - tasks.Add(Task.Run(() => - { - var content = DataExporterUtil.ToOutputData(c, ass.GetTableExportDataList(c), genType); - var file = genType.EndsWith("json") ? c.JsonOutputDataFile : c.OutputDataFile; - var md5 = FileUtil.CalcMD5(content); - CacheManager.Ins.AddCache(file, md5, content); - genDataFilesInOutputDataDir.Add(new FileInfo() { FilePath = file, MD5 = md5 }); - })); - } + GenDataScatter(ctx); break; } case "data_json_monolithic": { await CheckLoadCfgDataAsync(); - List> allJsonTask = new List>(); - foreach (var c in exportTables) - { - allJsonTask.Add(Task.Run(() => - { - return DataExporterUtil.ToOutputData(c, ass.GetTableExportDataList(c), "data_json"); - })); - } - await Task.WhenAll(allJsonTask); - - int estimatedCapacity = allJsonTask.Sum(t => t.Result.Length + 100); - var sb = new MemoryStream(estimatedCapacity); - sb.Write(System.Text.Encoding.UTF8.GetBytes("{\n")); - for (int i = 0; i < exportTables.Count; i++) - { - if (i != 0) - { - sb.Write(System.Text.Encoding.UTF8.GetBytes((",\n"))); - } - sb.Write(System.Text.Encoding.UTF8.GetBytes("\"" + exportTables[i].Name + "\":")); - sb.Write(allJsonTask[i].Result); - } - sb.Write(System.Text.Encoding.UTF8.GetBytes("\n}")); - - var content = sb.ToArray(); - s_logger.Debug("estimated size:{0} actual size:{1}", estimatedCapacity, content.Length); - var md5 = FileUtil.CalcMD5(content); - var outputFile = args.OutputDataJsonMonolithicFile; - CacheManager.Ins.AddCache(outputFile, md5, content); - genScatteredFiles.Add(new FileInfo() { FilePath = outputFile, MD5 = md5 }); - break; - } - case "data_lua": - { - await CheckLoadCfgDataAsync(); - - tasks.Add(Task.Run(() => - { - var render = new LuaRender(); - var content = FileHeaderUtil.ConcatAutoGenerationHeader(render.RenderDefines(ass.Types.Values.ToList()), ELanguage.LUA); - var file = "Types.lua"; - var md5 = CacheFileUtil.GenMd5AndAddCache(file, content); - genDataFilesInOutputDataDir.Add(new FileInfo() { FilePath = file, MD5 = md5 }); - - })); - - foreach (var c in exportTables) - { - tasks.Add(Task.Run(() => - { - var content = DataExporterUtil.ToOutputData(c, ass.GetTableExportDataList(c), genType); - var file = $"{c.Name}.lua"; - var md5 = FileUtil.CalcMD5(content); - CacheManager.Ins.AddCache(file, md5, content); - genDataFilesInOutputDataDir.Add(new FileInfo() { FilePath = file, MD5 = md5 }); - })); - } + tasks.Add(GenJsonDataMonolithic(ctx)); break; } case "data_resources": { await CheckLoadCfgDataAsync(); - var genDataTasks = new List>>(); - foreach (var c in exportTables) - { - genDataTasks.Add(Task.Run(() => - { - return DataExporterUtil.ExportResourceList(ass.GetTableExportDataList(c)); - })); - } - - tasks.Add(Task.Run(async () => - { - var ress = new HashSet<(string, string)>(10000); - var resourceLines = new List(10000); - foreach (var task in genDataTasks) - { - foreach (var ri in await task) - { - if (ress.Add((ri.Resource, ri.Tag))) - { - resourceLines.Add($"{ri.Resource},{ri.Tag}"); - } - } - } - var file = args.OutputDataResourceListFile; - var contents = System.Text.Encoding.UTF8.GetBytes(string.Join("\n", resourceLines)); - var md5 = FileUtil.CalcMD5(contents); - CacheManager.Ins.AddCache(file, md5, contents); - - genScatteredFiles.Add(new FileInfo() { FilePath = file, MD5 = md5 }); - })); + GenResourceList(ctx); break; } @@ -862,58 +434,390 @@ import abc agent.Session.ReplyRpc(rpc, res); } - private const string PYTHON_VECTOR_DEFINES = @" -class Vector2: - def __init__(self, x, y): - self.x = x - self.y = y - def __str__(self): - return '{%g,%g}' % (self.x, self.y) + private void GenerateCodeScatter(GenContext ctx) + { + string genType = ctx.GenType; + ctx.Render = CreateCodeRender(genType); + ctx.Lan = GetLanguage(genType); + foreach (var c in ctx.ExportTypes) + { + ctx.Tasks.Add(Task.Run(() => + { + var content = FileHeaderUtil.ConcatAutoGenerationHeader(ctx.Render.RenderAny(c), ctx.Lan); + var file = RenderFileUtil.GetDefTypePath(c.FullName, ctx.Lan); + var md5 = CacheFileUtil.GenMd5AndAddCache(file, content); + ctx.GenCodeFilesInOutputCodeDir.Add(new FileInfo() { FilePath = file, MD5 = md5 }); + })); + } - @staticmethod - def fromJson(_json_): - x = _json_['x'] - y = _json_['y'] - if (x == None or y == None): - raise Exception() - return Vector2(x, y) + ctx.Tasks.Add(Task.Run(() => + { + var module = ctx.TopModule; + var name = ctx.TargetService.Manager; + var content = FileHeaderUtil.ConcatAutoGenerationHeader(ctx.Render.RenderService(name, module, ctx.ExportTables), ctx.Lan); + var file = RenderFileUtil.GetDefTypePath(name, ctx.Lan); + var md5 = CacheFileUtil.GenMd5AndAddCache(file, content); + ctx.GenCodeFilesInOutputCodeDir.Add(new FileInfo() { FilePath = file, MD5 = md5 }); + })); + } + + private void GenerateCodeMonolithic(GenContext ctx, string outputFile, List fileContent, Action> preContent, Action> postContent) + { + ctx.Tasks.Add(Task.Run(() => + { + fileContent.Add(FileHeaderUtil.GetAutoGenerationHeader(ctx.Lan)); + + preContent?.Invoke(fileContent); + + foreach (var type in ctx.ExportTypes) + { + fileContent.Add(ctx.Render.RenderAny(type)); + } + + fileContent.Add(ctx.Render.RenderService("Tables", ctx.TopModule, ctx.ExportTables)); + postContent?.Invoke(fileContent); + + var file = outputFile; + var md5 = CacheFileUtil.GenMd5AndAddCache(file, string.Join('\n', fileContent)); + ctx.GenCodeFilesInOutputCodeDir.Add(new FileInfo() { FilePath = file, MD5 = md5 }); + })); + } + + private void GenLuaCode(GenContext ctx) + { + string genType = ctx.GenType; + LuaCodeRenderBase render = CreateCodeRender(genType) as LuaCodeRenderBase; + var file = "Types.lua"; + var content = render.RenderAll(ctx.ExportTypes); + var md5 = CacheFileUtil.GenMd5AndAddCache(file, string.Join('\n', content)); + ctx.GenCodeFilesInOutputCodeDir.Add(new FileInfo() { FilePath = file, MD5 = md5 }); + } + + private void GenTypescriptCode(GenContext ctx) + { + string genType = ctx.GenType; + var args = ctx.GenArgs; + ctx.Render = CreateCodeRender(genType); + ctx.Lan = GetLanguage(genType); + + var lines = new List(10000); + Action> preContent = (fileContent) => + { + var brightRequirePath = args.TypescriptBrightRequirePath; + bool isGenBinary = genType.EndsWith("bin"); + if (isGenBinary) + { + if (args.UsePuertsByteBuf) + { + fileContent.Add(TypescriptStringTemplate.PuertsByteBufImports); + } + else + { + fileContent.Add(string.Format(TypescriptStringTemplate.BrightByteBufImportsFormat, brightRequirePath)); + } + } + + if (args.EmbedBrightTypes) + { + fileContent.Add(isGenBinary ? TypescriptStringTemplate.VectorTypesByteBuf : TypescriptStringTemplate.VectorTypesJson); + if (isGenBinary) + { + fileContent.Add(TypescriptStringTemplate.SerializeTypes); + } + } + else + { + if (isGenBinary) + { + fileContent.Add(string.Format(TypescriptStringTemplate.SerializeImportsFormat, brightRequirePath)); + } + fileContent.Add(string.Format(TypescriptStringTemplate.VectorImportsFormat, brightRequirePath)); + } + + fileContent.Add(@$"export namespace {ctx.TopModule} {{"); + }; + + Action> postContent = (fileContent) => + { + fileContent.Add("}"); // end of topmodule + }; + + GenerateCodeMonolithic(ctx, "Types.ts", lines, preContent, postContent); + } + + private void GenPythonCodes(GenContext ctx) + { + string genType = ctx.GenType; + ctx.Render = CreateCodeRender(genType); + ctx.Lan = GetLanguage(genType); + + var isPython3 = genType.Contains("python3"); + + var lines = new List(10000); + Action> preContent = (fileContent) => + { + if (isPython3) + { + fileContent.Add(PythonStringTemplates.ImportTython3Enum); + } + fileContent.Add(PythonStringTemplates.PythonVectorTypes); + }; + + GenerateCodeMonolithic(ctx, "Types.py", lines, preContent, null); -class Vector3: - def __init__(self, x, y, z): - self.x = x - self.y = y - self.z = z - def __str__(self): - return '{%f,%f,%f}' % (self.x, self.y, self.z) - @staticmethod - def fromJson(_json_): - x = _json_['x'] - y = _json_['y'] - z = _json_['z'] - if (x == None or y == None or z == None): - raise Exception() - return Vector3(x, y, z) + ctx.Tasks.Add(Task.Run(() => + { + var moduleInitContent = ""; + var initFile = "__init__.py"; -class Vector4: - def __init__(self, x, y, z, w): - self.x = x - self.y = y - self.z = z - self.w = w - def __str__(self): - return '{%g,%g,%g,%g}' % (self.x, self.y, self.z, self.w) - - @staticmethod - def fromJson(_json_): - x = _json_['x'] - y = _json_['y'] - z = _json_['z'] - w = _json_['w'] - if (x == None or y == None or z == None or w == None): - raise Exception() - return Vector4(x, y, z, w) + var initMd5 = CacheFileUtil.GenMd5AndAddCache(initFile, moduleInitContent); + ctx.GenCodeFilesInOutputCodeDir.Add(new FileInfo() { FilePath = initFile, MD5 = initMd5 }); + })); + } -"; + private void GenCppCode(GenContext ctx) + { + var render = new CppCodeBinRender(); + // 将所有 头文件定义 生成到一个文件 + // 按照 const,enum,bean,table, service 的顺序生成 + + ctx.Tasks.Add(Task.Run(() => + { + var headerFileContent = new List + { + @$" +#pragma once +#include + +#include ""bright/serialization/ByteBuf.h"" +#include ""bright/CfgBean.hpp"" + +using ByteBuf = bright::serialization::ByteBuf; + +namespace {ctx.TopModule} +{{ + +" + }; + + foreach (var type in ctx.ExportTypes) + { + if (type is DefEnum e) + { + headerFileContent.Add(render.Render(e)); + } + } + + foreach (var type in ctx.ExportTypes) + { + if (type is DefConst c) + { + headerFileContent.Add(render.Render(c)); + } + } + + foreach (var type in ctx.ExportTypes) + { + if (type is DefBean e) + { + headerFileContent.Add(render.RenderForwardDefine(e)); + } + } + + foreach (var type in ctx.ExportTypes) + { + if (type is DefBean e) + { + headerFileContent.Add(render.Render(e)); + } + } + + foreach (var type in ctx.ExportTables) + { + headerFileContent.Add(render.Render(type)); + } + + headerFileContent.Add(render.RenderService("Tables", ctx.TopModule, ctx.ExportTables)); + + headerFileContent.Add("}"); // end of topmodule + + var content = FileHeaderUtil.ConcatAutoGenerationHeader(string.Join('\n', headerFileContent), ELanguage.CPP); + var file = "gen_types.h"; + var md5 = CacheFileUtil.GenMd5AndAddCache(file, content); + ctx.GenCodeFilesInOutputCodeDir.Add(new FileInfo() { FilePath = file, MD5 = md5 }); + })); + + var beanTypes = ctx.ExportTypes.Where(c => c is DefBean).ToList(); + + int TYPE_PER_STUB_FILE = 100; + + for (int i = 0, n = (beanTypes.Count + TYPE_PER_STUB_FILE - 1) / TYPE_PER_STUB_FILE; i < n; i++) + { + int index = i; + ctx.Tasks.Add(Task.Run(() => + { + int startIndex = index * TYPE_PER_STUB_FILE; + var content = FileHeaderUtil.ConcatAutoGenerationHeader( + render.RenderStub(ctx.TopModule, beanTypes.GetRange(startIndex, Math.Min(TYPE_PER_STUB_FILE, beanTypes.Count - startIndex))), + ELanguage.CPP); + var file = $"gen_stub_{index}.cpp"; + var md5 = CacheFileUtil.GenMd5AndAddCache(file, content); + ctx.GenCodeFilesInOutputCodeDir.Add(new FileInfo() { FilePath = file, MD5 = md5 }); + })); + } + } + + private void GenCppUeEditor(GenContext ctx) + { + var render = new UE4EditorCppRender(); + + var renderTypes = ctx.Assembly.Types.Values.Where(c => c is DefEnum || c is DefBean).ToList(); + + foreach (var c in renderTypes) + { + ctx.Tasks.Add(Task.Run(() => + { + var content = FileHeaderUtil.ConcatAutoGenerationHeader(render.RenderAny(c), ELanguage.CPP); + var file = "editor_" + RenderFileUtil.GetUeCppDefTypeHeaderFilePath(c.FullName); + var md5 = CacheFileUtil.GenMd5AndAddCache(file, content); + ctx.GenCodeFilesInOutputCodeDir.Add(new FileInfo() { FilePath = file, MD5 = md5 }); + })); + } + + int TYPE_PER_STUB_FILE = 200; + + for (int i = 0, n = (renderTypes.Count + TYPE_PER_STUB_FILE - 1) / TYPE_PER_STUB_FILE; i < n; i++) + { + int index = i; + ctx.Tasks.Add(Task.Run(() => + { + int startIndex = index * TYPE_PER_STUB_FILE; + var content = FileHeaderUtil.ConcatAutoGenerationHeader( + render.RenderStub(renderTypes.GetRange(startIndex, Math.Min(TYPE_PER_STUB_FILE, renderTypes.Count - startIndex))), + ELanguage.CPP); + var file = $"stub_{index}.cpp"; + var md5 = CacheFileUtil.GenMd5AndAddCache(file, content); + ctx.GenCodeFilesInOutputCodeDir.Add(new FileInfo() { FilePath = file, MD5 = md5 }); + })); + } + } + + private void GenCsUnityEditor(GenContext ctx) + { + var render = new EditorCsRender(); + foreach (var c in ctx.Assembly.Types.Values) + { + ctx.Tasks.Add(Task.Run(() => + { + var content = FileHeaderUtil.ConcatAutoGenerationHeader(render.RenderAny(c), ELanguage.CS); + var file = RenderFileUtil.GetDefTypePath(c.FullName, ELanguage.CS); + var md5 = CacheFileUtil.GenMd5AndAddCache(file, content); + ctx.GenCodeFilesInOutputCodeDir.Add(new FileInfo() { FilePath = file, MD5 = md5 }); + })); + } + } + + private void GenCppUeBp(GenContext ctx) + { + var render = new UE4BpCppRender(); + foreach (var c in ctx.ExportTypes) + { + if (!(c is DefEnum || c is DefBean)) + { + continue; + } + + ctx.Tasks.Add(Task.Run(() => + { + var content = FileHeaderUtil.ConcatAutoGenerationHeader(render.RenderAny(c), ELanguage.CPP); + var file = "bp_" + RenderFileUtil.GetUeCppDefTypeHeaderFilePath(c.FullName); + var md5 = CacheFileUtil.GenMd5AndAddCache(file, content); + ctx.GenCodeFilesInOutputCodeDir.Add(new FileInfo() { FilePath = file, MD5 = md5 }); + })); + } + } + + private void GenDataScatter(GenContext ctx) + { + string genType = ctx.GenType; + foreach (var c in ctx.ExportTables) + { + ctx.Tasks.Add(Task.Run(() => + { + var content = DataExporterUtil.ToOutputData(c, ctx.Assembly.GetTableExportDataList(c), genType); + var file = GetOutputFileName(genType, c.OutputDataFile); + var md5 = CacheFileUtil.GenMd5AndAddCache(file, content); + ctx.GenDataFilesInOutputDataDir.Add(new FileInfo() { FilePath = file, MD5 = md5 }); + })); + } + } + + private async Task GenJsonDataMonolithic(GenContext ctx) + { + var exportTables = ctx.ExportTables; + List> allJsonTask = new List>(); + foreach (var c in exportTables) + { + allJsonTask.Add(Task.Run(() => + { + return DataExporterUtil.ToOutputData(c, ctx.Assembly.GetTableExportDataList(c), "data_json"); + })); + } + await Task.WhenAll(allJsonTask); + + int estimatedCapacity = allJsonTask.Sum(t => t.Result.Length + 100); + var sb = new MemoryStream(estimatedCapacity); + sb.Write(System.Text.Encoding.UTF8.GetBytes("{\n")); + for (int i = 0; i < exportTables.Count; i++) + { + if (i != 0) + { + sb.Write(System.Text.Encoding.UTF8.GetBytes((",\n"))); + } + sb.Write(System.Text.Encoding.UTF8.GetBytes("\"" + exportTables[i].Name + "\":")); + sb.Write(allJsonTask[i].Result); + } + sb.Write(System.Text.Encoding.UTF8.GetBytes("\n}")); + + var content = sb.ToArray(); + s_logger.Debug("estimated size:{0} actual size:{1}", estimatedCapacity, content.Length); + var outputFile = ctx.GenArgs.OutputDataJsonMonolithicFile; + var md5 = CacheFileUtil.GenMd5AndAddCache(outputFile, content); + ctx.GenScatteredFiles.Add(new FileInfo() { FilePath = outputFile, MD5 = md5 }); + } + + private void GenResourceList(GenContext ctx) + { + var genDataTasks = new List>>(); + foreach (var c in ctx.ExportTables) + { + genDataTasks.Add(Task.Run(() => + { + return DataExporterUtil.ExportResourceList(ctx.Assembly.GetTableExportDataList(c)); + })); + } + + ctx.Tasks.Add(Task.Run(async () => + { + var ress = new HashSet<(string, string)>(10000); + var resourceLines = new List(10000); + foreach (var task in genDataTasks) + { + foreach (var ri in await task) + { + if (ress.Add((ri.Resource, ri.Tag))) + { + resourceLines.Add($"{ri.Resource},{ri.Tag}"); + } + } + } + var file = ctx.GenArgs.OutputDataResourceListFile; + var content = string.Join("\n", resourceLines); + var md5 = CacheFileUtil.GenMd5AndAddCache(file, content); + + ctx.GenScatteredFiles.Add(new FileInfo() { FilePath = file, MD5 = md5 }); + })); + } } } diff --git a/src/Luban.Job.Cfg/Source/TypeVisitors/GoBinImport.cs b/src/Luban.Job.Cfg/Source/TypeVisitors/GoBinImport.cs new file mode 100644 index 0000000..e627243 --- /dev/null +++ b/src/Luban.Job.Cfg/Source/TypeVisitors/GoBinImport.cs @@ -0,0 +1,52 @@ +using Luban.Job.Common.Types; +using Luban.Job.Common.TypeVisitors; +using System.Collections.Generic; + +namespace Luban.Job.Cfg.TypeVisitors +{ + class GoBinImport : DecoratorActionVisitor> + { + public static GoBinImport Ins { get; } = new(); + + public override void DoAccept(TType type, HashSet x) + { + + } + + public override void Accept(TArray type, HashSet x) + { + type.ElementType.Apply(this, x); + } + + public override void Accept(TList type, HashSet x) + { + type.ElementType.Apply(this, x); + } + + public override void Accept(TSet type, HashSet x) + { + + } + + public override void Accept(TMap type, HashSet x) + { + type.KeyType.Apply(this, x); + type.ValueType.Apply(this, x); + } + + public override void Accept(TVector2 type, HashSet x) + { + x.Add("bright/math"); + } + + public override void Accept(TVector3 type, HashSet x) + { + x.Add("bright/math"); + } + + public override void Accept(TVector4 type, HashSet x) + { + x.Add("bright/math"); + } + } +} diff --git a/src/Luban.Job.Cfg/Source/TypeVisitors/GoDeserializeVisitor.cs b/src/Luban.Job.Cfg/Source/TypeVisitors/GoDeserializeBinVisitor.cs similarity index 81% rename from src/Luban.Job.Cfg/Source/TypeVisitors/GoDeserializeVisitor.cs rename to src/Luban.Job.Cfg/Source/TypeVisitors/GoDeserializeBinVisitor.cs index ebe92e2..9d8dce5 100644 --- a/src/Luban.Job.Cfg/Source/TypeVisitors/GoDeserializeVisitor.cs +++ b/src/Luban.Job.Cfg/Source/TypeVisitors/GoDeserializeBinVisitor.cs @@ -3,9 +3,9 @@ using Luban.Job.Common.TypeVisitors; namespace Luban.Job.Cfg.TypeVisitors { - class GoDeserializeVisitor : DecoratorFuncVisitor + class GoDeserializeBinVisitor : DecoratorFuncVisitor { - public static GoDeserializeVisitor Ins { get; } = new GoDeserializeVisitor(); + public static GoDeserializeBinVisitor Ins { get; } = new GoDeserializeBinVisitor(); public override string DoAccept(TType type, string fieldName, string bufName) { diff --git a/src/Luban.Job.Cfg/Source/TypeVisitors/GoDeserializeJsonUndering2Visitor.cs b/src/Luban.Job.Cfg/Source/TypeVisitors/GoDeserializeJsonUndering2Visitor.cs index 3720c8d..3ae9f9b 100644 --- a/src/Luban.Job.Cfg/Source/TypeVisitors/GoDeserializeJsonUndering2Visitor.cs +++ b/src/Luban.Job.Cfg/Source/TypeVisitors/GoDeserializeJsonUndering2Visitor.cs @@ -91,7 +91,7 @@ namespace Luban.Job.Cfg.TypeVisitors public string Accept(TBean type, string varName, string bufName) { - return $"{{ var _ok_ bool; var _x_ map[string]interface{{}}; if _x_, _ok_ = {bufName}.(map[string]interface{{}}); !_ok_ {{ err = errors.New(\"{varName} error\"); return }}; if {varName}, err = {(type.Bean.IsAbstractType ? $"NewChild{type.Bean.GoFullName}(_x_)" : $"New{ type.Bean.GoFullName} (_x_)")}; err != nil {{ return }} }}"; + return $"{{ var _ok_ bool; var _x_ map[string]interface{{}}; if _x_, _ok_ = {bufName}.(map[string]interface{{}}); !_ok_ {{ err = errors.New(\"{varName} error\"); return }}; if {varName}, err = {($"New{ type.Bean.GoFullName}(_x_)")}; err != nil {{ return }} }}"; } public string Accept(TArray type, string varName, string bufName) diff --git a/src/Luban.Job.Cfg/Source/TypeVisitors/GoDeserializeJsonUnderingVisitor.cs b/src/Luban.Job.Cfg/Source/TypeVisitors/GoDeserializeJsonUnderingVisitor.cs index 50a8d44..aac0f92 100644 --- a/src/Luban.Job.Cfg/Source/TypeVisitors/GoDeserializeJsonUnderingVisitor.cs +++ b/src/Luban.Job.Cfg/Source/TypeVisitors/GoDeserializeJsonUnderingVisitor.cs @@ -91,7 +91,7 @@ namespace Luban.Job.Cfg.TypeVisitors public string Accept(TBean type, string varName, string fieldName, string bufName) { - return $"{{ var _ok_ bool; var _x_ map[string]interface{{}}; if _x_, _ok_ = {bufName}[\"{fieldName}\"].(map[string]interface{{}}); !_ok_ {{ err = errors.New(\"{fieldName} error\"); return }}; if {varName}, err = {(type.Bean.IsAbstractType ? $"NewChild{type.Bean.GoFullName}(_x_)" : $"New{ type.Bean.GoFullName} (_x_)")}; err != nil {{ return }} }}"; + return $"{{ var _ok_ bool; var _x_ map[string]interface{{}}; if _x_, _ok_ = {bufName}[\"{fieldName}\"].(map[string]interface{{}}); !_ok_ {{ err = errors.New(\"{fieldName} error\"); return }}; if {varName}, err = {($"New{ type.Bean.GoFullName}(_x_)")}; err != nil {{ return }} }}"; } diff --git a/src/Luban.Job.Cfg/Source/TypeVisitors/GoDeserializeUnderingVisitor.cs b/src/Luban.Job.Cfg/Source/TypeVisitors/GoDeserializeUnderingVisitor.cs index 7583a14..4ca50f8 100644 --- a/src/Luban.Job.Cfg/Source/TypeVisitors/GoDeserializeUnderingVisitor.cs +++ b/src/Luban.Job.Cfg/Source/TypeVisitors/GoDeserializeUnderingVisitor.cs @@ -79,8 +79,7 @@ namespace Luban.Job.Cfg.TypeVisitors public string Accept(TBean type, string fieldName, string bufName) { - return $"{{ if {fieldName}, err = {(type.Bean.IsAbstractType ? $"NewChild{type.Bean.GoFullName}({bufName})" : $"New{ type.Bean.GoFullName} ({ bufName})")}; err != nil {{ return }} }}"; - //return type.Bean.IsAbstractType ? $"NewChild{type.Bean.GoFullName}({bufName})" : $"New{ type.Bean.GoFullName} ({ bufName})"; + return $"{{ if {fieldName}, err = {($"New{type.Bean.GoFullName}({bufName})")}; err != nil {{ return }} }}"; } @@ -92,7 +91,7 @@ namespace Luban.Job.Cfg.TypeVisitors if _n_, err = {bufName}.ReadSize(); err != nil {{return}} for i := 0 ; i < _n_ ; i++ {{ var _e_ {elementType.Apply(GoTypeNameVisitor.Ins)} - {elementType.Apply(GoDeserializeVisitor.Ins, "_e_", bufName)} + {elementType.Apply(GoDeserializeBinVisitor.Ins, "_e_", bufName)} {fieldName} = append({fieldName}, _e_) }} }} @@ -122,9 +121,9 @@ namespace Luban.Job.Cfg.TypeVisitors if _n_, err = {bufName}.ReadSize(); err != nil {{return}} for i := 0 ; i < _n_ ; i++ {{ var _key_ {type.KeyType.Apply(GoTypeNameVisitor.Ins)} - {type.KeyType.Apply(GoDeserializeVisitor.Ins, "_key_", bufName)} + {type.KeyType.Apply(GoDeserializeBinVisitor.Ins, "_key_", bufName)} var _value_ {type.ValueType.Apply(GoTypeNameVisitor.Ins)} - {type.ValueType.Apply(GoDeserializeVisitor.Ins, "_value_", bufName)} + {type.ValueType.Apply(GoDeserializeBinVisitor.Ins, "_value_", bufName)} {fieldName}[_key_] = _value_ }} }}"; diff --git a/src/Luban.Job.Cfg/Source/TypeVisitors/CollectGoImport.cs b/src/Luban.Job.Cfg/Source/TypeVisitors/GoJsonImport.cs similarity index 90% rename from src/Luban.Job.Cfg/Source/TypeVisitors/CollectGoImport.cs rename to src/Luban.Job.Cfg/Source/TypeVisitors/GoJsonImport.cs index 59cc7e2..03eec3f 100644 --- a/src/Luban.Job.Cfg/Source/TypeVisitors/CollectGoImport.cs +++ b/src/Luban.Job.Cfg/Source/TypeVisitors/GoJsonImport.cs @@ -4,9 +4,9 @@ using System.Collections.Generic; namespace Luban.Job.Cfg.TypeVisitors { - class CollectGoImport : DecoratorActionVisitor> + class GoJsonImport : DecoratorActionVisitor> { - public static CollectGoImport Ins { get; } = new CollectGoImport(); + public static GoJsonImport Ins { get; } = new(); public override void DoAccept(TType type, HashSet x) { diff --git a/src/Luban.Job.Cfg/Source/Utils/DataExporterUtil.cs b/src/Luban.Job.Cfg/Source/Utils/DataExporterUtil.cs index 7148c79..6d52a61 100644 --- a/src/Luban.Job.Cfg/Source/Utils/DataExporterUtil.cs +++ b/src/Luban.Job.Cfg/Source/Utils/DataExporterUtil.cs @@ -1,4 +1,5 @@ using Bright.Serialization; +using Luban.Job.Cfg.DataExporters; using Luban.Job.Cfg.Datas; using Luban.Job.Cfg.DataVisitors; using Luban.Job.Cfg.Defs; diff --git a/src/Luban.Job.Common/Source/Generate/ICodeRender.cs b/src/Luban.Job.Common/Source/Generate/ICodeRender.cs new file mode 100644 index 0000000..22038f4 --- /dev/null +++ b/src/Luban.Job.Common/Source/Generate/ICodeRender.cs @@ -0,0 +1,16 @@ +using Luban.Job.Common.Defs; +using System.Collections.Generic; + +namespace Luban.Job.Common.Generate +{ + public interface ICodeRender where T : DefTypeBase + { + string RenderAny(DefTypeBase o); + + string Render(DefConst c); + + string Render(DefEnum c); + + string RenderService(string name, string module, List tables); + } +} diff --git a/src/Luban.Job.Common/Source/TypeVisitors/CsDefineTypeName.cs b/src/Luban.Job.Common/Source/TypeVisitors/CsDefineTypeName.cs index 8d443d6..fc0d0b8 100644 --- a/src/Luban.Job.Common/Source/TypeVisitors/CsDefineTypeName.cs +++ b/src/Luban.Job.Common/Source/TypeVisitors/CsDefineTypeName.cs @@ -16,6 +16,11 @@ namespace Luban.Job.Common.TypeVisitors return type.Apply(CsUnderingDefineTypeName.Ins); } + public override string Accept(TText type) + { + return type.Apply(CsUnderingDefineTypeName.Ins); + } + public override string Accept(TBean type) { return type.Apply(CsUnderingDefineTypeName.Ins); diff --git a/src/Luban.Job.Common/Source/Utils/FileHeaderUtil.cs b/src/Luban.Job.Common/Source/Utils/FileHeaderUtil.cs index d04a329..f99e5f3 100644 --- a/src/Luban.Job.Common/Source/Utils/FileHeaderUtil.cs +++ b/src/Luban.Job.Common/Source/Utils/FileHeaderUtil.cs @@ -42,5 +42,15 @@ namespace Luban.Job.Common.Utils default: return AUTO_GENERATE_C_LIKE + txt; } } + + public static string GetAutoGenerationHeader(ELanguage lan) + { + switch (lan) + { + case ELanguage.LUA: return AUTO_GENERATE_LUA; + case ELanguage.PYTHON: return AUTO_GENERATE_PYTHON; + default: return AUTO_GENERATE_C_LIKE; + } + } } } diff --git a/src/Luban.Job.Common/Source/Utils/LuaStringTemplate.cs b/src/Luban.Job.Common/Source/Utils/LuaStringTemplate.cs new file mode 100644 index 0000000..2bb146c --- /dev/null +++ b/src/Luban.Job.Common/Source/Utils/LuaStringTemplate.cs @@ -0,0 +1,107 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Luban.Job.Common.Utils +{ + public static class LuaStringTemplate + { + public const string BaseDefines = @" +{{ + consts = x.consts + enums = x.enums + beans = x.beans + tables = x.tables +}} +local setmetatable = setmetatable +local pairs = pairs +local ipairs = ipairs +local tinsert = table.insert + +local function SimpleClass() + local class = {} + class.__index = class + class.New = function(...) + local ctor = class.ctor + local o = ctor and ctor(...) or {} + setmetatable(o, class) + return o + end + return class +end + + +local function get_map_size(m) + local n = 0 + for _ in pairs(m) do + n = n + 1 + end + return n +end"; + + public const string MethodHeader = @"local function InitTypes(methods) + local readBool = methods.readBool + local readByte = methods.readByte + local readShort = methods.readShort + local readFshort = methods.readFshort + local readInt = methods.readInt + local readFint = methods.readFint + local readLong = methods.readLong + local readFlong = methods.readFlong + local readFloat = methods.readFloat + local readDouble = methods.readDouble + local readSize = methods.readSize + + local readString = methods.readString + + local function readVector2(bs) + return { x = readFloat(bs), y = readFloat(bs) } + end + + local function readVector3(bs) + return { x = readFloat(bs), y = readFloat(bs), z = readFloat(bs) } + end + + local function readVector4(bs) + return { x = readFloat(bs), y = readFloat(bs), z = readFloat(bs), w = readFloat(bs) } + end + + local function readList(bs, keyFun) + local list = {} + local v + for i = 1, readSize(bs) do + tinsert(list, keyFun(bs)) + end + return list + end + + local readArray = readList + + local function readSet(bs, keyFun) + local set = {} + local v + for i = 1, readSize(bs) do + tinsert(set, keyFun(bs)) + end + return set + end + + local function readMap(bs, keyFun, valueFun) + local map = {} + for i = 1, readSize(bs) do + local k = keyFun(bs) + local v = valueFun(bs) + map[k] = v + end + return map + end + + local function readNullableBool(bs) + if readBool(bs) then + return readBool(bs) + end + end"; + } +} diff --git a/src/Luban.Job.Common/Source/Utils/PythonStringTemplates.cs b/src/Luban.Job.Common/Source/Utils/PythonStringTemplates.cs new file mode 100644 index 0000000..c0422a4 --- /dev/null +++ b/src/Luban.Job.Common/Source/Utils/PythonStringTemplates.cs @@ -0,0 +1,70 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Luban.Job.Common.Utils +{ + public class PythonStringTemplates + { + public const string PythonVectorTypes = @" +class Vector2: + def __init__(self, x, y): + self.x = x + self.y = y + def __str__(self): + return '{%g,%g}' % (self.x, self.y) + + @staticmethod + def fromJson(_json_): + x = _json_['x'] + y = _json_['y'] + if (x == None or y == None): + raise Exception() + return Vector2(x, y) + + +class Vector3: + def __init__(self, x, y, z): + self.x = x + self.y = y + self.z = z + def __str__(self): + return '{%f,%f,%f}' % (self.x, self.y, self.z) + @staticmethod + def fromJson(_json_): + x = _json_['x'] + y = _json_['y'] + z = _json_['z'] + if (x == None or y == None or z == None): + raise Exception() + return Vector3(x, y, z) + +class Vector4: + def __init__(self, x, y, z, w): + self.x = x + self.y = y + self.z = z + self.w = w + def __str__(self): + return '{%g,%g,%g,%g}' % (self.x, self.y, self.z, self.w) + + @staticmethod + def fromJson(_json_): + x = _json_['x'] + y = _json_['y'] + z = _json_['z'] + w = _json_['w'] + if (x == None or y == None or z == None or w == None): + raise Exception() + return Vector4(x, y, z, w) + +"; + + public const string ImportTython3Enum = @" +from enum import Enum +import abc +"; + } +} diff --git a/src/Luban.Job.Common/Source/Utils/TypescriptBrightTypeTemplates.cs b/src/Luban.Job.Common/Source/Utils/TypescriptStringTemplate.cs similarity index 98% rename from src/Luban.Job.Common/Source/Utils/TypescriptBrightTypeTemplates.cs rename to src/Luban.Job.Common/Source/Utils/TypescriptStringTemplate.cs index 93270fc..9b70e86 100644 --- a/src/Luban.Job.Common/Source/Utils/TypescriptBrightTypeTemplates.cs +++ b/src/Luban.Job.Common/Source/Utils/TypescriptStringTemplate.cs @@ -6,7 +6,7 @@ using System.Threading.Tasks; namespace Luban.Job.Common.Utils { - public static class TypescriptBrightTypeTemplates + public static class TypescriptStringTemplate { public const string PuertsByteBufImports = @" import {Bright} from 'csharp' diff --git a/src/Luban.Job.Db/Source/JobController.cs b/src/Luban.Job.Db/Source/JobController.cs index bc5e355..e4fc90b 100644 --- a/src/Luban.Job.Db/Source/JobController.cs +++ b/src/Luban.Job.Db/Source/JobController.cs @@ -135,11 +135,11 @@ namespace Luban.Job.Db { var fileContent = new List(); - fileContent.Add(string.Format(TypescriptBrightTypeTemplates.BrightByteBufImportsFormat, brightRequirePath)); + fileContent.Add(string.Format(TypescriptStringTemplate.BrightByteBufImportsFormat, brightRequirePath)); - fileContent.Add(string.Format(TypescriptBrightTypeTemplates.SerializeImportsFormat, brightRequirePath)); - fileContent.Add(string.Format(TypescriptBrightTypeTemplates.ProtocolImportsFormat, brightRequirePath)); - fileContent.Add(string.Format(TypescriptBrightTypeTemplates.VectorImportsFormat, brightRequirePath)); + fileContent.Add(string.Format(TypescriptStringTemplate.SerializeImportsFormat, brightRequirePath)); + fileContent.Add(string.Format(TypescriptStringTemplate.ProtocolImportsFormat, brightRequirePath)); + fileContent.Add(string.Format(TypescriptStringTemplate.VectorImportsFormat, brightRequirePath)); fileContent.Add($"import {{FieldLogger, FieldLoggerGeneric1, FieldLoggerGeneric2}} from '{brightRequirePath}/transaction/FieldLogger'"); fileContent.Add($"import TxnBeanBase from '{brightRequirePath}/transaction/TxnBeanBase'"); fileContent.Add($"import {{TxnTable, TxnTableGeneric}} from '{brightRequirePath}/transaction/TxnTable'"); diff --git a/src/Luban.Job.Proto/Source/JobController.cs b/src/Luban.Job.Proto/Source/JobController.cs index cd55496..76d15e2 100644 --- a/src/Luban.Job.Proto/Source/JobController.cs +++ b/src/Luban.Job.Proto/Source/JobController.cs @@ -159,23 +159,23 @@ namespace Luban.Job.Proto var fileContent = new List(); if (args.UsePuertsByteBuf) { - fileContent.Add(TypescriptBrightTypeTemplates.PuertsByteBufImports); + fileContent.Add(TypescriptStringTemplate.PuertsByteBufImports); } else { - fileContent.Add(string.Format(TypescriptBrightTypeTemplates.BrightByteBufImportsFormat, brightRequirePath)); + fileContent.Add(string.Format(TypescriptStringTemplate.BrightByteBufImportsFormat, brightRequirePath)); } if (args.EmbedBrightTypes) { - fileContent.Add(TypescriptBrightTypeTemplates.VectorTypesByteBuf); - fileContent.Add(TypescriptBrightTypeTemplates.SerializeTypes); - fileContent.Add(TypescriptBrightTypeTemplates.ProtoTypes); + fileContent.Add(TypescriptStringTemplate.VectorTypesByteBuf); + fileContent.Add(TypescriptStringTemplate.SerializeTypes); + fileContent.Add(TypescriptStringTemplate.ProtoTypes); } else { - fileContent.Add(string.Format(TypescriptBrightTypeTemplates.SerializeImportsFormat, brightRequirePath)); - fileContent.Add(string.Format(TypescriptBrightTypeTemplates.ProtocolImportsFormat, brightRequirePath)); - fileContent.Add(string.Format(TypescriptBrightTypeTemplates.VectorImportsFormat, brightRequirePath)); + fileContent.Add(string.Format(TypescriptStringTemplate.SerializeImportsFormat, brightRequirePath)); + fileContent.Add(string.Format(TypescriptStringTemplate.ProtocolImportsFormat, brightRequirePath)); + fileContent.Add(string.Format(TypescriptStringTemplate.VectorImportsFormat, brightRequirePath)); } fileContent.Add(@$"export namespace {ass.TopModule} {{");