EmitCSharp.cs 21 KB

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