EmitCSharp.cs 21 KB

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