public static void SavePackageId(Template t, string outDir) { var allpkgs = t.Structs.Where(a => a.IsPackage).OrderByDescending(a => a.RefCounter); // 生成 packageId -- ProjectName + Namespace + Name 的 csv 文件 // 根据 接收者生成 pkgId 的规则,记录接收者的 ProjectName. var sb = new StringBuilder(); var lst = new List<string>(); foreach (var pkg in t.Structs.Where(a => a.IsPackage).OrderByDescending(a => a.RefCounter)) { var pn = ""; if (pkg.Projects.Count > 0) { var o = pkg.Projects.Find(a => a.SendRecvType == TemplateLibrary.SendRecvTypes.SendAndRecv || a.SendRecvType == TemplateLibrary.SendRecvTypes.RecvOnly); if (o != null) { pn = o.Project.Name; } } lst.Add(pkg.PackageId + "," + pn + "," + pkg.Namespace + "," + pkg.Name); } lst.Sort((a, b) => { var aa = a.Split(','); var bb = b.Split(','); return long.Parse(aa[0]).CompareTo(long.Parse(bb[0])); }); sb.Append(string.Join(Environment.NewLine, lst)); sb.WriteToFile(Path.Combine(outDir, t.Name + "_packageId_config.csv")); }
public void WriteFiles(string path) { Directory.CreateDirectory(path); var sb = new StringBuilder(); WriteFile(sb); var schemaFileName = $"{path}/{Name}.cs"; sb.WriteToFile(schemaFileName); foreach (var tableClassModel in TableClassModels) { sb.Clear(); var tableFileName = $"{path}/{tableClassModel.ClassName}.cs"; tableClassModel.WriteFile(sb); sb.WriteToFile(tableFileName); } }
public static string Gen( Template sd, string outputDirPath, string fn ) { var sb = new StringBuilder(); try { sb.WriteToFile( Path.Combine( outputDirPath, fn + "_packets.lua" ), false ); } catch( Exception ex ) { return ex.Message; } return ""; }
public static string Gen(Template sd, string outputDirPath, string fn) { var sb = new StringBuilder(); try { sb.WriteToFile(Path.Combine(outputDirPath, fn + "_packets.lua"), false); } catch (Exception ex) { return(ex.Message); } return(""); }
public void ExtensionMethods_WriteToFile_WhenSavingStringBuilder_ExpectSavedFile() { //------------Setup for test-------------------------- var tmpFile = Path.GetTempFileName(); const string val = "<x><y>1</y></x>"; StringBuilder value = new StringBuilder(val); //------------Execute Test--------------------------- value.WriteToFile(tmpFile, Encoding.UTF8, new TxFileManager()); //------------Assert Results------------------------- var result = File.ReadAllText(tmpFile); // clean up ;) File.Delete(tmpFile); Assert.AreEqual(val, result, "WriteToFile did not write"); }
public void ExtensionMethods_WriteToFile_WhenSavingStringBuilderToFileWithExistingDataThatIsShorter_ExpectSavedFileWithNoMangle() { //------------Setup for test-------------------------- var tmpFile = Path.GetTempFileName(); File.WriteAllText(tmpFile, "this is going to be some very long test just to ensure we can over write it"); const string val = "<x><y>1</y></x>"; StringBuilder value = new StringBuilder(val); //------------Execute Test--------------------------- value.WriteToFile(tmpFile, Encoding.UTF8); //------------Assert Results------------------------- var result = File.ReadAllText(tmpFile); // clean up ;) File.Delete(tmpFile); Assert.AreEqual(val, result, "WriteToFile did not truncate"); }
public void ExtensionMethods_WriteToFile_RollbackIfError() { //------------Setup for test-------------------------- var tmpFile = Path.GetTempFileName(); File.WriteAllText(tmpFile, "this is going to be some very long test just to ensure we can over write it"); const string val = "<x><y>1</y></x>"; StringBuilder value = new StringBuilder(val); //------------Execute Test--------------------------- IFileManager fm = new TxFileManager(); value.WriteToFile(tmpFile, Encoding.UTF8, fm); //------------Assert Results------------------------- var result = File.ReadAllText(tmpFile); // clean up ;) File.Delete(tmpFile); Assert.AreEqual(val, result, "WriteToFile did not truncate"); }
public static string Gen( Template t, string outDir, string pn ) { _pn = pn; var ns = pn + "Packets"; ConvertNamespace( t, ns ); var sb = new StringBuilder(); sb.Append( @"#ifndef __" + pn.ToUpper() + @"_H__ #define __" + pn.ToUpper() + @"_H__ namespace " + pn + @"Packets {" ); foreach( var c in t.Classes ) { sb.Append( @" class " + c.Name + @";" ); } sb.Append( @" } namespace " + pn + @"Packets {" ); foreach( var c in t.Classes ) { sb.Append( ( c.Desc == "" ? "" : GetComment( c.Desc, 4 ) ) + @" class " + c.Name + @" : Memmoveable { PACKET_CLASS_HEADER" + ( IsPod( c ) ? "_POD" : "" ) + @"( " + c.Name + @" ); public: " ); foreach( var f in c.Fields ) { var tn = SplitTypeKeyword( GetTypeKeyword( f.Declare ), f.Declare ); sb.Append( ( f.Desc == "" ? "" : GetComment( f.Desc, 8 ) ) + @" " + tn.Key + " _" + f.Name.ToFirstLower() + tn.Value + ( ( GetDefaultValueByType( f ) != "" ) ? ( " = " + GetDefaultValueByType( f ) ) : "" ) + ";" ); } sb.Append( @" static void fill( FlatBuffer& fb" ); foreach( var f in c.Fields ) { var tn = GetTypeKeyword( f.Declare ); var atn = SplitTypeKeyword( GetTypeKeyword( f.Declare ), f.Declare ); if( f.Declare.DataType == DataTypes.Array ) { sb.Append( @" , " + atn.Key + "( &" + f.Name + " )" + atn.Value ); } else { sb.Append( @" , " + tn + " " + f.Name ); } } sb.Append( @" ); " ); foreach( var f in c.Fields ) { var tn = GetTypeKeyword( f.Declare ); var atn = SplitTypeKeyword( GetTypeKeyword( f.Declare ), f.Declare ); if( f.Get ) { sb.Append( @" " + tn + " const& get" + f.Name.ToFirstUpper() + @"();" ); } if( f.Set ) { if( IsSimpleType( f ) ) { if( f.Declare.DataType == DataTypes.Array ) { sb.Append( @" inline void set" + f.Name.ToFirstUpper() + @"( " + atn.Key + @"( &v )" + atn.Value + @" ) { _" + f.Name.ToFirstLower() + @" = v; }" ); } else { sb.Append( @" inline void set" + f.Name.ToFirstUpper() + @"( " + tn + @" v ) { _" + f.Name.ToFirstLower() + @" = v; }" ); } } else { sb.Append( @" template<typename VT> void set" + f.Name.ToFirstUpper() + @"( VT&& v ) { _" + f.Name.ToFirstLower() + @" = std::forward<VT>( v ); }" ); } } } sb.Append( @" };" ); } sb.Append( @" } #endif " ); try { sb.WriteToFile( Path.Combine( outDir, ns + ".h" ) ); } catch( Exception ex ) { return ex.Message; } sb.Clear(); sb.Append( @"#include ""Lib/All.h"" #include """ + ns + @".h"" namespace " + pn + @"Packets {" ); foreach( var c in t.Classes ) { sb.Append( @" ushort " + c.Name + @"::getTypeID() { return " + c.TypeID + @"; }" ); if( !IsPod( c ) ) { sb.Append( @" " + c.Name + @"::" + c.Name + @"( " + c.Name + @" const& other )" ); bool isFirst = true; foreach( var f in c.Fields ) { sb.Append( @" " + ( isFirst ? ":" : "," ) + " _" + f.Name.ToFirstLower() + @"( other._" + f.Name.ToFirstLower() + @" )" ); isFirst = false; } sb.Append( @" { } " + c.Name + @"::" + c.Name + @"( " + c.Name + @"&& other )" ); isFirst = true; foreach( var f in c.Fields ) { if( ( f.Declare.Class as Class != null ) && IsPod( (Class)f.Declare.Class ) ) { sb.Append( @" " + ( isFirst ? ":" : "," ) + " _" + f.Name.ToFirstLower() + @"( other._" + f.Name.ToFirstLower() + @" )" ); } else { sb.Append( @" " + ( isFirst ? ":" : "," ) + " _" + f.Name.ToFirstLower() + @"( std::move( other._" + f.Name.ToFirstLower() + @" ) )" ); } isFirst = false; } sb.Append( @" { } " + c.Name + @"& " + c.Name + @"::operator=( " + c.Name + @" const& other ) {" ); foreach( var f in c.Fields ) { sb.Append( @" _" + f.Name.ToFirstLower() + @" = other._" + f.Name.ToFirstLower() + @";" ); } sb.Append( @" return *this; } " + c.Name + @"& " + c.Name + @"::operator=( " + c.Name + @"&& other ) {" ); foreach( var f in c.Fields ) { if( ( f.Declare.Class as Class != null ) && IsPod( (Class)f.Declare.Class ) ) { sb.Append( @" _" + f.Name.ToFirstLower() + @" = other._" + f.Name.ToFirstLower() + @";" ); } else { sb.Append( @" _" + f.Name.ToFirstLower() + @" = std::move( other._" + f.Name.ToFirstLower() + @" );" ); } } sb.Append( @" return *this; } " ); } foreach( var f in c.Fields ) { if( f.Get ) { var tn = GetTypeKeyword( f.Declare ); sb.Append( @" " + tn + " const& " + c.Name + @"::get" + f.Name.ToFirstUpper() + @"() { return _" + f.Name.ToFirstLower() + @"; }" ); } } sb.Append( @" void " + c.Name + @"::fill( FlatBuffer& fb" ); foreach( var f in c.Fields ) { var tn = GetTypeKeyword( f.Declare ); var atn = SplitTypeKeyword( GetTypeKeyword( f.Declare ), f.Declare ); if( f.Declare.DataType == DataTypes.Array ) { sb.Append( @" , " + atn.Key + @"( &p" + f.Name.ToFirstUpper() + " )" + atn.Value ); } else { sb.Append( @" , " + tn + @" p" + f.Name.ToFirstUpper() ); } } sb.Append( @" ) {" ); if( c.Fields.Count > 0 ) { sb.Append( @" fb.writes(" ); foreach( var f in c.Fields ) { sb.Append( @" p" + f.Name.ToFirstUpper() + ( f == c.Fields[ c.Fields.Count - 1 ] ? "" : @", " ) ); } sb.Append( @" );" ); } sb.Append( @" }" ); sb.Append( @" void " + c.Name + @"::writeBuffer( FlatBuffer& fb ) const {" ); if( c.Fields.Count > 0 ) { sb.Append( @" fb.writes(" ); foreach( var f in c.Fields ) { sb.Append( @" _" + f.Name.ToFirstLower() + ( f == c.Fields[ c.Fields.Count - 1 ] ? "" : @", " ) ); } sb.Append( @" );" ); } sb.Append( @" } bool " + c.Name + @"::readBuffer( FlatBuffer& fb ) {" ); if( c.Fields.Count > 0 ) { sb.Append( @" return fb.reads(" ); foreach( var f in c.Fields ) { sb.Append( @" _" + f.Name.ToFirstLower() + ( f == c.Fields[ c.Fields.Count - 1 ] ? "" : @", " ) ); } sb.Append( @" );" ); } else { sb.Append( @" return true;" ); } sb.Append( @" } void " + c.Name + @"::writeBufferDirect( FlatBuffer& fb ) const {" ); if( c.Fields.Count > 0 ) { sb.Append( @" fb.writesDirect(" ); foreach( var f in c.Fields ) { sb.Append( @" _" + f.Name.ToFirstLower() + ( f == c.Fields[ c.Fields.Count - 1 ] ? "" : @", " ) ); } sb.Append( @" );" ); } sb.Append( @" } int " + c.Name + @"::getWriteBufferSize() const {" ); if( c.Fields.Count > 0 ) { sb.Append( @" return " ); foreach( var f in c.Fields ) { if( IsSimpleType( f ) ) { sb.Append( @" sizeof( _" + f.Name.ToFirstLower() + " )" ); } else { sb.Append( @" BufferUtils::getSizes( _" + f.Name.ToFirstLower() + " )" ); } sb.Append( f == c.Fields[ c.Fields.Count - 1 ] ? "" : @" + " ); } sb.Append( @";" ); } sb.Append( @" } " ); } sb.Append( @" } " ); try { sb.WriteToFile( Path.Combine( outDir, ns + ".cpp" ) ); } catch( Exception ex ) { return ex.Message; } System.Diagnostics.Process.Start( "explorer.exe", outDir ); return ""; }
public static string Gen(Template t, string outDir, string pn) { #region 生成 PkgTypes.java outDir = Path.Combine(outDir, "Java"); if (!Directory.Exists(outDir)) { try { Directory.CreateDirectory(outDir); } catch (Exception ex) { return(ex.Message); } } _pn = pn; var ns = pn + "PkgTypes"; var ms = pn + "Handler"; ConvertNamespace(t, ns); var sb = new StringBuilder(); // 生成所有枚举 foreach (var e in t.Enums) { sb.Clear(); sb.Append(@" package com.cdrdj.cspkgtypes;" + @" import java.util.ArrayList; import java.util.Date; import java.util.List; import com.cdrdj.is.ByteBuffer; import com.cdrdj.is.IBBReader; import com.cdrdj.is.IBBWriter; "); sb.Append(@""); if (!string.IsNullOrWhiteSpace(e.Desc)) { sb.Append(@" // " + e.Desc); } sb.Append(@" public enum " + e.Name + @" {"); for (int i = 0; i < e.Fields.Count; i++) { var ef = e.Fields[i]; sb.Append(@" " + ef.Name + "( (" + GetEnumTypeKeyword(e) + ")" + ef.Value + " )"); if (i != e.Fields.Count - 1) { sb.Append(@","); } else { sb.Append(@";"); } if (!string.IsNullOrWhiteSpace(ef.Desc)) { sb.Append("// " + ef.Desc); } } sb.Append(@" " + GetEnumTypeKeyword(e) + @" value;"); sb.Append(@" " + e.Name + @"( " + GetEnumTypeKeyword(e) + @" v ) { this.value = v; }"); sb.Append(@" public static " + e.Name + @" valueOf( int v ) { switch( v ) {"); for (int i = 0; i < e.Fields.Count; i++) { var ef = e.Fields[i]; sb.Append(@" case " + ef.Value + @": return " + ef.Name + ";"); } sb.Append(@" default: return null; } }"); sb.Append(@" };"); try { //sb.WriteToFile( Path.Combine( @"D:\erdj_project_shengcheng\java", e.Name + ".java" ) ); var outFile = Path.Combine(outDir, e.Name + ".java"); sb.WriteToFile(outFile); } catch (Exception ex) { return(ex.Message); } } Dictionary <int, string> dc = new Dictionary <int, string>(); int cmdId = 0; // 生成类声明 foreach (var c in t.Classes) { sb.Clear(); sb.Append(@" package com.cdrdj.cspkgtypes;" + @" import java.util.ArrayList; import java.util.Date; import java.util.List; import com.cdrdj.is.ByteBuffer; import com.cdrdj.is.IBBReader; import com.cdrdj.is.IBBWriter; "); cmdId++; sb.Append(@""); if (!string.IsNullOrWhiteSpace(c.Desc)) { sb.Append(@" // " + c.Desc); } sb.Append(@" public class " + c.Name + @" implements IBBWriter, IBBReader {"); // 生成类成员 foreach (var f in c.Fields) { //maomao var tn = GetTypeKeyword(f.Declare); sb.Append((f.Desc == "" ? "" : GetComment(f.Desc, 8)) + @" public " + tn + " " + f.Name.ToFirstLower()); if (f.Declare.DataType == DataTypes.Custom && f.Declare.Class != null && !f.Declare.Class.IsEnum) { sb.Append(@" = new " + tn + "()"); } else if (f.Declare.DataType == DataTypes.BuiltIn && f.Declare.Name == "DateTime") { sb.Append(@" = new " + tn + "(1,0,1,0,0,0)"); } else if (f.Declare.DataType == DataTypes.BuiltIn && f.Declare.Name == "String") { sb.Append(@" ="""""); } else if (f.Declare.DataType == DataTypes.Generic) { sb.Append(@" = new " + tn.Replace("List<", "ArrayList<") + "()"); } else if (f.Declare.DataType == DataTypes.Custom && f.Declare.Class != null && f.Declare.Class.IsEnum) { var myEnum = (Enum)f.Declare.Class; sb.Append(@" = " + GetEnumFristString(myEnum)); } else if (f.Declare.DataType == DataTypes.Array) { sb.Append(@" = new byte[ 0 ]"); } sb.Append(";"); } dc.Add(cmdId, c.Name); // 生成静态直写函数 sb.Append(@" public static final short commandType = " + cmdId + @"; "); sb.Append(@" public void WriteToBB( ByteBuffer bb ) {"); if (c.Fields.Count != 0) { for (int i = 0; i < c.Fields.Count; ++i) { sb.Append(@" bb."); var f = c.Fields[i]; sb.Append(GetWriteTypeBuffer(f.Declare)); sb.Append("( "); sb.Append(f.Name); if (f.Declare.Class != null && f.Declare.Class.IsEnum) { sb.Append(@".value"); } sb.Append(@" );"); } } sb.Append(@" } public void ReadFromBB( ByteBuffer bb ) {"); for (int i = 0; i < c.Fields.Count; ++i) { bool flag = false; sb.Append(@" "); var f = c.Fields[i]; sb.Append(f.Name); sb.Append(" = "); if (f.Declare.Class != null && f.Declare.Class.IsEnum) { var ooxx = (Enum)f.Declare.Class; sb.Append(ooxx.Name + ".valueOf( "); flag = true; } sb.Append("bb."); sb.Append(GetReadTypeBuffer(f.Declare)); sb.Append(@"("); if (f.Declare.Childs.Count > 0 && f.Declare.Childs[0].DataType == DataTypes.Custom) { sb.Append(" " + GetBufferString(f.Declare.Childs[0]) + ".class "); } else if (f.Declare.DataType == DataTypes.Custom && f.Declare.Class != null && !f.Declare.Class.IsEnum) { sb.Append(" " + GetBufferString(f.Declare) + ".class "); } if (f.Declare.DataType == DataTypes.Generic) { if (f.Declare.Childs.Count > 0 && f.Declare.Childs[0].DataType == DataTypes.Custom) { sb.Append(@","); } sb.Append(f.Declare.MinLen + @"," + f.Declare.MaxLen + " "); } else if ((f.Declare.DataType == DataTypes.BuiltIn && f.Declare.Name == "String") || f.Declare.DataType == DataTypes.Array) { sb.Append(@" " + f.Declare.MinLen + @"," + f.Declare.MaxLen + @" "); } if (flag) { sb.Append(@") "); } sb.Append(@");"); } sb.Append(@" } "); sb.Append(@" };"); try { //sb.WriteToFile( Path.Combine( @"D:\erdj_project_shengcheng\java", c.Name + ".java" ) ); var outFile = Path.Combine(outDir, c.Name + ".java"); sb.WriteToFile(outFile); } catch (Exception ex) { return(ex.Message); } } #endregion #region 生成 Rotate.java sb.Clear(); sb.Append(@" short cmdID = bb.ReadShort(); switch( cmdID ) {"); foreach (var dcItem in dc) { sb.Append(@" case " + dcItem.Key + @" : { " + dcItem.Value + @" myItem = null; try { myItem = bb.ReadClass( " + dcItem.Value + @".class ); } catch { System.out.println( ""ByteBuff Error"" ); } // code here break; }"); } sb.Append(@" default: break; }"); try { //sb.WriteToFile( Path.Combine( @"D:\erdj_project_shengcheng\java", "RotateJava.txt" ) ); var outFile = Path.Combine(outDir, "RotateJava.txt"); sb.WriteToFile(outFile); } catch (Exception ex) { return(ex.Message); } #endregion #region 生成 EnumToString.java sb.Clear(); sb.Append(@" public class EnumToString {"); foreach (var e in t.Enums) { sb.Append(@" public static string Get(" + e.Name + @" e ) { switch(e) {"); foreach (var ee in e.Fields) { sb.Append(@" case " + e.Name + "." + ee.Name + @": return """ + e.Name + "." + ee.Name + " " + ee.Desc + @""";"); } sb.Append(@" } }"); } sb.Append(@" }"); try { //sb.WriteToFile( Path.Combine( @"D:\svn\xieyi\java", "EnumToString.java" ) ); var outFile = Path.Combine(outDir, "EnumToString.java"); sb.WriteToFile(outFile); } catch (Exception ex) { return(ex.Message); } #endregion //System.Diagnostics.Process.Start( "explorer.exe", outDir ); return(""); }
public static string Gen(Template t, string outputDirPath, string pn) { _pn = pn; var sb = new StringBuilder(); sb.Clear(); sb.Append(@"using SerialHelper; // 解码函数数组声明 // public Action<Bytes>[] PacketHandlers; // 向数组存入对应的处理函数 // PacketHandlers = new Action<Bytes, params object[]>[ (int)" + pn + @"_AllClassEnums.ZMaxValue ]; "); foreach (var ns_ in t.Namespaces) { var ns = (ns_ != "" ? ns_ : pn); foreach (var c in t.Classes.Where(a => a.Namespace == ns_)) { var en = ns.Replace(".", "_") + "_" + c.Name; sb.Append(@" PacketHandlers[ (int)" + pn + @"_AllClassEnums." + en + @" ] = " + en + @";"); } } sb.Append(@" // 不获取标记位系列函数实现空壳 "); foreach (var ns_ in t.Namespaces) { var ns = (ns_ != "" ? ns_ : pn); foreach (var c in t.Classes.Where(a => a.Namespace == ns_)) { var en = ns.Replace(".", "_") + "_" + c.Name; sb.Append(@" private void " + en + @"( Bytes b, params object[] extPs ) { var o = new " + ns + @"." + c.Name + @"(); var rtv = o.readFrom( b ); if( rtv != ReadState.Success ) { return; // 这里放置解包错误处理代码 } // if( On_" + en + @" != null ) On_" + en + @"( o ); } "); } } sb.Append(@" // 获取标记位 "); foreach (var ns_ in t.Namespaces) { var ns = (ns_ != "" ? ns_ : pn); foreach (var c in t.Classes.Where(a => a.Namespace == ns_)) { var en = ns.Replace(".", "_") + "_" + c.Name; sb.Append(@" private void " + en + @"( Bytes b, params object[] ext_ps ) { var o = new " + ns + @"." + c.Name + @"(); var flags = new bool[ (int)" + ns + @"." + c.Name + @"_e.ZMaxValue ]; var rtv = o.readFrom( b, flags ); if( rtv != ReadState.Success ) { // 这里放置解包错误处理代码 return; } // read success code here if( On_" + en + @" != null ) On_" + en + @"( o ); "); foreach (var f in c.Fields) { sb.Append(@" if( flags[ (int)" + ns + @"." + c.Name + @"_e." + f.Name + @" ] ) { // 处理代码 if( On_" + en + @"_m_" + f.Name + @" != null ) On_" + en + @"_m_" + f.Name + @"( o ); }"); } sb.Append(@" } "); } } sb.Append(@" "); foreach (var ns_ in t.Namespaces) { var ns = (ns_ != "" ? ns_ : pn); foreach (var c in t.Classes.Where(a => a.Namespace == ns_)) { var en = ns.Replace(".", "_") + "_" + c.Name; sb.Append(@" public static event System.Action<" + ns + "." + c.Name + @"> On_" + en + @";"); foreach (var f in c.Fields) { sb.Append(@" public static event System.Action<" + ns + "." + c.Name + @"> On_" + en + @"_m_" + f.Name + @";"); } } } sb.Append(@" "); sb.Append(@" // 可能有用的扩展函数 public static byte[] toByteArray( this ISC o ) { var b = new Bytes(); b.write( o ); b.collapse(); return b._buf; } #region SyncSend /// <summary> /// 同步获取返回结果 /// </summary> public T SyncSend<T>( ISC cmd, int timeoutSec ) where T : ISC { string cb_ = Guid.NewGuid().ToString(); bool got_ = false; T rtv_ = default( T ); var func = new Action<string, T>( ( cb, o ) => { if( cb_ != cb ) return; got_ = true; rtv_ = o; } ); RegisterHandler<T>( func ); Send( cmd, cb_ ); for( int i = 0; i < timeoutSec * 10; ++i ) { if( got_ ) goto LabEnd; System.Threading.Thread.Sleep( 100 ); } LabEnd: UnregisterHandler<T>( func ); return rtv_; } private void RegisterHandler<T>( dynamic func ) where T : ISC {"); foreach (var ns_ in t.Namespaces) { var ns = (ns_ != "" ? ns_ : pn); foreach (var c in t.Classes.Where(a => a.Namespace == ns_)) { var en = ns.Replace(".", "_") + "_" + c.Name; sb.Append(@" if( typeof( T ) == typeof( " + ns + "." + c.Name + @" ) ) On_" + en + @" += func;"); } } sb.Append(@" } private void UnegisterHandler<T>( dynamic func ) where T : ISC {"); foreach (var ns_ in t.Namespaces) { var ns = (ns_ != "" ? ns_ : pn); foreach (var c in t.Classes.Where(a => a.Namespace == ns_)) { var en = ns.Replace(".", "_") + "_" + c.Name; sb.Append(@" if( typeof( T ) == typeof( " + ns + "." + c.Name + @" ) ) On_" + en + @" -= func;"); } } sb.Append(@" } #endregion "); try { sb.WriteToFile(Path.Combine(outputDirPath, pn + "_Samples.txt")); } catch (Exception ex) { return(ex.Message); } sb.Clear(); sb.Append(@"using SerialHelper; public static partial class " + pn + @"_AllClassHandler { public static ISC read( int opcode, byte[] buf ) { var b = new Bytes( buf, buf.Length ); switch( (" + pn + @"_AllClassEnums)opcode ) {"); foreach (var ns_ in t.Namespaces) { var ns = (ns_ != "" ? ns_ : pn); foreach (var c in t.Classes.Where(a => a.Namespace == ns_)) { var en = ns.Replace(".", "_") + "_" + c.Name; sb.Append(@" case " + pn + @"_AllClassEnums." + en + @": { var o = new " + ns + @"." + c.Name + @"(); var rtv = o.readFrom( b ); if( rtv != ReadState.Success ) return null; return o; }"); } } sb.Append(@" default: return null; } } } "); try { sb.WriteToFile(Path.Combine(outputDirPath, pn + "_AllClassHandler.cs")); } catch (Exception ex) { return(ex.Message); } sb.Clear(); sb.Append(@" public enum " + pn + @"_AllClassEnums {"); int idx = 0; foreach (var ns_ in t.Namespaces) { var ns = (ns_ != "" ? ns_ : pn); foreach (var c in t.Classes.Where(a => a.Namespace == ns_)) { var en = ns.Replace(".", "_") + "_" + c.Name; sb.Append(GetComment(c.Desc, 4) + @" " + en + @" = " + (idx++) + @","); } } sb.Append(@" ZMaxValue = " + t.Classes.Count + @" } "); try { sb.WriteToFile(Path.Combine(outputDirPath, pn + "_AllClassEnums.cs")); } catch (Exception ex) { return(ex.Message); } sb.Clear(); foreach (var ns_ in t.Namespaces) { var ns = (ns_ != "" ? ns_ : pn); sb.Append(@" namespace " + ns + @" {"); foreach (var c in t.Classes.Where(a => a.Namespace == ns_)) { sb.Append(GetComment(c.Desc, 4) + @" public enum " + c.Name + @"_e : byte {"); foreach (var f in c.Fields) { sb.Append(GetComment(f.Desc, 8) + @" " + f.Name + @","); } sb.Append(@" ZMaxValue = " + c.Fields.Count + @" } "); } sb.Append(@" } "); } try { sb.WriteToFile(Path.Combine(outputDirPath, pn + "_Enum.cs")); } catch (Exception ex) { return(ex.Message); } // todo: change tn add basenamespace sb.Clear(); sb.Append(@"using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SerialHelper { partial class Bytes {"); foreach (var e in t.Enums) { var ns = (e.Namespace != "" ? e.Namespace : pn); var tn = ns + "." + e.Name; sb.Append(@" public void write( List<" + tn + @"> v ) { if( v == null ) { write( -1 ); return; } else if( v.Count == 0 ) { write( 0 ); return; } write( v.Count ); for( int i = 0; i < v.Count; ++i ) { write( (" + e.GetTypeKeyword() + @")v[ i ] ); } } public ReadState read( ref List<" + tn + @"> v ) { int len = 0; var rtv = read( ref len ); if( rtv != ReadState.Success ) return rtv; if( len < -1 ) return ReadState.Fail; else if( len == -1 ) { v = null; return rtv; } else if( len == 0 ) { if( v != null ) v.Clear(); else v = new List<" + tn + @">(); return rtv; } if( v == null ) v = new List<" + tn + @">(); else v.Clear(); for( int i = 0; i < len; ++i ) { " + e.GetTypeKeyword() + @" o = 0; rtv = read( ref o ); if( rtv != ReadState.Success ) return rtv; v.Add( (" + tn + @")o ); } return ReadState.Success; } "); } foreach (var g in t.Classes.SelectMany(a => a.Fields).Where(a => a.IsDictionary).GroupBy(a => a.KeyTypeNamespace + "." + a.KeyType + "," + a.TypeNamespace + "." + a.Type)) { var f = g.First(); var ktn = GetKeyTypeKeyword(f); var vtn = GetTypeKeyword(f); sb.Append(@" public void write( Dictionary<" + ktn + @", " + vtn + @"> v ) { if( v == null ) { write( -1 ); return; } else if( v.Count == 0 ) { write( 0 ); return; } write( v.Count ); write( v.Keys.ToList() ); write( v.Values.ToList() ); } public ReadState read( ref Dictionary<" + ktn + @", " + vtn + @"> v ) { int len = 0; var rtv = read( ref len ); if( rtv != ReadState.Success ) return rtv; if( len < -1 ) return ReadState.Fail; else if( len == -1 ) { v = null; return rtv; } else if( len == 0 ) { if( v != null ) v.Clear(); else v = new Dictionary<" + ktn + @", " + vtn + @">(); return rtv; } if( v == null ) v = new Dictionary<" + ktn + @", " + vtn + @">(); else v.Clear(); var keys = new List<" + ktn + @">(); rtv = read( ref keys ); if( rtv != ReadState.Success ) return rtv; if( keys.Count != len ) return ReadState.Fail; var vals = new List<" + vtn + @">(); rtv = read( ref vals ); if( rtv != ReadState.Success ) return rtv; if( vals.Count != len ) return ReadState.Fail; for( int i = 0; i < len; ++i ) { v.Add( keys[ i ], vals[ i ] ); } return ReadState.Success; } "); } sb.Append(@" } } "); try { sb.WriteToFile(Path.Combine(outputDirPath, pn + "_BytesPartial.cs")); } catch (Exception ex) { return(ex.Message); } sb.Clear(); sb.Append(@"using System; using System.Collections.Generic; using SerialHelper; "); foreach (var ns_ in t.Namespaces) { var ns = (ns_ != "" ? ns_ : pn); sb.Append(@" namespace " + ns + @" {"); foreach (var e in t.Enums.Where(a => a.Namespace == ns_)) { sb.Append(GetComment(e.Desc, 4) + @" public enum " + e.Name + @" : " + e.GetTypeKeyword() + @" {"); foreach (var f in e.Fields) { sb.Append(GetComment(f.Desc, 8) + @" " + f.Name + " = " + f.Value + @","); } sb.Append(@" } "); } foreach (var c in t.Classes.Where(a => a.Namespace == ns_)) { sb.Append(GetComment(c.Desc, 4) + @" public partial class " + c.Name + @" : ISC {"); foreach (var f in c.Fields) { sb.Append(GetComment(f.Desc, 8)); if (f.IsArray) { sb.Append(@" public List<" + GetTypeKeyword(f) + @"> " + f.Name + ";"); // + @" = " + GetDefaultValueByType( f ) + @";" ); } else if (f.IsDictionary) { sb.Append(@" public Dictionary<" + GetKeyTypeKeyword(f) + ", " + GetTypeKeyword(f) + @"> " + f.Name + ";"); // + @" = " + GetDefaultValueByType( f ) + @";" ); } else { sb.Append(@" public " + GetTypeKeyword(f) + @" " + f.Name + ";"); // + @" = " + GetDefaultValueByType( f ) + @";" ); } } sb.Append(@" } "); } sb.Append(@" } "); } try { sb.WriteToFile(Path.Combine(outputDirPath, pn + "_Class.cs")); } catch (Exception ex) { return(ex.Message); } sb.Clear(); sb.Append(@"using System; using System.Collections.Generic; using SerialHelper; "); foreach (var ns_ in t.Namespaces) { var ns = (ns_ != "" ? ns_ : pn); sb.Append(@" namespace " + ns + @" {"); foreach (var c in t.Classes.Where(a => a.Namespace == ns_)) { sb.Append(@" partial class " + c.Name + @" {"); foreach (var f in c.Fields) { if (f.IsArray) { sb.Append(@" public List<" + GetTypeKeyword(f) + @"> __prop__" + f.Name + " { get { return " + f.Name + "; } }"); } else if (f.IsDictionary) { sb.Append(@" public Dictionary<" + GetKeyTypeKeyword(f) + ", " + GetTypeKeyword(f) + @"> __prop__" + f.Name + " { get { return " + f.Name + "; } }"); } else { sb.Append(@" public " + GetTypeKeyword(f) + @" __prop__" + f.Name + " { get { return " + f.Name + "; } }"); } } sb.Append(@" } "); } sb.Append(@" } "); } try { sb.WriteToFile(Path.Combine(outputDirPath, pn + "_ClassProp.cs")); } catch (Exception ex) { return(ex.Message); } sb.Clear(); sb.Append(@"using System; using System.Collections.Generic; using System.Text; using System.Linq; using SerialHelper; "); foreach (var ns_ in t.Namespaces) { var ns = (ns_ != "" ? ns_ : pn); sb.Append(@" namespace " + ns + @" {"); foreach (var c in t.Classes.Where(a => a.Namespace == ns_)) { var en = ns.Replace(".", "_") + "_" + c.Name; sb.Append(@" partial class " + c.Name + @" { public int getOpcode() { return (int)" + pn + @"_AllClassEnums." + en + @"; } public " + pn + @"_AllClassEnums getOpcodeEnum() { return " + pn + @"_AllClassEnums." + en + @"; } public void writeTo( Bytes bin ) { bin.write( (uint)" + c.Fields.Count + @" );"); foreach (var f in c.Fields) { if (f.TypeClass != null && f.TypeClass.IsEnum && !f.IsArray) { sb.Append(@" bin.write( (" + (f.TypeClass as Enum).GetTypeKeyword() + ")this." + f.Name + @" );"); } else { sb.Append(@" bin.write( this." + f.Name + @" );"); } } sb.Append(@" } "); if (c.Fields.Count > 0) { sb.Append(@" public void writeTo( Bytes bin, params " + c.Name + @"_e[] ms ) { if( ms.Length == " + c.Fields.Count + @" || ms.Length == 0 || ms == null ) { writeTo( bin ); return; } #if DEBUG for( int k = 0; k < ms.Length - 1; ++k ) { if( ms[ k ] > ms[ k + 1 ] ) throw new Exception( ""错误的枚举顺序: "" + ms[ k ].ToString() + ms[ k + 1 ].ToString() ); if( ms[ k ] == ms[ k + 1 ] ) throw new Exception( ""重复的枚举项: "" + ms[ k ].ToString() ); } #endif bin.write( (uint)ms.Length ); bin.ensure( ms.Length + 1 ); Array.Copy( ms, 0, bin._buf, bin._len, ms.Length ); bin._len += ms.Length; int i = 0;"); foreach (var f in c.Fields) { if (f.TypeClass != null && f.TypeClass.IsEnum && !f.IsArray) { sb.Append(@" if( ms[ i ] == " + c.Name + @"_e." + f.Name + @" ) { bin.write( (" + (f.TypeClass as Enum).GetTypeKeyword() + ")this." + f.Name + @" ); if( ++i == ms.Length ) return; }"); } else { sb.Append(@" if( ms[ i ] == " + c.Name + @"_e." + f.Name + @" ) { bin.write( this." + f.Name + @" ); if( ++i == ms.Length ) return; }"); } } sb.Append(@" } public ReadState readFrom( Bytes bin, bool[] filledMembers = null ) { ReadState rtv; uint len = 0; rtv = bin.read( ref len ); if( rtv != ReadState.Success ) return rtv; if( len > " + c.Fields.Count + @" ) return ReadState.Fail; else if( len == " + c.Fields.Count + @" ) {"); foreach (var f in c.Fields) { if (f.TypeClass != null && f.TypeClass.IsEnum && !f.IsArray) { var tn = (f.TypeNamespace != "" ? f.TypeNamespace : pn) + "." + f.Type; var e = (f.TypeClass as Enum); sb.Append(@" { " + e.GetTypeKeyword() + @" tmp = 0; rtv = bin.read( ref tmp ); if( rtv != ReadState.Success ) return rtv; this." + f.Name + @" = (" + tn + @")tmp; }"); } else { sb.Append(@" rtv = bin.read( ref this." + f.Name + @" ); if( rtv != ReadState.Success ) return rtv;"); } } if (c.Fields.Count > 0) { sb.Append(@" if( filledMembers != null ) { for( int j = 0; j < " + c.Fields.Count + @"; ++j ) filledMembers[ j ] = true; }"); } sb.Append(@" } else { var ms = new " + c.Name + @"_e[ len ]; for( int j = 0; j < len; ++j ) { ms[ j ] = (" + c.Name + @"_e)bin._buf[ bin._readIdx++ ]; } int i = 0;"); foreach (var f in c.Fields) { if (f.TypeClass != null && f.TypeClass.IsEnum && !f.IsArray) { var e = (f.TypeClass as Enum); var tn = (f.TypeNamespace != "" ? f.TypeNamespace : pn) + "." + f.Type; sb.Append(@" if( ms[ i ] == " + c.Name + @"_e." + f.Name + @" ) { " + e.GetTypeKeyword() + @" tmp = 0; rtv = bin.read( ref tmp ); if( rtv != ReadState.Success ) return rtv; else if ( filledMembers != null ) filledMembers[ (int)" + c.Name + @"_e." + f.Name + @" ] = true; this." + f.Name + @" = (" + tn + @")tmp; if( ++i == ms.Length ) return rtv; }"); } else { sb.Append(@" if( ms[ i ] == " + c.Name + @"_e." + f.Name + @" ) { rtv = bin.read( ref this." + f.Name + @" ); if( rtv != ReadState.Success ) return rtv; else if ( filledMembers != null ) filledMembers[ (int)" + c.Name + @"_e." + f.Name + @" ] = true; if( ++i == ms.Length ) return rtv; }"); } } sb.Append(@" } return rtv; } "); } else { sb.Append(@" public ReadState readFrom( Bytes bin, bool[] filledMembers = null ) { ReadState rtv; uint len = 0; rtv = bin.read( ref len ); if( rtv != ReadState.Success ) return rtv; if( len == 0 ) return rtv; return ReadState.Fail; } "); } sb.Append(@" } "); } sb.Append(@" } "); } try { sb.WriteToFile(Path.Combine(outputDirPath, pn + "_Partial.cs")); } catch (Exception ex) { return(ex.Message); } System.Diagnostics.Process.Start("explorer.exe", outputDirPath); return(""); }
public static void Gen(Template t, string outDir) { string pn = t.Name; _pn = pn; // root namespace ConvertNamespace(t, pn); var enums = t.Structs.Where(a => a.IsEnum).ToList(); var packages = t.Structs.Where(a => a.IsPackage) .OrderByDescending(a => a.RefCounter).ToList(); // 按依赖顺序排序 var packages_and_structs = t.Structs.Where(a => a.IsPackage || a.IsStruct) .OrderByDescending(a => a.RefCounter).ToList(); // 按依赖顺序排序 var sb = new StringBuilder(); #region 生成 pn.h // 文件头部 sb.Append(@"#pragma once #include ""xxlib_bytesutils.hpp"" "); /*******************************************************/ // 所有枚举 /*******************************************************/ // namespace root { sb.Append(@" namespace " + pn + @" {"); foreach (var e in enums) { // namespace xxx { if (e.Namespace != "") { sb.Append(@" namespace " + e.Namespace + @" {"); } // // desc sb.Append(GetComment(e.Desc, 0)); // enum class xxx : valType { sb.Append(@" enum class " + e.Name + @" : " + GetEnumTypeKeyword(e) + @" {"); foreach (var ef in e.Members) { // // desc sb.Append(GetComment(ef.Desc, 4)); // enum item = val sb.Append(@" " + ef.Name + " = " + ef.EnumValue + ","); } // enum class }; // xxx sb.Append(@" };"); // namespace } // xxx if (e.Namespace != "") { sb.Append(@" } // " + e.Namespace); } } #if false /*******************************************************/ // 预声明部分 /*******************************************************/ // namespace root { sb.Append( @" namespace " + pn + @" {" ); foreach( var c in packages_and_structs ) { // namespace xxx { if( c.Namespace != "" ) { sb.Append( @" namespace " + c.Namespace + @" {" ); } // // desc sb.Append( GetComment( c.Desc, 0 ) ); // struct xxx sb.Append( @" struct " + c.Name + @";" ); // namespace } // xxx if( c.Namespace != "" ) { sb.Append( @" } // " + c.Namespace ); } } // namespace } // root sb.Append( @" } // " + pn + @" " ); #endif /*******************************************************/ // 结构体部分 /*******************************************************/ foreach (var c in packages_and_structs) { // namespace xxx { if (c.Namespace != "") { sb.Append(@" namespace " + c.Namespace + @" {"); } // // desc sb.Append(GetComment(c.Desc, 0)); // struct xxx { sb.Append(@" struct " + c.Name + @" {"); // packageId; if (c.StructType == StructTypes.Package) { sb.Append(@" const static short packageId = " + c.PackageId + ";"); } #if false // constructors sb.Append(@" " + c.Name + @"() {} " + c.Name + @"( " + c.Name + @" const& o ) = default; " + c.Name + @"( " + c.Name + @" && o ) = default; " + c.Name + @"& operator=( " + c.Name + @" const& o ) = default; " + c.Name + @"& operator=( " + c.Name + @" && o ) = default; "); #endif // WriteTo(char *dstBuf, members........ ) sb.Append(@" inline static size_t WriteTo(size_t bufLen, char *dstBuf"); foreach (var f in c.Members.Where(a => a.Deprecated == null)) { sb.Append(", " + GetTypeKeyword(f) + " const &" + f.Name); } sb.Append(@") {"); if (c.Members.Count > 0) { sb.Append(@" if (bufLen && bufLen < xxlib::BytesUtils::Calc("); foreach (var f in c.Members) { sb.Append(f.Name + ", "); } sb.Length -= 2; sb.Append(@")) return (size_t)-1; size_t len = 0;"); foreach (var f in c.Members) { sb.Append(@" len += xxlib::BytesUtils::" + (f.Compress && f.Type.Compressable() ? "Var" : "") + "WriteTo(dstBuf + len, " + f.Name + ");"); } sb.Append(@" return len;"); } else { sb.Append(@" return 0;"); } sb.Append(@" } "); // members foreach (var f in c.Members) { var tn = GetTypeKeyword(f); //var dv = GetDefaultValueByType(f); string dv = ""; // // desc sb.Append(GetComment(f.Desc, 4)); // type val;// = default; sb.Append(@" " + (f.Deprecated == null ? "" : "// ") + tn + " " + f.Name + (f.Type.IsArray ? ("[" + f.MinLen + "]") : "") + (dv != "" ? (" = " + dv) : "") + ";"); } sb.Append(@" };"); // namespace } // xxx if (c.Namespace != "") { sb.Append(@" } // " + c.Namespace); } } // namespace } // root sb.Append(@" } // " + pn + @" "); sb.Append(@" namespace xxlib { namespace BytesUtils {"); foreach (var c in packages_and_structs) { var ctn = GetNamespace(c) + "::" + c.Name; var cms = c.Members.Where(a => a.Deprecated == null).ToList(); if (c.BackwardCompatibility) { // sb.Append(@" //inline size_t Calc(" + ctn + @" const &in) //{ // return 4 + 5"); // if (cms.Count > 0) // { // sb.Append(" + 5 * " + cms.Count + " +"); // } // foreach (var f in cms) // { // sb.Append(@" // Calc(in." + f.Name + ") +"); // } // if (cms.Count > 0) // sb.Length -= 2; // sb.Append(@"; //} //inline size_t WriteTo(char *dstBuf, " + ctn + @" const &in) //{ // size_t len = 4; // len += VarWriteTo(dstBuf + len, " + cms.Count + @"u);"); // foreach (var f in cms.OrderBy(a => a.Ordinal)) // { // sb.Append(@" // len += VarWriteTo(dstBuf + len, " + f.Ordinal + @"u); // len += " + (f.Compress && f.Type.Compressable() ? "Var" : "") + "WriteTo(dstBuf + len, in." + f.Name + ");"); // } // sb.Append(@" // WriteTo(dstBuf, (uint32_t)len); // return len; //} //template<> //inline int32_t ReadFrom(char const *srcBuf, size_t const &dataLen, size_t &offset, " + ctn + @" &out) //{ // int32_t rtv = 0; // uint32_t count = 0, idx = 0, len = 0; // auto bak = offset; // if (rtv = ReadFrom(srcBuf, dataLen, offset, len)) return rtv; // if (rtv = VarReadFrom(srcBuf, dataLen, offset, count)) return rtv; // for (uint32_t i = 0; i < count; i++) // { // if (rtv = VarReadFrom(srcBuf, dataLen, offset, idx)) return rtv; // switch (idx) // {"); // foreach (var f in c.Members.OrderBy(a => a.Ordinal)) // { // sb.Append(@" // case " + f.Ordinal + @": // {"); // if (f.Deprecated != null) // { // var tn = f.Type.IsArray ? GetTypeKeyword(f.Type.ChildType) : GetTypeKeyword(f); // sb.Append(@" // " + tn + " tmp;"); // } // sb.Append(@" // if (rtv = " + (f.Compress && f.Type.Compressable() ? "Var" : "") + "ReadFrom" + ((f.Type.IsContainer && !f.Type.IsArray) ? "Limit" : "") + "(srcBuf, dataLen, offset"); // if (f.Type.IsContainer && !f.Type.IsArray) // { // sb.Append(@", " + f.MinLen + ", " + f.MaxLen); // } // sb.Append(", " + (f.Deprecated != null ? "tmp" : ("out." + f.Name)) + @")) return rtv; // break; // }"); // } // sb.Append(@" // default: // offset = bak + len; // return rtv; // } // } // return rtv; //}"); } else { sb.Append(@" inline size_t Calc(" + ctn + @" const &in) { return "); if (c.Members.Count == 0) { sb.Append(@"0"); } else { sb.Append(@"Calc("); foreach (var f in c.Members) { sb.Append(@"in." + f.Name + ", "); } sb.Length -= 2; sb.Append(")"); } sb.Append(@"; } inline size_t WriteTo(char *dstBuf, " + ctn + @" const &in) { size_t len = 0;"); foreach (var f in c.Members) { sb.Append(@" len += " + (f.Compress && f.Type.Compressable() ? "Var" : "") + "WriteTo(dstBuf + len, in." + f.Name + ");"); } sb.Append(@" return len; } template<> inline int32_t ReadFrom(char const *srcBuf, size_t const &dataLen, size_t &offset, " + ctn + @" &out) { int32_t rtv = 0;"); foreach (var f in c.Members) { sb.Append(@" if (rtv = " + (f.Compress && f.Type.Compressable() ? "Var" : "") + "ReadFrom" + ((f.Type.IsContainer && !f.Type.IsArray) ? "Limit" : "") + "(srcBuf, dataLen, offset"); if (f.Type.IsContainer && !f.Type.IsArray) { sb.Append(@", " + f.MinLen + ", " + f.MaxLen); } sb.Append(", out." + f.Name + @")) return rtv;"); } sb.Append(@" return rtv; }"); } } sb.Append(@" } }"); sb.WriteToFile(Path.Combine(outDir, pn + ".h")); #endregion }
public static string Gen(Template t, string outDir, string pn) { _pn = pn; var ns = pn + "Packets"; ConvertNamespace(t, ns); var sb = new StringBuilder(); sb.Append(@"#ifndef __" + pn.ToUpper() + @"_H__ #define __" + pn.ToUpper() + @"_H__ namespace " + pn + @"Packets {"); foreach (var c in t.Classes) { sb.Append(@" class " + c.Name + @";"); } sb.Append(@" } namespace " + pn + @"Packets {"); foreach (var c in t.Classes) { sb.Append((c.Desc == "" ? "" : GetComment(c.Desc, 4)) + @" class " + c.Name + @" : Memmoveable { PACKET_CLASS_HEADER" + (IsPod(c) ? "_POD" : "") + @"( " + c.Name + @" ); public: "); foreach (var f in c.Fields) { var tn = SplitTypeKeyword(GetTypeKeyword(f.Declare), f.Declare); sb.Append((f.Desc == "" ? "" : GetComment(f.Desc, 8)) + @" " + tn.Key + " _" + f.Name.ToFirstLower() + tn.Value + ((GetDefaultValueByType(f) != "") ? (" = " + GetDefaultValueByType(f)) : "") + ";"); } sb.Append(@" static void fill( FlatBuffer& fb"); foreach (var f in c.Fields) { var tn = GetTypeKeyword(f.Declare); var atn = SplitTypeKeyword(GetTypeKeyword(f.Declare), f.Declare); if (f.Declare.DataType == DataTypes.Array) { sb.Append(@" , " + atn.Key + "( &" + f.Name + " )" + atn.Value); } else { sb.Append(@" , " + tn + " " + f.Name); } } sb.Append(@" ); "); foreach (var f in c.Fields) { var tn = GetTypeKeyword(f.Declare); var atn = SplitTypeKeyword(GetTypeKeyword(f.Declare), f.Declare); if (f.Get) { sb.Append(@" " + tn + " const& get" + f.Name.ToFirstUpper() + @"();"); } if (f.Set) { if (IsSimpleType(f)) { if (f.Declare.DataType == DataTypes.Array) { sb.Append(@" inline void set" + f.Name.ToFirstUpper() + @"( " + atn.Key + @"( &v )" + atn.Value + @" ) { _" + f.Name.ToFirstLower() + @" = v; }"); } else { sb.Append(@" inline void set" + f.Name.ToFirstUpper() + @"( " + tn + @" v ) { _" + f.Name.ToFirstLower() + @" = v; }"); } } else { sb.Append(@" template<typename VT> void set" + f.Name.ToFirstUpper() + @"( VT&& v ) { _" + f.Name.ToFirstLower() + @" = std::forward<VT>( v ); }"); } } } sb.Append(@" };"); } sb.Append(@" } #endif "); try { sb.WriteToFile(Path.Combine(outDir, ns + ".h")); } catch (Exception ex) { return(ex.Message); } sb.Clear(); sb.Append(@"#include ""Lib/All.h"" #include """ + ns + @".h"" namespace " + pn + @"Packets {"); foreach (var c in t.Classes) { sb.Append(@" ushort " + c.Name + @"::getTypeID() { return " + c.TypeID + @"; }"); if (!IsPod(c)) { sb.Append(@" " + c.Name + @"::" + c.Name + @"( " + c.Name + @" const& other )"); bool isFirst = true; foreach (var f in c.Fields) { sb.Append(@" " + (isFirst ? ":" : ",") + " _" + f.Name.ToFirstLower() + @"( other._" + f.Name.ToFirstLower() + @" )"); isFirst = false; } sb.Append(@" { } " + c.Name + @"::" + c.Name + @"( " + c.Name + @"&& other )"); isFirst = true; foreach (var f in c.Fields) { if ((f.Declare.Class as Class != null) && IsPod((Class)f.Declare.Class)) { sb.Append(@" " + (isFirst ? ":" : ",") + " _" + f.Name.ToFirstLower() + @"( other._" + f.Name.ToFirstLower() + @" )"); } else { sb.Append(@" " + (isFirst ? ":" : ",") + " _" + f.Name.ToFirstLower() + @"( std::move( other._" + f.Name.ToFirstLower() + @" ) )"); } isFirst = false; } sb.Append(@" { } " + c.Name + @"& " + c.Name + @"::operator=( " + c.Name + @" const& other ) {"); foreach (var f in c.Fields) { sb.Append(@" _" + f.Name.ToFirstLower() + @" = other._" + f.Name.ToFirstLower() + @";"); } sb.Append(@" return *this; } " + c.Name + @"& " + c.Name + @"::operator=( " + c.Name + @"&& other ) {"); foreach (var f in c.Fields) { if ((f.Declare.Class as Class != null) && IsPod((Class)f.Declare.Class)) { sb.Append(@" _" + f.Name.ToFirstLower() + @" = other._" + f.Name.ToFirstLower() + @";"); } else { sb.Append(@" _" + f.Name.ToFirstLower() + @" = std::move( other._" + f.Name.ToFirstLower() + @" );"); } } sb.Append(@" return *this; } "); } foreach (var f in c.Fields) { if (f.Get) { var tn = GetTypeKeyword(f.Declare); sb.Append(@" " + tn + " const& " + c.Name + @"::get" + f.Name.ToFirstUpper() + @"() { return _" + f.Name.ToFirstLower() + @"; }"); } } sb.Append(@" void " + c.Name + @"::fill( FlatBuffer& fb"); foreach (var f in c.Fields) { var tn = GetTypeKeyword(f.Declare); var atn = SplitTypeKeyword(GetTypeKeyword(f.Declare), f.Declare); if (f.Declare.DataType == DataTypes.Array) { sb.Append(@" , " + atn.Key + @"( &p" + f.Name.ToFirstUpper() + " )" + atn.Value); } else { sb.Append(@" , " + tn + @" p" + f.Name.ToFirstUpper()); } } sb.Append(@" ) {"); if (c.Fields.Count > 0) { sb.Append(@" fb.writes("); foreach (var f in c.Fields) { sb.Append(@" p" + f.Name.ToFirstUpper() + (f == c.Fields[c.Fields.Count - 1] ? "" : @", ")); } sb.Append(@" );"); } sb.Append(@" }"); sb.Append(@" void " + c.Name + @"::writeBuffer( FlatBuffer& fb ) const {"); if (c.Fields.Count > 0) { sb.Append(@" fb.writes("); foreach (var f in c.Fields) { sb.Append(@" _" + f.Name.ToFirstLower() + (f == c.Fields[c.Fields.Count - 1] ? "" : @", ")); } sb.Append(@" );"); } sb.Append(@" } bool " + c.Name + @"::readBuffer( FlatBuffer& fb ) {"); if (c.Fields.Count > 0) { sb.Append(@" return fb.reads("); foreach (var f in c.Fields) { sb.Append(@" _" + f.Name.ToFirstLower() + (f == c.Fields[c.Fields.Count - 1] ? "" : @", ")); } sb.Append(@" );"); } else { sb.Append(@" return true;"); } sb.Append(@" } void " + c.Name + @"::writeBufferDirect( FlatBuffer& fb ) const {"); if (c.Fields.Count > 0) { sb.Append(@" fb.writesDirect("); foreach (var f in c.Fields) { sb.Append(@" _" + f.Name.ToFirstLower() + (f == c.Fields[c.Fields.Count - 1] ? "" : @", ")); } sb.Append(@" );"); } sb.Append(@" } int " + c.Name + @"::getWriteBufferSize() const {"); if (c.Fields.Count > 0) { sb.Append(@" return "); foreach (var f in c.Fields) { if (IsSimpleType(f)) { sb.Append(@" sizeof( _" + f.Name.ToFirstLower() + " )"); } else { sb.Append(@" BufferUtils::getSizes( _" + f.Name.ToFirstLower() + " )"); } sb.Append(f == c.Fields[c.Fields.Count - 1] ? "" : @" + "); } sb.Append(@";"); } sb.Append(@" } "); } sb.Append(@" } "); try { sb.WriteToFile(Path.Combine(outDir, ns + ".cpp")); } catch (Exception ex) { return(ex.Message); } System.Diagnostics.Process.Start("explorer.exe", outDir); return(""); }
public static string Gen( Template t, string outputDirPath, string pn ) { _pn = pn; var sb = new StringBuilder(); sb.Clear(); sb.Append( @"using SerialHelper; // 解码函数数组声明 // public Action<Bytes>[] PacketHandlers; // 向数组存入对应的处理函数 // PacketHandlers = new Action<Bytes, params object[]>[ (int)" + pn + @"_AllClassEnums.ZMaxValue ]; " ); foreach( var ns_ in t.Namespaces ) { var ns = ( ns_ != "" ? ns_ : pn ); foreach( var c in t.Classes.Where( a => a.Namespace == ns_ ) ) { var en = ns.Replace( ".", "_" ) + "_" + c.Name; sb.Append( @" PacketHandlers[ (int)" + pn + @"_AllClassEnums." + en + @" ] = " + en + @";" ); } } sb.Append( @" // 不获取标记位系列函数实现空壳 " ); foreach( var ns_ in t.Namespaces ) { var ns = ( ns_ != "" ? ns_ : pn ); foreach( var c in t.Classes.Where( a => a.Namespace == ns_ ) ) { var en = ns.Replace( ".", "_" ) + "_" + c.Name; sb.Append( @" private void " + en + @"( Bytes b, params object[] extPs ) { var o = new " + ns + @"." + c.Name + @"(); var rtv = o.readFrom( b ); if( rtv != ReadState.Success ) { return; // 这里放置解包错误处理代码 } // if( On_" + en + @" != null ) On_" + en + @"( o ); } " ); } } sb.Append( @" // 获取标记位 " ); foreach( var ns_ in t.Namespaces ) { var ns = ( ns_ != "" ? ns_ : pn ); foreach( var c in t.Classes.Where( a => a.Namespace == ns_ ) ) { var en = ns.Replace( ".", "_" ) + "_" + c.Name; sb.Append( @" private void " + en + @"( Bytes b, params object[] ext_ps ) { var o = new " + ns + @"." + c.Name + @"(); var flags = new bool[ (int)" + ns + @"." + c.Name + @"_e.ZMaxValue ]; var rtv = o.readFrom( b, flags ); if( rtv != ReadState.Success ) { // 这里放置解包错误处理代码 return; } // read success code here if( On_" + en + @" != null ) On_" + en + @"( o ); " ); foreach( var f in c.Fields ) { sb.Append( @" if( flags[ (int)" + ns + @"." + c.Name + @"_e." + f.Name + @" ] ) { // 处理代码 if( On_" + en + @"_m_" + f.Name + @" != null ) On_" + en + @"_m_" + f.Name + @"( o ); }" ); } sb.Append( @" } " ); } } sb.Append( @" " ); foreach( var ns_ in t.Namespaces ) { var ns = ( ns_ != "" ? ns_ : pn ); foreach( var c in t.Classes.Where( a => a.Namespace == ns_ ) ) { var en = ns.Replace( ".", "_" ) + "_" + c.Name; sb.Append( @" public static event System.Action<" + ns + "." + c.Name + @"> On_" + en + @";" ); foreach( var f in c.Fields ) { sb.Append( @" public static event System.Action<" + ns + "." + c.Name + @"> On_" + en + @"_m_" + f.Name + @";" ); } } } sb.Append( @" " ); sb.Append( @" // 可能有用的扩展函数 public static byte[] toByteArray( this ISC o ) { var b = new Bytes(); b.write( o ); b.collapse(); return b._buf; } #region SyncSend /// <summary> /// 同步获取返回结果 /// </summary> public T SyncSend<T>( ISC cmd, int timeoutSec ) where T : ISC { string cb_ = Guid.NewGuid().ToString(); bool got_ = false; T rtv_ = default( T ); var func = new Action<string, T>( ( cb, o ) => { if( cb_ != cb ) return; got_ = true; rtv_ = o; } ); RegisterHandler<T>( func ); Send( cmd, cb_ ); for( int i = 0; i < timeoutSec * 10; ++i ) { if( got_ ) goto LabEnd; System.Threading.Thread.Sleep( 100 ); } LabEnd: UnregisterHandler<T>( func ); return rtv_; } private void RegisterHandler<T>( dynamic func ) where T : ISC {"); foreach( var ns_ in t.Namespaces ) { var ns = ( ns_ != "" ? ns_ : pn ); foreach( var c in t.Classes.Where( a => a.Namespace == ns_ ) ) { var en = ns.Replace( ".", "_" ) + "_" + c.Name; sb.Append( @" if( typeof( T ) == typeof( " + ns + "." + c.Name + @" ) ) On_" + en + @" += func;" ); } } sb.Append(@" } private void UnegisterHandler<T>( dynamic func ) where T : ISC {" ); foreach( var ns_ in t.Namespaces ) { var ns = ( ns_ != "" ? ns_ : pn ); foreach( var c in t.Classes.Where( a => a.Namespace == ns_ ) ) { var en = ns.Replace( ".", "_" ) + "_" + c.Name; sb.Append( @" if( typeof( T ) == typeof( " + ns + "." + c.Name + @" ) ) On_" + en + @" -= func;" ); } } sb.Append( @" } #endregion " ); try { sb.WriteToFile( Path.Combine( outputDirPath, pn + "_Samples.txt" ) ); } catch( Exception ex ) { return ex.Message; } sb.Clear(); sb.Append( @"using SerialHelper; public static partial class " + pn + @"_AllClassHandler { public static ISC read( int opcode, byte[] buf ) { var b = new Bytes( buf, buf.Length ); switch( (" + pn + @"_AllClassEnums)opcode ) {" ); foreach( var ns_ in t.Namespaces ) { var ns = ( ns_ != "" ? ns_ : pn ); foreach( var c in t.Classes.Where( a => a.Namespace == ns_ ) ) { var en = ns.Replace( ".", "_" ) + "_" + c.Name; sb.Append( @" case " + pn + @"_AllClassEnums." + en + @": { var o = new " + ns + @"." + c.Name + @"(); var rtv = o.readFrom( b ); if( rtv != ReadState.Success ) return null; return o; }" ); } } sb.Append( @" default: return null; } } } " ); try { sb.WriteToFile( Path.Combine( outputDirPath, pn + "_AllClassHandler.cs" ) ); } catch( Exception ex ) { return ex.Message; } sb.Clear(); sb.Append( @" public enum " + pn + @"_AllClassEnums {" ); int idx = 0; foreach( var ns_ in t.Namespaces ) { var ns = ( ns_ != "" ? ns_ : pn ); foreach( var c in t.Classes.Where( a => a.Namespace == ns_ ) ) { var en = ns.Replace( ".", "_" ) + "_" + c.Name; sb.Append( GetComment( c.Desc, 4 ) + @" " + en + @" = " + ( idx++ ) + @"," ); } } sb.Append( @" ZMaxValue = " + t.Classes.Count + @" } " ); try { sb.WriteToFile( Path.Combine( outputDirPath, pn + "_AllClassEnums.cs" ) ); } catch( Exception ex ) { return ex.Message; } sb.Clear(); foreach( var ns_ in t.Namespaces ) { var ns = ( ns_ != "" ? ns_ : pn ); sb.Append( @" namespace " + ns + @" {" ); foreach( var c in t.Classes.Where( a => a.Namespace == ns_ ) ) { sb.Append( GetComment( c.Desc, 4 ) + @" public enum " + c.Name + @"_e : byte {" ); foreach( var f in c.Fields ) { sb.Append( GetComment( f.Desc, 8 ) + @" " + f.Name + @"," ); } sb.Append( @" ZMaxValue = " + c.Fields.Count + @" } " ); } sb.Append( @" } " ); } try { sb.WriteToFile( Path.Combine( outputDirPath, pn + "_Enum.cs" ) ); } catch( Exception ex ) { return ex.Message; } // todo: change tn add basenamespace sb.Clear(); sb.Append( @"using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SerialHelper { partial class Bytes {" ); foreach( var e in t.Enums ) { var ns = ( e.Namespace != "" ? e.Namespace : pn ); var tn = ns + "." + e.Name; sb.Append( @" public void write( List<" + tn + @"> v ) { if( v == null ) { write( -1 ); return; } else if( v.Count == 0 ) { write( 0 ); return; } write( v.Count ); for( int i = 0; i < v.Count; ++i ) { write( (" + e.GetTypeKeyword() + @")v[ i ] ); } } public ReadState read( ref List<" + tn + @"> v ) { int len = 0; var rtv = read( ref len ); if( rtv != ReadState.Success ) return rtv; if( len < -1 ) return ReadState.Fail; else if( len == -1 ) { v = null; return rtv; } else if( len == 0 ) { if( v != null ) v.Clear(); else v = new List<" + tn + @">(); return rtv; } if( v == null ) v = new List<" + tn + @">(); else v.Clear(); for( int i = 0; i < len; ++i ) { " + e.GetTypeKeyword() + @" o = 0; rtv = read( ref o ); if( rtv != ReadState.Success ) return rtv; v.Add( (" + tn + @")o ); } return ReadState.Success; } " ); } foreach( var g in t.Classes.SelectMany( a => a.Fields ).Where( a => a.IsDictionary ).GroupBy( a => a.KeyTypeNamespace + "." + a.KeyType + "," + a.TypeNamespace + "." + a.Type ) ) { var f = g.First(); var ktn = GetKeyTypeKeyword( f ); var vtn = GetTypeKeyword( f ); sb.Append( @" public void write( Dictionary<" + ktn + @", " + vtn + @"> v ) { if( v == null ) { write( -1 ); return; } else if( v.Count == 0 ) { write( 0 ); return; } write( v.Count ); write( v.Keys.ToList() ); write( v.Values.ToList() ); } public ReadState read( ref Dictionary<" + ktn + @", " + vtn + @"> v ) { int len = 0; var rtv = read( ref len ); if( rtv != ReadState.Success ) return rtv; if( len < -1 ) return ReadState.Fail; else if( len == -1 ) { v = null; return rtv; } else if( len == 0 ) { if( v != null ) v.Clear(); else v = new Dictionary<" + ktn + @", " + vtn + @">(); return rtv; } if( v == null ) v = new Dictionary<" + ktn + @", " + vtn + @">(); else v.Clear(); var keys = new List<" + ktn + @">(); rtv = read( ref keys ); if( rtv != ReadState.Success ) return rtv; if( keys.Count != len ) return ReadState.Fail; var vals = new List<" + vtn + @">(); rtv = read( ref vals ); if( rtv != ReadState.Success ) return rtv; if( vals.Count != len ) return ReadState.Fail; for( int i = 0; i < len; ++i ) { v.Add( keys[ i ], vals[ i ] ); } return ReadState.Success; } " ); } sb.Append( @" } } " ); try { sb.WriteToFile( Path.Combine( outputDirPath, pn + "_BytesPartial.cs" ) ); } catch( Exception ex ) { return ex.Message; } sb.Clear(); sb.Append( @"using System; using System.Collections.Generic; using SerialHelper; " ); foreach( var ns_ in t.Namespaces ) { var ns = ( ns_ != "" ? ns_ : pn ); sb.Append( @" namespace " + ns + @" {" ); foreach( var e in t.Enums.Where( a => a.Namespace == ns_ ) ) { sb.Append( GetComment( e.Desc, 4 ) + @" public enum " + e.Name + @" : " + e.GetTypeKeyword() + @" {" ); foreach( var f in e.Fields ) { sb.Append( GetComment( f.Desc, 8 ) + @" " + f.Name + " = " + f.Value + @"," ); } sb.Append( @" } " ); } foreach( var c in t.Classes.Where( a => a.Namespace == ns_ ) ) { sb.Append( GetComment( c.Desc, 4 ) + @" public partial class " + c.Name + @" : ISC {" ); foreach( var f in c.Fields ) { sb.Append( GetComment( f.Desc, 8 ) ); if( f.IsArray ) { sb.Append( @" public List<" + GetTypeKeyword( f ) + @"> " + f.Name + ";" );// + @" = " + GetDefaultValueByType( f ) + @";" ); } else if( f.IsDictionary ) { sb.Append( @" public Dictionary<" + GetKeyTypeKeyword( f ) + ", " + GetTypeKeyword( f ) + @"> " + f.Name + ";" );// + @" = " + GetDefaultValueByType( f ) + @";" ); } else { sb.Append( @" public " + GetTypeKeyword( f ) + @" " + f.Name + ";" );// + @" = " + GetDefaultValueByType( f ) + @";" ); } } sb.Append( @" } " ); } sb.Append( @" } " ); } try { sb.WriteToFile( Path.Combine( outputDirPath, pn + "_Class.cs" ) ); } catch( Exception ex ) { return ex.Message; } sb.Clear(); sb.Append( @"using System; using System.Collections.Generic; using SerialHelper; " ); foreach( var ns_ in t.Namespaces ) { var ns = ( ns_ != "" ? ns_ : pn ); sb.Append( @" namespace " + ns + @" {" ); foreach( var c in t.Classes.Where( a => a.Namespace == ns_ ) ) { sb.Append( @" partial class " + c.Name + @" {" ); foreach( var f in c.Fields ) { if( f.IsArray ) { sb.Append( @" public List<" + GetTypeKeyword( f ) + @"> __prop__" + f.Name + " { get { return " + f.Name + "; } }" ); } else if( f.IsDictionary ) { sb.Append( @" public Dictionary<" + GetKeyTypeKeyword( f ) + ", " + GetTypeKeyword( f ) + @"> __prop__" + f.Name + " { get { return " + f.Name + "; } }" ); } else { sb.Append( @" public " + GetTypeKeyword( f ) + @" __prop__" + f.Name + " { get { return " + f.Name + "; } }" ); } } sb.Append( @" } " ); } sb.Append( @" } " ); } try { sb.WriteToFile( Path.Combine( outputDirPath, pn + "_ClassProp.cs" ) ); } catch( Exception ex ) { return ex.Message; } sb.Clear(); sb.Append( @"using System; using System.Collections.Generic; using System.Text; using System.Linq; using SerialHelper; " ); foreach( var ns_ in t.Namespaces ) { var ns = ( ns_ != "" ? ns_ : pn ); sb.Append( @" namespace " + ns + @" {" ); foreach( var c in t.Classes.Where( a => a.Namespace == ns_ ) ) { var en = ns.Replace( ".", "_" ) + "_" + c.Name; sb.Append( @" partial class " + c.Name + @" { public int getOpcode() { return (int)" + pn + @"_AllClassEnums." + en + @"; } public " + pn + @"_AllClassEnums getOpcodeEnum() { return " + pn + @"_AllClassEnums." + en + @"; } public void writeTo( Bytes bin ) { bin.write( (uint)" + c.Fields.Count + @" );" ); foreach( var f in c.Fields ) { if( f.TypeClass != null && f.TypeClass.IsEnum && !f.IsArray ) { sb.Append( @" bin.write( (" + ( f.TypeClass as Enum ).GetTypeKeyword() + ")this." + f.Name + @" );" ); } else sb.Append( @" bin.write( this." + f.Name + @" );" ); } sb.Append( @" } " ); if( c.Fields.Count > 0 ) { sb.Append( @" public void writeTo( Bytes bin, params " + c.Name + @"_e[] ms ) { if( ms.Length == " + c.Fields.Count + @" || ms.Length == 0 || ms == null ) { writeTo( bin ); return; } #if DEBUG for( int k = 0; k < ms.Length - 1; ++k ) { if( ms[ k ] > ms[ k + 1 ] ) throw new Exception( ""错误的枚举顺序: "" + ms[ k ].ToString() + ms[ k + 1 ].ToString() ); if( ms[ k ] == ms[ k + 1 ] ) throw new Exception( ""重复的枚举项: "" + ms[ k ].ToString() ); } #endif bin.write( (uint)ms.Length ); bin.ensure( ms.Length + 1 ); Array.Copy( ms, 0, bin._buf, bin._len, ms.Length ); bin._len += ms.Length; int i = 0;" ); foreach( var f in c.Fields ) { if( f.TypeClass != null && f.TypeClass.IsEnum && !f.IsArray ) { sb.Append( @" if( ms[ i ] == " + c.Name + @"_e." + f.Name + @" ) { bin.write( (" + ( f.TypeClass as Enum ).GetTypeKeyword() + ")this." + f.Name + @" ); if( ++i == ms.Length ) return; }" ); } else sb.Append( @" if( ms[ i ] == " + c.Name + @"_e." + f.Name + @" ) { bin.write( this." + f.Name + @" ); if( ++i == ms.Length ) return; }" ); } sb.Append( @" } public ReadState readFrom( Bytes bin, bool[] filledMembers = null ) { ReadState rtv; uint len = 0; rtv = bin.read( ref len ); if( rtv != ReadState.Success ) return rtv; if( len > " + c.Fields.Count + @" ) return ReadState.Fail; else if( len == " + c.Fields.Count + @" ) {" ); foreach( var f in c.Fields ) { if( f.TypeClass != null && f.TypeClass.IsEnum && !f.IsArray ) { var tn = ( f.TypeNamespace != "" ? f.TypeNamespace : pn ) + "." + f.Type; var e = ( f.TypeClass as Enum ); sb.Append( @" { " + e.GetTypeKeyword() + @" tmp = 0; rtv = bin.read( ref tmp ); if( rtv != ReadState.Success ) return rtv; this." + f.Name + @" = (" + tn + @")tmp; }" ); } else sb.Append( @" rtv = bin.read( ref this." + f.Name + @" ); if( rtv != ReadState.Success ) return rtv;" ); } if( c.Fields.Count > 0 ) { sb.Append( @" if( filledMembers != null ) { for( int j = 0; j < " + c.Fields.Count + @"; ++j ) filledMembers[ j ] = true; }" ); } sb.Append( @" } else { var ms = new " + c.Name + @"_e[ len ]; for( int j = 0; j < len; ++j ) { ms[ j ] = (" + c.Name + @"_e)bin._buf[ bin._readIdx++ ]; } int i = 0;" ); foreach( var f in c.Fields ) { if( f.TypeClass != null && f.TypeClass.IsEnum && !f.IsArray ) { var e = ( f.TypeClass as Enum ); var tn = ( f.TypeNamespace != "" ? f.TypeNamespace : pn ) + "." + f.Type; sb.Append( @" if( ms[ i ] == " + c.Name + @"_e." + f.Name + @" ) { " + e.GetTypeKeyword() + @" tmp = 0; rtv = bin.read( ref tmp ); if( rtv != ReadState.Success ) return rtv; else if ( filledMembers != null ) filledMembers[ (int)" + c.Name + @"_e." + f.Name + @" ] = true; this." + f.Name + @" = (" + tn + @")tmp; if( ++i == ms.Length ) return rtv; }" ); } else sb.Append( @" if( ms[ i ] == " + c.Name + @"_e." + f.Name + @" ) { rtv = bin.read( ref this." + f.Name + @" ); if( rtv != ReadState.Success ) return rtv; else if ( filledMembers != null ) filledMembers[ (int)" + c.Name + @"_e." + f.Name + @" ] = true; if( ++i == ms.Length ) return rtv; }" ); } sb.Append( @" } return rtv; } " ); } else { sb.Append( @" public ReadState readFrom( Bytes bin, bool[] filledMembers = null ) { ReadState rtv; uint len = 0; rtv = bin.read( ref len ); if( rtv != ReadState.Success ) return rtv; if( len == 0 ) return rtv; return ReadState.Fail; } " ); } sb.Append( @" } " ); } sb.Append( @" } " ); } try { sb.WriteToFile( Path.Combine( outputDirPath, pn + "_Partial.cs" ) ); } catch( Exception ex ) { return ex.Message; } System.Diagnostics.Process.Start( "explorer.exe", outputDirPath ); return ""; }
public static void SaveMemberOrdinal(Template t, string outDir) { var allclass = t.Structs; // 生成 Namespace, Class Name, Property Name, property id 的 csv 文件 var sb = new StringBuilder(); foreach (var c in allclass) { foreach (var m in c.Members) { sb.Append(c.Namespace + "," + c.Name + "," + m.Name + "," + m.Ordinal + "\n"); } } if (sb.Length > 0) { --sb.Length; // 去掉最后 \n } sb.WriteToFile(Path.Combine(outDir, t.Name + "_memberOrdinal_config.csv")); }
public void ExtensionMethods_WriteToFile_WhenSavingStringBuilder_ExpectSavedFile() { //------------Setup for test-------------------------- var tmpFile = Path.GetTempFileName(); const string val = "<x><y>1</y></x>"; StringBuilder value = new StringBuilder(val); //------------Execute Test--------------------------- value.WriteToFile(tmpFile, Encoding.UTF8,new TxFileManager()); //------------Assert Results------------------------- var result = File.ReadAllText(tmpFile); // clean up ;) File.Delete(tmpFile); Assert.AreEqual(val, result, "WriteToFile did not write"); }
public static string Gen(Template t, string outDir, string pn) { #region 生成 PkgTypes.cs outDir = Path.Combine(outDir, "CS"); if (!Directory.Exists(outDir)) { try { Directory.CreateDirectory(outDir); } catch (Exception ex) { return(ex.Message); } } _pn = pn; var ns = pn + "PkgTypes"; var ms = pn + "Handler"; ConvertNamespace(t, ns); var sb = new StringBuilder(); sb.Append(@" using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;"); // 生成所有枚举 sb.Append(@" // enums namespace " + pn + @"PkgTypes {"); foreach (var e in t.Enums) { sb.Append(@""); if (!string.IsNullOrWhiteSpace(e.Desc)) { sb.Append(@" // " + e.Desc); } sb.Append(@" public enum " + e.Name + @" : " + GetEnumTypeKeyword(e) + @" {"); foreach (var ef in e.Fields) { if (!string.IsNullOrWhiteSpace(ef.Desc)) { sb.Append(@" /// <summary> /// " + ef.Desc + @" /// </summary> "); } sb.Append(@" " + ef.Name + " = " + ef.Value + ", "); } sb.Append(@" };"); } sb.Append(@" } "); Dictionary <int, string> dc = new Dictionary <int, string>(); Dictionary <int, Class> dcDesc = new Dictionary <int, Class>(); int cmdId = 0; // 生成类声明 sb.Append(@" // struct declares namespace " + pn + @"PkgTypes {"); foreach (var c in t.Classes) { cmdId++; sb.Append(@""); if (!string.IsNullOrWhiteSpace(c.Desc)) { sb.Append(@" // " + c.Desc); } sb.Append(@" public class " + c.Name + @" : IBBWriter, IBBReader {"); // 生成类成员 foreach (var f in c.Fields) { var tn = GetTypeKeyword(f.Declare); sb.Append((f.Desc == "" ? "" : GetComment(f.Desc, 8)) + @" " + "public " + tn + " " + f.Name.ToFirstLower()); if (f.Declare.DataType == DataTypes.Generic || (f.Declare.DataType == DataTypes.Custom && f.Declare.Class != null && !f.Declare.Class.IsEnum)) { sb.Append(@" = new " + tn + "()"); } else if (f.Declare.DataType == DataTypes.BuiltIn && f.Declare.Name == "DateTime") { sb.Append(@" = new " + tn + "(1991,1,1,0,0,0)"); } else if (f.Declare.DataType == DataTypes.BuiltIn && f.Declare.Name == "String") { sb.Append(@" = """""); } else if (f.Declare.DataType == DataTypes.Array) { sb.Append(@" = new byte[0]"); } sb.Append(";"); } dc.Add(cmdId, pn + @"PkgTypes." + c.Name); dcDesc.Add(cmdId, c); // 生成静态直写函数 sb.Append(@" public const short commandType = " + cmdId + @"; "); sb.Append(@" public void WriteToBuffer( ByteBuffer bb ) {"); if (c.Fields.Count != 0) { for (int i = 0; i < c.Fields.Count; ++i) { sb.Append(@" bb.Write( "); var f = c.Fields[i]; if (f.Declare.Class != null && f.Declare.Class.IsEnum) { sb.Append(@"(int)"); } sb.Append(f.Name); sb.Append(@" );"); } } sb.Append(@" } public void ReaderFromBuffer( ByteBuffer bb ) {"); for (int i = 0; i < c.Fields.Count; ++i) { sb.Append(@" "); var f = c.Fields[i]; if (!(f.Declare.DataType == DataTypes.Generic) && !(f.Declare.DataType == DataTypes.BuiltIn && f.Declare.Name == "String")) { if ((f.Declare.DataType != DataTypes.Array) && (f.Declare.MaxLen != 0)) { throw new ArgumentOutOfRangeException("不是字符串和容器类型不能填写大小"); // throw } } sb.Append(f.Name); if (f.Declare.Class != null && f.Declare.Class.IsEnum) { sb.Append(@" = (" + GetTypeKeyword(f.Declare) + @") bb."); } else { sb.Append(" = bb."); } sb.Append(GetTypeBuffer(f.Declare)); if (f.Declare.Childs.Count > 0 && f.Declare.Childs[0].DataType == DataTypes.Custom) { sb.Append(@"<" + GetBufferString(f.Declare.Childs[0]) + @">"); } else if (f.Declare.DataType == DataTypes.Custom && f.Declare.Class != null && !f.Declare.Class.IsEnum) { sb.Append(@"<" + GetBufferString(f.Declare) + @">"); } if (f.Declare.DataType == DataTypes.Array || f.Declare.DataType == DataTypes.Generic || (f.Declare.DataType == DataTypes.BuiltIn && f.Declare.Name == "String")) { sb.Append(@"( " + f.Declare.MinLen + @"," + f.Declare.MaxLen + @" );"); } else { sb.Append(@"();"); } } sb.Append(@" } "); sb.Append(@" };"); } sb.Append(@" }"); try { var outFile = Path.Combine(outDir, ns + ".cs"); sb.WriteToFile(outFile); } catch (Exception ex) { return(ex.Message); } #endregion #region 生成 Rotate.cs sb.Clear(); sb.Append(@" var sb = new StringBuilder(); short pkgId = bb.ReadShort(); switch( pkgId ) {"); foreach (var dcItem in dcDesc) { sb.Append(@" case " + AddNameSpaceString(pn, dcItem.Value.Name) + @".commandType : { " + AddNameSpaceString(pn, dcItem.Value.Name) + @" myItem = null; try { myItem = bb.Read<" + AddNameSpaceString(pn, dcItem.Value.Name) + @">(); } catch { Console.Write( ""ByteBuff Error"" ); } // code here string endString = JsonConvert.SerializeObject(myItem);"); if (pn == "CS") { sb.Append(@" sb.Append(""客服端发送类型为:"");"); } else if (pn == "SC") { sb.Append(@" sb.Append(""服务器返回类型为:"");"); } sb.Append(@" sb.Append(""" + dcItem.Value.Name + @"\n"");"); if (pn == "CS") { sb.Append(@" sb.Append(""客服端发送数据为:"");"); } else if (pn == "SC") { sb.Append(@" sb.Append(""服务器返回数据为:"");"); } sb.Append(@" sb.Append(endString);"); sb.Append(@" sb.Append(""( " + dcItem.Value.Desc + @" )"");"); sb.Append(@" sb.Append(""\n""); break; }"); } sb.Append(@" default: sb.Append(""no commandType""+ pkgId); break; } bb.offset = 0; return sb.ToString(); "); try { var outFile = Path.Combine(outDir, ns + "Rotate.txt"); sb.WriteToFile(outFile); } catch (Exception ex) { return(ex.Message); } #endregion if (pn != "SC") { return(""); } #region 生成 WriteCommandType sb.Clear(); sb.Append(@" static class ByteBufferExt {"); foreach (var c in t.Classes) { sb.Append(@" public static void WriteCommand(this ByteBuffer bb," + pn + @"PkgTypes." + c.Name + @" v) { bb.Write( " + pn + @"PkgTypes." + c.Name + @".commandType ); bb.Write( v ); } "); } sb.Append(@" }"); try { var outFile = Path.Combine(outDir, ns + "WriteCommandType.cs"); sb.WriteToFile(outFile); } catch (Exception ex) { return(ex.Message); } #endregion //System.Diagnostics.Process.Start( "explorer.exe", outDir ); return(""); }
public static string Gen(Template t, string outDir, string pn) { #region 生成 PkgTypes.h outDir = Path.Combine(outDir, "CPP"); if (!Directory.Exists(outDir)) { try { Directory.CreateDirectory(outDir); } catch (Exception ex) { return(ex.Message); } } _pn = pn; var ns = pn + "PkgTypes"; var ms = pn + "Handler"; ConvertNamespace(t, ns); var sb = new StringBuilder(); sb.Append(@"#ifndef __" + pn.ToUpper() + @"PkgTypes_H__ #define __" + pn.ToUpper() + @"PkgTypes_H__ #include ""xxlib.h"" "); // 生成类预声明 sb.Append(@" // predeclares namespace " + pn + @"PkgTypes {"); foreach (var c in t.Classes) { sb.Append(@" struct " + c.Name + @";"); } sb.Append(@" } "); // 生成所有枚举 sb.Append(@" // enums namespace " + pn + @"PkgTypes {"); foreach (var e in t.Enums) { sb.Append(@""); if (!string.IsNullOrWhiteSpace(e.Desc)) { sb.Append(@" // " + e.Desc); } sb.Append(@" enum class " + e.Name + @" : " + GetEnumTypeKeyword(e) + @" {"); foreach (var ef in e.Fields) { sb.Append(@" " + ef.Name + " = " + ef.Value + ", "); if (!string.IsNullOrWhiteSpace(ef.Desc)) { sb.Append("// " + ef.Desc); } } sb.Append(@" };"); } sb.Append(@" } "); Dictionary <int, string> dc = new Dictionary <int, string>(); // 生成类声明 sb.Append(@" // struct declares namespace " + pn + @"PkgTypes {"); int cmdId = 0; foreach (var c in t.Classes) { cmdId++; sb.Append(@""); if (!string.IsNullOrWhiteSpace(c.Desc)) { sb.Append(@" // " + c.Desc); } sb.Append(@" struct " + c.Name + @" : xxlib::Memmoveable {"); sb.Append(@" " + c.Name + @"(){}"); // 生成类成员 foreach (var f in c.Fields) { //maomao var tn = GetTypeKeyword(f.Declare); sb.Append((f.Desc == "" ? "" : GetComment(f.Desc, 8)) + @" " + tn + " " + f.Name.ToFirstLower()); sb.Append((GetDefaultValueByType(f) != "") ? (" = " + GetDefaultValueByType(f)) : ""); sb.Append(" ;"); } dc.Add(cmdId, pn + @"PkgTypes::" + c.Name); //if( c.Fields.Count > 0 ) //{ // 生成静态直写函数 sb.Append(@" const static short commandType; "); // 生成 ByteBuffer 接口函数 sb.Append(@" // interface for ByteBuffer void WriteTo( xxlib::ByteBuffer& bb ) const; bool ReadFrom( xxlib::ByteBuffer& bb );"); //} sb.Append(@" };"); } sb.Append(@" } #endif "); try { var outFile = Path.Combine(outDir, ns + ".h"); sb.WriteToFile(outFile); } catch (Exception ex) { return(ex.Message); } #endregion #region 生成PkgTypes.cpp sb.Clear(); sb.Append(@" #include """ + ns + @".h"" using namespace xxlib; namespace " + pn + @"PkgTypes {"); foreach (var dcItem in dc) { sb.Append(@" const short " + dcItem.Value + @"::commandType = " + dcItem.Key + ";"); } // cmdId = 0; foreach (var c in t.Classes) { cmdId++; //if( c.Fields.Count == 0 ) continue; // 生成 ByteBuffer 接口函数的定义 // todo: namespace support //short cmdId = " + cmdId + @"; sb.Append(@" void " + c.Name + @"::WriteTo( ByteBuffer& bb ) const {"); if (c.Fields.Count != 0) { sb.Append(@" bb.WriteMulti( "); for (int i = 0; i < c.Fields.Count; ++i) { if (i != 0) { sb.Append(", "); } var f = c.Fields[i]; sb.Append(f.Name); } sb.Append(@" );"); } sb.Append(@" } bool " + c.Name + @"::ReadFrom( ByteBuffer& bb ) {"); if (c.Fields.Count != 0) { for (int i = 0; i < c.Fields.Count; ++i) { sb.Append(@" if( !bb.Read( "); var f = c.Fields[i]; sb.Append(f.Name); if (f.Declare.MaxLen > 0) { sb.Append(@", " + f.Declare.MinLen + ", " + f.Declare.MaxLen); } sb.Append(@" ) ) return false;"); } } sb.Append(@" return true;"); sb.Append(@" }"); } sb.Append(@" } "); try { var outFile = Path.Combine(outDir, ns + ".cpp"); sb.WriteToFile(outFile); } catch (Exception ex) { return(ex.Message); } #endregion #region 生成 Rotate.txt sb.Clear(); sb.Append(@" short cmdID=-1; bb.Read(cmdID); switch( cmdID ) {"); foreach (var dcItem in dc) { sb.Append(@" case " + dcItem.Key + @" : { " + dcItem.Value + @" myItem; auto v= bb.Read( myItem ); if(!v) { cout<<""ByteBuffer error""<<endl; } // code here break; }"); } sb.Append(@" default: break; }"); try { var outFile = Path.Combine(outDir, ns + "RotateCpp.txt"); sb.WriteToFile(outFile); } catch (Exception ex) { return(ex.Message); } #endregion #region 生成 EnumToString.h sb.Clear(); sb.Append(@" #include ""SCPkgTypes.h"" class EnumToString { public:"); foreach (var e in t.Enums) { sb.Append(@" static char const* const Get( " + pn + @"PkgTypes::" + e.Name + @" e ); static char const* const GetShow( " + pn + @"PkgTypes::" + e.Name + @" e );"); } sb.Append(@" };"); try { var outFile = Path.Combine(outDir, ns + "EnumToString.h"); sb.WriteToFile(outFile); } catch (Exception ex) { return(ex.Message); } #endregion #region 生成 EnumToString.cpp sb.Clear(); sb.Append(@" #include ""EnumToString.h"""); foreach (var e in t.Enums) { sb.Append(@" char const* const EnumToString::Get( " + pn + @"PkgTypes::" + e.Name + @" e ) { switch(e) {"); foreach (var ee in e.Fields) { sb.Append(@" case " + pn + @"PkgTypes::" + e.Name + "::" + ee.Name + @": return """ + e.Name + "::" + ee.Name + " " + ee.Desc + @""";"); } sb.Append(@" } }"); sb.Append(@" char const* const EnumToString::GetShow( " + pn + @"PkgTypes::" + e.Name + @" e ) { switch(e) {"); foreach (var ee in e.Fields) { sb.Append(@" case " + pn + @"PkgTypes::" + e.Name + "::" + ee.Name + @": return """ + ee.Desc + @""";"); } sb.Append(@" } }"); } try { var outFile = Path.Combine(outDir, ns + "EnumToString.cpp"); sb.WriteToFile(outFile); } catch (Exception ex) { return(ex.Message); } #endregion //System.Diagnostics.Process.Start( "explorer.exe", outDir ); return(""); }