PersistentSchema.EmitCSharp.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using System.Text;
  6. using static System.FormattableString;
  7. namespace Epsylon.glTF2Toolkit.CodeGen
  8. {
  9. class CSharpEmitter
  10. {
  11. #region runtime names
  12. class _RuntimeType
  13. {
  14. internal _RuntimeType(SchemaType t) { _PersistentType = t; }
  15. private readonly SchemaType _PersistentType;
  16. public string RuntimeName { get; set; }
  17. private readonly Dictionary<string, _RuntimeField> _Fields = new Dictionary<string, _RuntimeField>();
  18. private readonly Dictionary<string, _RuntimeEnum> _Enums = new Dictionary<string, _RuntimeEnum>();
  19. public _RuntimeField UseField(FieldInfo finfo)
  20. {
  21. var key = $"{finfo.PersistentName}";
  22. if (_Fields.TryGetValue(key, out _RuntimeField rfield)) return rfield;
  23. rfield = new _RuntimeField(finfo);
  24. _Fields[key] = rfield;
  25. return rfield;
  26. }
  27. public _RuntimeEnum UseEnum(string name)
  28. {
  29. var key = name;
  30. if (_Enums.TryGetValue(key, out _RuntimeEnum renum)) return renum;
  31. renum = new _RuntimeEnum(name);
  32. _Enums[key] = renum;
  33. return renum;
  34. }
  35. }
  36. class _RuntimeEnum
  37. {
  38. internal _RuntimeEnum(string name) { _Name = name; }
  39. private readonly string _Name;
  40. }
  41. class _RuntimeField
  42. {
  43. internal _RuntimeField(FieldInfo f) { _PersistentField = f; }
  44. private readonly FieldInfo _PersistentField;
  45. public string PrivateField { get; set; }
  46. public string PublicProperty { get; set; }
  47. public string CollectionContainer { get; set; }
  48. public string DictionaryContainer { get; set; }
  49. // MinVal, MaxVal, readonly, static
  50. // serialization sections
  51. // deserialization sections
  52. // validation sections
  53. // clone sections
  54. }
  55. private readonly Dictionary<string, _RuntimeType> _Types = new Dictionary<string, _RuntimeType>();
  56. private string _DefaultCollectionContainer = "TItem[]";
  57. #endregion
  58. #region setup & declaration
  59. private string _SanitizeName(string name)
  60. {
  61. name = name.Replace(" ", "");
  62. return name;
  63. }
  64. private _RuntimeType _UseType(SchemaType stype)
  65. {
  66. var key = $"{stype.PersistentName}";
  67. if (_Types.TryGetValue(key, out _RuntimeType rtype)) return rtype;
  68. rtype = new _RuntimeType(stype)
  69. {
  70. RuntimeName = _SanitizeName(stype.PersistentName)
  71. };
  72. _Types[key] = rtype;
  73. return rtype;
  74. }
  75. private _RuntimeField _UseField(FieldInfo finfo) { return _UseType(finfo.DeclaringClass).UseField(finfo); }
  76. public void SetRuntimeName(SchemaType stype, string newName) { _UseType(stype).RuntimeName = newName; }
  77. public void SetRuntimeName(string persistentName, string runtimeName)
  78. {
  79. if (!_Types.TryGetValue(persistentName, out _RuntimeType t)) return;
  80. t.RuntimeName = runtimeName;
  81. }
  82. public void SetFieldName(FieldInfo finfo, string name) { _UseField(finfo).PrivateField = name; }
  83. public string GetFieldRuntimeName(FieldInfo finfo) { return _UseField(finfo).PrivateField; }
  84. public void SetPropertyName(FieldInfo finfo, string name) { _UseField(finfo).PublicProperty = name; }
  85. public string GetPropertyName(FieldInfo finfo) { return _UseField(finfo).PublicProperty; }
  86. public void SetCollectionContainer(string container) { _DefaultCollectionContainer = container; }
  87. public void SetCollectionContainer(FieldInfo finfo, string container) { _UseField(finfo).CollectionContainer = container; }
  88. public void DeclareClass(ClassType type)
  89. {
  90. _UseType(type);
  91. foreach(var f in type.Fields)
  92. {
  93. var runtimeName = _SanitizeName(f.PersistentName);
  94. SetFieldName(f, $"_{runtimeName}");
  95. SetPropertyName(f, runtimeName);
  96. }
  97. }
  98. public void DeclareEnum(EnumType type)
  99. {
  100. _UseType(type);
  101. foreach (var f in type.Values)
  102. {
  103. // SetFieldName(f, $"_{runtimeName}");
  104. // SetPropertyName(f, runtimeName);
  105. }
  106. }
  107. public void DeclareContext(SchemaType.Context context)
  108. {
  109. foreach(var ctype in context.Classes)
  110. {
  111. DeclareClass(ctype);
  112. }
  113. foreach (var etype in context.Enumerations)
  114. {
  115. DeclareEnum(etype);
  116. }
  117. }
  118. private string _GetRuntimeName(SchemaType type, _RuntimeField extra = null)
  119. {
  120. if (type is ObjectType anyType) return typeof(Object).Name;
  121. if (type is StringType strType) return typeof(String).Name;
  122. if (type is BlittableType blitType)
  123. {
  124. var tname = blitType.DataType.Name;
  125. return blitType.IsNullable ? $"{tname}?" : tname;
  126. }
  127. if (type is ArrayType arrayType)
  128. {
  129. var container = extra?.CollectionContainer;
  130. if (string.IsNullOrWhiteSpace(container)) container = _DefaultCollectionContainer;
  131. return container.Replace("TItem",_GetRuntimeName(arrayType.ItemType));
  132. }
  133. if (type is DictionaryType dictType)
  134. {
  135. var key = this._GetRuntimeName(dictType.KeyType);
  136. var val = this._GetRuntimeName(dictType.ValueType);
  137. return $"Dictionary<{key},{val}>";
  138. }
  139. if (type is EnumType enumType)
  140. {
  141. return _UseType(enumType).RuntimeName;
  142. }
  143. if (type is ClassType classType)
  144. {
  145. return _UseType(classType).RuntimeName;
  146. }
  147. throw new NotImplementedException();
  148. }
  149. private string _GetConstantRuntimeName(SchemaType type)
  150. {
  151. if (type is StringType strType) return $"const {typeof(String).Name}";
  152. if (type is BlittableType blitType)
  153. {
  154. var tname = blitType.DataType.Name;
  155. if (blitType.DataType == typeof(Int32)) return $"const {tname}";
  156. if (blitType.DataType == typeof(Single)) return $"const {tname}";
  157. if (blitType.DataType == typeof(Double)) return $"const {tname}";
  158. return $"static readonly {tname}";
  159. }
  160. if (type is EnumType enumType)
  161. {
  162. return $"const {_UseType(enumType).RuntimeName}";
  163. }
  164. if (type is ArrayType aType)
  165. {
  166. return $"static readonly {_UseType(aType).RuntimeName}";
  167. }
  168. throw new NotImplementedException();
  169. }
  170. private Object _GetConstantRuntimeValue(SchemaType type, Object value)
  171. {
  172. if (value == null) throw new ArgumentNullException();
  173. if (type is StringType stype)
  174. {
  175. if (value is String) return value;
  176. return value == null ? null : System.Convert.ChangeType(value, typeof(string), System.Globalization.CultureInfo.InvariantCulture);
  177. }
  178. if (type is BlittableType btype)
  179. {
  180. if (btype.DataType == typeof(Boolean).GetTypeInfo())
  181. {
  182. if (value is Boolean) return value;
  183. var str = value as String;
  184. if (str.ToLower() == "false") return false;
  185. if (str.ToLower() == "true") return true;
  186. throw new NotImplementedException();
  187. }
  188. if (value is String) return value;
  189. return value == null ? null : System.Convert.ChangeType(value, btype.DataType.AsType(), System.Globalization.CultureInfo.InvariantCulture);
  190. }
  191. if (type is EnumType etype)
  192. {
  193. var etypeName = _GetRuntimeName(type);
  194. if (value is String) return $"{etypeName}.{value}";
  195. else return $"({etypeName}){value}";
  196. }
  197. if (type is ArrayType aType)
  198. {
  199. var atypeName = _GetRuntimeName(type);
  200. return value.ToString();
  201. }
  202. throw new NotImplementedException();
  203. }
  204. #endregion
  205. #region emit
  206. public string EmitContext(SchemaType.Context context)
  207. {
  208. var sb = new StringBuilder();
  209. sb.AppendLine("//------------------------------------------------------------------------------------------------");
  210. sb.AppendLine("// This file has been programatically generated; DON´T EDIT!");
  211. sb.AppendLine("//------------------------------------------------------------------------------------------------");
  212. sb.AppendLine();
  213. sb.AppendLine();
  214. sb.AppendLine("using System;");
  215. sb.AppendLine("using System.Collections.Generic;");
  216. sb.AppendLine("using System.Linq;");
  217. sb.AppendLine("using System.Text;");
  218. sb.AppendLine("using System.Numerics;");
  219. sb.AppendLine("using Newtonsoft.Json;");
  220. sb.AppendLine();
  221. sb.AppendLine($"namespace {Constants.OutputNamespace}");
  222. sb.AppendLine("{");
  223. sb.AppendLine("using Collections;".Indent(1));
  224. sb.AppendLine();
  225. foreach (var etype in context.Enumerations)
  226. {
  227. var cout = EmitEnum(etype);
  228. sb.AppendLine(cout);
  229. sb.AppendLine();
  230. }
  231. foreach (var ctype in context.Classes)
  232. {
  233. var cout = EmitClass(ctype);
  234. sb.AppendLine(cout);
  235. sb.AppendLine();
  236. }
  237. sb.AppendLine("}");
  238. return sb.ToString();
  239. }
  240. public string EmitEnum(EnumType type)
  241. {
  242. var sb = new StringBuilder();
  243. sb.EmitLine(1, $"public enum {_GetRuntimeName(type)}");
  244. sb.EmitLine(1, "{");
  245. if (type.UseIntegers)
  246. {
  247. foreach (var kvp in type.Values)
  248. {
  249. var k = kvp.Key;
  250. sb.EmitLine(2, $"{k} = {kvp.Value},");
  251. }
  252. }
  253. else
  254. {
  255. foreach (var kvp in type.Values)
  256. {
  257. var k = kvp.Key;
  258. sb.EmitLine(2, $"{k},");
  259. }
  260. }
  261. sb.EmitLine(1, "}");
  262. return sb.ToString();
  263. }
  264. public string EmitClass(ClassType type)
  265. {
  266. var xclass = new CSharpClassEmitter(this)
  267. {
  268. ClassDeclaration = _GetClassDeclaration(type),
  269. HasBaseClass = type.BaseClass != null
  270. };
  271. foreach (var f in type.Fields)
  272. {
  273. var trname = _GetRuntimeName(f.FieldType);
  274. var frname = GetFieldRuntimeName(f);
  275. xclass.AddFields(_GetClassField(f));
  276. if (f.FieldType is EnumType etype)
  277. {
  278. // emit serializer
  279. var smethod = etype.UseIntegers ? "SerializePropertyEnumValue" : "SerializePropertyEnumSymbol";
  280. smethod = $"{smethod}<{trname}>(writer,\"{f.PersistentName}\",{frname}";
  281. if (f.DefaultValue != null) smethod += $", {frname}Default";
  282. smethod += ");";
  283. xclass.AddFieldSerializerCase(smethod);
  284. // emit deserializer
  285. xclass.AddFieldDeserializerCase(f.PersistentName, $"{frname} = DeserializeValue<{_GetRuntimeName(etype)}>(reader);");
  286. continue;
  287. }
  288. xclass.AddFieldSerializerCase(_GetJSonSerializerMethod(f));
  289. xclass.AddFieldDeserializerCase(f.PersistentName, _GetJSonDeserializerMethod(f));
  290. }
  291. return String.Join("\r\n",xclass.EmitCode().Indent(1));
  292. }
  293. private string _GetClassDeclaration(ClassType type)
  294. {
  295. var classDecl = string.Empty;
  296. classDecl += "partial ";
  297. classDecl += "class ";
  298. classDecl += _GetRuntimeName(type);
  299. if (type.BaseClass != null) classDecl += $" : {_GetRuntimeName(type.BaseClass)}";
  300. return classDecl;
  301. }
  302. private IEnumerable<string> _GetClassField(FieldInfo f)
  303. {
  304. var tdecl = _GetRuntimeName(f.FieldType, _UseField(f));
  305. var fname = GetFieldRuntimeName(f);
  306. string defval = string.Empty;
  307. if (f.DefaultValue != null)
  308. {
  309. var tconst = _GetConstantRuntimeName(f.FieldType);
  310. var vconst = _GetConstantRuntimeValue(f.FieldType, f.DefaultValue);
  311. // fix boolean value
  312. if (vconst is Boolean bconst) vconst = bconst ? "true" : "false";
  313. defval = $"{fname}Default";
  314. yield return Invariant($"private {tconst} {defval} = {vconst};");
  315. }
  316. if (f.MinimumValue != null)
  317. {
  318. var tconst = _GetConstantRuntimeName(f.FieldType);
  319. var vconst = _GetConstantRuntimeValue(f.FieldType, f.MinimumValue);
  320. yield return Invariant($"private {tconst} {fname}Minimum = {vconst};");
  321. }
  322. if (f.MaximumValue != null)
  323. {
  324. var tconst = _GetConstantRuntimeName(f.FieldType);
  325. var vconst = _GetConstantRuntimeValue(f.FieldType, f.MaximumValue);
  326. yield return Invariant($"private {tconst} {fname}Maximum = {vconst};");
  327. }
  328. if (f.MinItems > 0)
  329. {
  330. yield return $"private const int {fname}MinItems = {f.MinItems};";
  331. }
  332. if (f.MaxItems > 0 && f.MaxItems < int.MaxValue)
  333. {
  334. yield return $"private const int {fname}MaxItems = {f.MaxItems};";
  335. }
  336. if (f.FieldType is EnumType etype && etype.IsNullable) tdecl = tdecl + "?";
  337. yield return string.IsNullOrEmpty(defval) ? $"private {tdecl} {fname};" : $"private {tdecl} {fname} = {defval};";
  338. yield return string.Empty;
  339. }
  340. private string _GetJSonSerializerMethod(FieldInfo f)
  341. {
  342. var pname = f.PersistentName;
  343. var fname = GetFieldRuntimeName(f);
  344. if (f.FieldType is ClassType ctype)
  345. {
  346. return $"SerializePropertyObject(writer,\"{pname}\",{fname});";
  347. }
  348. if (f.FieldType is ArrayType atype)
  349. {
  350. if (f.MinItems > 0) return $"SerializeProperty(writer,\"{pname}\",{fname},{fname}MinItems);";
  351. return $"SerializeProperty(writer,\"{pname}\",{fname});";
  352. }
  353. if (f.DefaultValue != null) return $"SerializeProperty(writer,\"{pname}\",{fname},{fname}Default);";
  354. return $"SerializeProperty(writer,\"{pname}\",{fname});";
  355. }
  356. private string _GetJSonDeserializerMethod(FieldInfo f)
  357. {
  358. var fname = GetFieldRuntimeName(f);
  359. if (f.FieldType is ArrayType atype)
  360. {
  361. var titem = _GetRuntimeName(atype.ItemType);
  362. return $"DeserializeList<{titem}>(reader,{fname});";
  363. }
  364. else if (f.FieldType is DictionaryType dtype)
  365. {
  366. var titem = _GetRuntimeName(dtype.ValueType);
  367. return $"DeserializeDictionary<{titem}>(reader,{fname});";
  368. }
  369. return $"{fname} = DeserializeValue<{_GetRuntimeName(f.FieldType)}>(reader);";
  370. }
  371. #endregion
  372. }
  373. class CSharpClassEmitter
  374. {
  375. public CSharpClassEmitter(CSharpEmitter emitter)
  376. {
  377. _Emitter = emitter;
  378. }
  379. private readonly CSharpEmitter _Emitter;
  380. private readonly List<string> _Fields = new List<string>();
  381. private readonly List<string> _SerializerBody = new List<string>();
  382. private readonly List<string> _DeserializerSwitchBody = new List<string>();
  383. public string ClassDeclaration { get; set; }
  384. public bool HasBaseClass { get; set; }
  385. public void AddFields(IEnumerable<string> lines) { _Fields.AddRange(lines); }
  386. public void AddFieldSerializerCase(string line) { _SerializerBody.Add(line); }
  387. public void AddFieldDeserializerCase(string persistentName, string line)
  388. {
  389. _DeserializerSwitchBody.Add($"case \"{persistentName}\": {line} break;");
  390. }
  391. public IEnumerable<string> EmitCode()
  392. {
  393. yield return ClassDeclaration;
  394. yield return "{";
  395. yield return string.Empty;
  396. foreach (var l in _Fields.Indent(1)) yield return l;
  397. yield return string.Empty;
  398. yield return "protected override void SerializeProperties(JsonWriter writer)".Indent(1);
  399. yield return "{".Indent(1);
  400. if (HasBaseClass) yield return "base.SerializeProperties(writer);".Indent(2);
  401. foreach (var l in _SerializerBody.Indent(2)) yield return l;
  402. yield return "}".Indent(1);
  403. yield return string.Empty;
  404. yield return "protected override void DeserializeProperty(JsonReader reader, string property)".Indent(1);
  405. yield return "{".Indent(1);
  406. yield return "switch (property)".Indent(2);
  407. yield return "{".Indent(2);
  408. foreach (var l in _DeserializerSwitchBody.Indent(3)) yield return l;
  409. if (HasBaseClass) yield return "default: base.DeserializeProperty(reader,property); break;".Indent(3);
  410. else yield return "default: throw new NotImplementedException();".Indent(3);
  411. yield return "}".Indent(2);
  412. yield return "}".Indent(1);
  413. yield return string.Empty;
  414. yield return "}";
  415. }
  416. }
  417. }