EmitCSharp.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  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 static string _SanitizeName(string name)
  66. {
  67. return name.Replace(" ", string.Empty, StringComparison.OrdinalIgnoreCase);
  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).Replace("@","at", StringComparison.Ordinal);
  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. switch (type)
  127. {
  128. case ObjectType anyType: return anyType.PersistentName;
  129. case StringType strType: return strType.PersistentName;
  130. case BlittableType blitType:
  131. {
  132. var tname = blitType.DataType.Name;
  133. return blitType.IsNullable ? $"{tname}?" : tname;
  134. }
  135. case ArrayType arrayType:
  136. {
  137. var container = extra?.CollectionContainer;
  138. if (string.IsNullOrWhiteSpace(container)) container = _DefaultCollectionContainer;
  139. return container.Replace("TItem", _GetRuntimeName(arrayType.ItemType), StringComparison.Ordinal);
  140. }
  141. case DictionaryType dictType:
  142. {
  143. var key = _GetRuntimeName(dictType.KeyType);
  144. var val = _GetRuntimeName(dictType.ValueType);
  145. return $"Dictionary<{key},{val}>";
  146. }
  147. case EnumType enumType: return _UseType(enumType).RuntimeName;
  148. case ClassType classType: return _UseType(classType).RuntimeName;
  149. default: throw new NotImplementedException();
  150. }
  151. }
  152. private string _GetConstantRuntimeName(SchemaType type)
  153. {
  154. switch (type)
  155. {
  156. case StringType strType: return $"const {typeof(string).Name}";
  157. case BlittableType blitType:
  158. {
  159. var tname = blitType.DataType.Name;
  160. if (blitType.DataType == typeof(int)) return $"const {tname}";
  161. if (blitType.DataType == typeof(float)) return $"const {tname}";
  162. if (blitType.DataType == typeof(double)) return $"const {tname}";
  163. return $"static readonly {tname}";
  164. }
  165. case EnumType enumType: return $"const {_UseType(enumType).RuntimeName}";
  166. case ArrayType aType: return $"static readonly {_UseType(aType).RuntimeName}";
  167. default: throw new NotImplementedException();
  168. }
  169. }
  170. private Object _GetConstantRuntimeValue(SchemaType type, Object value)
  171. {
  172. if (value == null) throw new ArgumentNullException(nameof(value));
  173. switch (type)
  174. {
  175. case StringType _:
  176. return value is string
  177. ? value
  178. : Convert.ChangeType(value, typeof(string), System.Globalization.CultureInfo.InvariantCulture);
  179. case BlittableType btype:
  180. {
  181. if (btype.DataType == typeof(bool).GetTypeInfo())
  182. {
  183. if (value is bool) return value;
  184. var str = value as string;
  185. if (str.ToUpperInvariant() == "FALSE") return false;
  186. if (str.ToUpperInvariant() == "TRUE") return true;
  187. throw new NotImplementedException();
  188. }
  189. return value is string
  190. ? value
  191. : Convert.ChangeType(value, btype.DataType.AsType(), System.Globalization.CultureInfo.InvariantCulture);
  192. }
  193. case EnumType etype:
  194. {
  195. var etypeName = _GetRuntimeName(type);
  196. if (value is string) return $"{etypeName}.{value}";
  197. else return $"({etypeName}){value}";
  198. }
  199. case ArrayType aType:
  200. {
  201. var atypeName = _GetRuntimeName(type);
  202. return value.ToString();
  203. }
  204. default: throw new NotImplementedException();
  205. }
  206. }
  207. #endregion
  208. #region emit
  209. public string EmitContext(SchemaType.Context context)
  210. {
  211. var sb = new StringBuilder();
  212. sb.AppendLine("// <auto-generated/>");
  213. sb.AppendLine();
  214. sb.AppendLine("//------------------------------------------------------------------------------------------------");
  215. sb.AppendLine("// This file has been programatically generated; DON´T EDIT!");
  216. sb.AppendLine("//------------------------------------------------------------------------------------------------");
  217. sb.AppendLine();
  218. sb.AppendLine("#pragma warning disable SA1001");
  219. sb.AppendLine("#pragma warning disable SA1027");
  220. sb.AppendLine("#pragma warning disable SA1028");
  221. sb.AppendLine("#pragma warning disable SA1121");
  222. sb.AppendLine("#pragma warning disable SA1205");
  223. sb.AppendLine("#pragma warning disable SA1309");
  224. sb.AppendLine("#pragma warning disable SA1402");
  225. sb.AppendLine("#pragma warning disable SA1505");
  226. sb.AppendLine("#pragma warning disable SA1507");
  227. sb.AppendLine("#pragma warning disable SA1508");
  228. sb.AppendLine("#pragma warning disable SA1652");
  229. sb.AppendLine();
  230. sb.AppendLine("using System;");
  231. sb.AppendLine("using System.Collections.Generic;");
  232. sb.AppendLine("using System.Linq;");
  233. sb.AppendLine("using System.Text;");
  234. sb.AppendLine("using System.Numerics;");
  235. #if USENEWTONSOFT
  236. sb.AppendLine("using Newtonsoft.Json;");
  237. #else
  238. sb.AppendLine("using System.Text.Json;");
  239. #endif
  240. sb.AppendLine();
  241. sb.AppendLine($"namespace {Constants.OutputNamespace}");
  242. sb.AppendLine("{");
  243. sb.AppendLine("using Collections;".Indent(1));
  244. sb.AppendLine();
  245. foreach (var etype in context.Enumerations)
  246. {
  247. var cout = EmitEnum(etype);
  248. sb.AppendLine(cout);
  249. sb.AppendLine();
  250. }
  251. foreach (var ctype in context.Classes)
  252. {
  253. if (ctype.IgnoredByEmitter) continue;
  254. var cout = EmitClass(ctype);
  255. sb.AppendLine(cout);
  256. sb.AppendLine();
  257. }
  258. sb.AppendLine("}");
  259. return sb.ToString();
  260. }
  261. public string EmitEnum(EnumType type)
  262. {
  263. var sb = new StringBuilder();
  264. foreach (var l in type.Description.EmitSummary(0)) sb.EmitLine(1, l);
  265. sb.EmitLine(1, $"public enum {_GetRuntimeName(type)}");
  266. sb.EmitLine(1, "{");
  267. if (type.UseIntegers)
  268. {
  269. foreach (var kvp in type.Values)
  270. {
  271. var k = kvp.Key;
  272. sb.EmitLine(2, $"{k} = {kvp.Value},");
  273. }
  274. }
  275. else
  276. {
  277. foreach (var kvp in type.Values)
  278. {
  279. var k = kvp.Key;
  280. sb.EmitLine(2, $"{k},");
  281. }
  282. }
  283. sb.EmitLine(1, "}");
  284. return sb.ToString();
  285. }
  286. public string EmitClass(ClassType type)
  287. {
  288. var xclass = new CSharpClassEmitter(this)
  289. {
  290. ClassSummary = type.Description,
  291. ClassDeclaration = _GetClassDeclaration(type),
  292. HasBaseClass = type.BaseClass != null
  293. };
  294. xclass.AddFields(type);
  295. return String.Join("\r\n",xclass.EmitCode().Indent(1));
  296. }
  297. private string _GetClassDeclaration(ClassType type)
  298. {
  299. var classDecl = string.Empty;
  300. classDecl += "partial ";
  301. classDecl += "class ";
  302. classDecl += _GetRuntimeName(type);
  303. if (type.BaseClass != null) classDecl += $" : {_GetRuntimeName(type.BaseClass)}";
  304. return classDecl;
  305. }
  306. internal IEnumerable<string> _GetClassField(FieldInfo f)
  307. {
  308. var tdecl = _GetRuntimeName(f.FieldType, _UseField(f));
  309. var fname = GetFieldRuntimeName(f);
  310. string defval = string.Empty;
  311. if (f.DefaultValue != null)
  312. {
  313. var tconst = _GetConstantRuntimeName(f.FieldType);
  314. var vconst = _GetConstantRuntimeValue(f.FieldType, f.DefaultValue);
  315. // fix boolean value
  316. if (vconst is Boolean bconst) vconst = bconst ? "true" : "false";
  317. defval = $"{fname}Default";
  318. yield return Invariant($"private {tconst} {defval} = {vconst};");
  319. }
  320. if (f.ExclusiveMinimumValue != null)
  321. {
  322. var tconst = _GetConstantRuntimeName(f.FieldType);
  323. var vconst = _GetConstantRuntimeValue(f.FieldType, f.ExclusiveMinimumValue);
  324. yield return Invariant($"private {tconst} {fname}ExclusiveMinimum = {vconst};");
  325. }
  326. if (f.InclusiveMinimumValue != null)
  327. {
  328. var tconst = _GetConstantRuntimeName(f.FieldType);
  329. var vconst = _GetConstantRuntimeValue(f.FieldType, f.InclusiveMinimumValue);
  330. yield return Invariant($"private {tconst} {fname}Minimum = {vconst};");
  331. }
  332. if (f.InclusiveMaximumValue != null)
  333. {
  334. var tconst = _GetConstantRuntimeName(f.FieldType);
  335. var vconst = _GetConstantRuntimeValue(f.FieldType, f.InclusiveMaximumValue);
  336. yield return Invariant($"private {tconst} {fname}Maximum = {vconst};");
  337. }
  338. if (f.ExclusiveMaximumValue != null)
  339. {
  340. var tconst = _GetConstantRuntimeName(f.FieldType);
  341. var vconst = _GetConstantRuntimeValue(f.FieldType, f.ExclusiveMaximumValue);
  342. yield return Invariant($"private {tconst} {fname}ExclusiveMaximum = {vconst};");
  343. }
  344. if (f.MinItems > 0)
  345. {
  346. yield return $"private const int {fname}MinItems = {f.MinItems};";
  347. }
  348. if (f.MaxItems > 0 && f.MaxItems < int.MaxValue)
  349. {
  350. yield return $"private const int {fname}MaxItems = {f.MaxItems};";
  351. }
  352. if (f.FieldType is EnumType etype && etype.IsNullable) tdecl = tdecl + "?";
  353. yield return string.IsNullOrEmpty(defval) ? $"private {tdecl} {fname};" : $"private {tdecl} {fname} = {defval};";
  354. yield return string.Empty;
  355. }
  356. #endregion
  357. }
  358. /// <summary>
  359. /// Utility class to emit a <see cref="SchemaReflection.ClassType"/>
  360. /// as c# source code
  361. /// </summary>
  362. class CSharpClassEmitter
  363. {
  364. #region constructor
  365. public CSharpClassEmitter(CSharpEmitter emitter)
  366. {
  367. _Emitter = emitter;
  368. }
  369. #endregion
  370. #region data
  371. private readonly CSharpEmitter _Emitter;
  372. private readonly List<string> _Fields = new List<string>();
  373. private readonly List<string> _SerializerBody = new List<string>();
  374. private readonly List<string> _DeserializerSwitchBody = new List<string>();
  375. public string ClassSummary { get; set; }
  376. public string ClassDeclaration { get; set; }
  377. public bool HasBaseClass { get; set; }
  378. private const string _READERMODIFIER = "ref ";
  379. #endregion
  380. #region API
  381. public void AddFields(ClassType type)
  382. {
  383. foreach (var f in type.Fields)
  384. {
  385. var trname = _Emitter._GetRuntimeName(f.FieldType);
  386. var frname = _Emitter.GetFieldRuntimeName(f);
  387. _Fields.AddRange(_Emitter._GetClassField(f));
  388. if (f.FieldType is EnumType etype)
  389. {
  390. // emit serializer
  391. var smethod = etype.UseIntegers ? "SerializePropertyEnumValue" : "SerializePropertyEnumSymbol";
  392. smethod = $"{smethod}<{trname}>(writer, \"{f.PersistentName}\", {frname}";
  393. if (f.DefaultValue != null) smethod += $", {frname}Default";
  394. smethod += ");";
  395. this.AddFieldSerializerCase(smethod);
  396. // emit deserializer
  397. this.AddFieldDeserializerCase(f.PersistentName, $"{frname} = DeserializePropertyValue<{_Emitter._GetRuntimeName(etype)}>({_READERMODIFIER}reader);");
  398. continue;
  399. }
  400. this.AddFieldSerializerCase(_GetJSonSerializerMethod(f));
  401. this.AddFieldDeserializerCase(f.PersistentName, _GetJSonDeserializerMethod(f));
  402. }
  403. }
  404. private string _GetJSonSerializerMethod(FieldInfo f)
  405. {
  406. var pname = f.PersistentName;
  407. var fname = _Emitter.GetFieldRuntimeName(f);
  408. if (f.FieldType is ClassType ctype)
  409. {
  410. return $"SerializePropertyObject(writer, \"{pname}\", {fname});";
  411. }
  412. if (f.FieldType is ArrayType atype)
  413. {
  414. if (f.MinItems > 0) return $"SerializeProperty(writer, \"{pname}\", {fname}, {fname}MinItems);";
  415. return $"SerializeProperty(writer,\"{pname}\",{fname});";
  416. }
  417. if (f.DefaultValue != null) return $"SerializeProperty(writer, \"{pname}\", {fname}, {fname}Default);";
  418. return $"SerializeProperty(writer, \"{pname}\", {fname});";
  419. }
  420. private string _GetJSonDeserializerMethod(FieldInfo f)
  421. {
  422. var fname = _Emitter.GetFieldRuntimeName(f);
  423. if (f.FieldType is ArrayType atype)
  424. {
  425. var titem = _Emitter._GetRuntimeName(atype.ItemType);
  426. return $"DeserializePropertyList<{titem}>({_READERMODIFIER}reader, {fname});";
  427. }
  428. else if (f.FieldType is DictionaryType dtype)
  429. {
  430. var titem = _Emitter._GetRuntimeName(dtype.ValueType);
  431. return $"DeserializePropertyDictionary<{titem}>({_READERMODIFIER}reader, {fname});";
  432. }
  433. return $"{fname} = DeserializePropertyValue<{_Emitter._GetRuntimeName(f.FieldType)}>({_READERMODIFIER}reader);";
  434. }
  435. public void AddFieldSerializerCase(string line) { _SerializerBody.Add(line); }
  436. public void AddFieldDeserializerCase(string persistentName, string line)
  437. {
  438. _DeserializerSwitchBody.Add($"case \"{persistentName}\": {line} break;");
  439. }
  440. public IEnumerable<string> EmitCode()
  441. {
  442. #if USENEWTONSOFT
  443. var readerType = "JsonReader";
  444. var writerType = "JsonWriter";
  445. #else
  446. var readerType = "ref Utf8JsonReader";
  447. var writerType = "Utf8JsonWriter";
  448. #endif
  449. foreach (var l in ClassSummary.EmitSummary(0)) yield return l;
  450. yield return "#if NET6_0_OR_GREATER";
  451. yield return "[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.NonPublicConstructors | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicConstructors)]";
  452. yield return "#endif";
  453. yield return "[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"SharpGLTF.CodeGen\", \"1.0.0.0\")]";
  454. yield return ClassDeclaration;
  455. yield return "{";
  456. yield return string.Empty;
  457. foreach (var l in _Fields.Indent(1)) yield return l;
  458. yield return string.Empty;
  459. // yield return "/// <inheritdoc />".Indent(1);
  460. yield return $"protected override void SerializeProperties({writerType} writer)".Indent(1);
  461. yield return "{".Indent(1);
  462. if (HasBaseClass) yield return "base.SerializeProperties(writer);".Indent(2);
  463. foreach (var l in _SerializerBody.Indent(2)) yield return l;
  464. yield return "}".Indent(1);
  465. yield return string.Empty;
  466. // yield return "/// <inheritdoc />".Indent(1);
  467. yield return $"protected override void DeserializeProperty(string jsonPropertyName, {readerType} reader)".Indent(1);
  468. yield return "{".Indent(1);
  469. yield return "switch (jsonPropertyName)".Indent(2);
  470. yield return "{".Indent(2);
  471. foreach (var l in _DeserializerSwitchBody.Indent(3)) yield return l;
  472. if (HasBaseClass) yield return $"default: base.DeserializeProperty(jsonPropertyName,{_READERMODIFIER}reader); break;".Indent(3);
  473. else yield return "default: throw new NotImplementedException();".Indent(3);
  474. yield return "}".Indent(2);
  475. yield return "}".Indent(1);
  476. yield return string.Empty;
  477. yield return "}";
  478. }
  479. #endregion
  480. }
  481. }