EmitCSharp.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801
  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. public partial class CSharpEmitter
  16. {
  17. #region data
  18. private readonly Dictionary<string, _RuntimeType> _Types = new Dictionary<string, _RuntimeType>();
  19. private string _DefaultCollectionContainer = "TItem[]";
  20. private System.Diagnostics.DebuggerBrowsableState? _FieldsBrowsableState;
  21. #endregion
  22. #region setup & declaration - types
  23. public void SetRuntimeName(string persistentName, string runtimeName, string runtimeNamespace = null)
  24. {
  25. if (!_Types.TryGetValue(persistentName, out _RuntimeType t)) return;
  26. t.RuntimeNamespace = runtimeNamespace;
  27. t.RuntimeName = runtimeName;
  28. }
  29. public void SetRuntimeName(SchemaType stype, string runtimeName, string runtimeNamespace = null)
  30. {
  31. var t = _UseType(stype);
  32. t.RuntimeNamespace = runtimeNamespace;
  33. t.RuntimeName = runtimeName;
  34. }
  35. public void AddRuntimeComment(string persistentName, string comment)
  36. {
  37. if (!_Types.TryGetValue(persistentName, out _RuntimeType t)) return;
  38. t.RuntimeComments.Add(comment);
  39. }
  40. public IReadOnlyList<string> GetRuntimeComments(SchemaType cls)
  41. {
  42. return !_TryGetType(cls, out var rtype)
  43. ? Array.Empty<string>()
  44. : (IReadOnlyList<string>)rtype.RuntimeComments;
  45. }
  46. /// <summary>
  47. /// Gets the runtime name associated to the type with the given <paramref name="persistentName"/>
  48. /// </summary>
  49. /// <param name="persistentName">The persistent name of the type.</param>
  50. /// <returns>The runtime name associated to the type.</returns>
  51. public string GetRuntimeName(string persistentName)
  52. {
  53. return _Types[persistentName].RuntimeName;
  54. }
  55. /// <summary>
  56. /// Gets the runtime namespace associated to the type with the given <paramref name="persistentName"/>
  57. /// </summary>
  58. /// <param name="persistentName">The persistent name of the type.</param>
  59. /// <returns>The runtime namespace associated to the type.</returns>
  60. public string GetRuntimeNamespace(string persistentName)
  61. {
  62. return _Types[persistentName].RuntimeNamespace ?? Constants.OutputNamespace;
  63. }
  64. public void SetDefaultCollectionContainer(string container) { _DefaultCollectionContainer = container; }
  65. public void SetFieldToChildrenList(SchemaType.Context ctx, string persistentName, string fieldName)
  66. {
  67. var classType = ctx.FindClass(persistentName);
  68. if (classType == null) return;
  69. var field = classType.UseField(fieldName);
  70. var runtimeName = this.GetRuntimeName(persistentName);
  71. this.SetCollectionContainer(field, $"ChildrenList<TItem,{runtimeName}>");
  72. }
  73. public void SetFieldToChildrenDictionary(SchemaType.Context ctx, string persistentName, string fieldName)
  74. {
  75. var classType = ctx.FindClass(persistentName);
  76. if (classType == null) return;
  77. var field = classType.UseField(fieldName);
  78. var runtimeName = this.GetRuntimeName(persistentName);
  79. this.SetCollectionContainer(field, $"ChildrenDictionary<TItem,{runtimeName}>");
  80. }
  81. public void DeclareClass(ClassType type)
  82. {
  83. _UseType(type);
  84. foreach (var f in type.Fields)
  85. {
  86. var runtimeName = _SanitizeName(f.PersistentName).Replace("@", "at", StringComparison.Ordinal);
  87. SetFieldRuntimeName(f, $"_{runtimeName}");
  88. SetPropertyName(f, runtimeName);
  89. }
  90. }
  91. public void DeclareEnum(EnumType type)
  92. {
  93. _UseType(type);
  94. foreach (var f in type.Values)
  95. {
  96. // SetFieldName(f, $"_{runtimeName}");
  97. // SetPropertyName(f, runtimeName);
  98. }
  99. }
  100. public void DeclareContext(SchemaType.Context context)
  101. {
  102. foreach (var ctype in context.Classes) { DeclareClass(ctype); }
  103. foreach (var etype in context.Enumerations) { DeclareEnum(etype); }
  104. }
  105. #endregion
  106. #region setup & declaration - fields
  107. public void SetFieldRuntimeName(FieldInfo finfo, string name) { _UseField(finfo).PrivateField = name; }
  108. public string GetFieldRuntimeName(FieldInfo finfo) { return _UseField(finfo).PrivateField; }
  109. public void SetPropertyName(FieldInfo finfo, string name) { _UseField(finfo).PublicProperty = name; }
  110. public string GetPropertyName(FieldInfo finfo) { return _UseField(finfo).PublicProperty; }
  111. public void SetCollectionContainer(FieldInfo finfo, string container) { _UseField(finfo).CollectionContainer = container; }
  112. #endregion
  113. #region core API
  114. private static string _SanitizeName(string name)
  115. {
  116. return name.Replace(" ", string.Empty, StringComparison.OrdinalIgnoreCase);
  117. }
  118. private _RuntimeType _UseType(SchemaType stype)
  119. {
  120. var key = $"{stype.PersistentName}";
  121. if (_Types.TryGetValue(key, out _RuntimeType rtype)) return rtype;
  122. rtype = new _RuntimeType(stype)
  123. {
  124. RuntimeName = _SanitizeName(stype.PersistentName)
  125. };
  126. _Types[key] = rtype;
  127. return rtype;
  128. }
  129. private bool _TryGetType(SchemaType stype, out _RuntimeType rtype)
  130. {
  131. var key = $"{stype.PersistentName}";
  132. return _Types.TryGetValue(key, out rtype);
  133. }
  134. private _RuntimeField _UseField(FieldInfo finfo) { return _UseType(finfo.DeclaringClass).UseField(finfo); }
  135. internal string _GetRuntimeName(SchemaType type) { return _GetRuntimeName(type, null); }
  136. private string _GetRuntimeName(SchemaType type, _RuntimeField extra)
  137. {
  138. switch (type)
  139. {
  140. case null: throw new ArgumentNullException(nameof(type));
  141. case ObjectType anyType: return anyType.PersistentName;
  142. case StringType strType: return strType.PersistentName;
  143. case BlittableType blitType:
  144. {
  145. var tname = blitType.DataType.Name;
  146. return blitType.IsNullable ? $"{tname}?" : tname;
  147. }
  148. case ArrayType arrayType:
  149. {
  150. var container = extra?.CollectionContainer;
  151. if (string.IsNullOrWhiteSpace(container)) container = _DefaultCollectionContainer;
  152. return container.Replace("TItem", _GetRuntimeName(arrayType.ItemType), StringComparison.Ordinal);
  153. }
  154. case DictionaryType dictType:
  155. {
  156. var key = _GetRuntimeName(dictType.KeyType);
  157. var val = _GetRuntimeName(dictType.ValueType);
  158. var container = extra?.CollectionContainer ?? string.Empty;
  159. if (container.StartsWith("ChildrenDictionary<"))
  160. {
  161. if (key == "String") return container.Replace("TItem", val, StringComparison.Ordinal);
  162. }
  163. return $"Dictionary<{key},{val}>";
  164. }
  165. case EnumType enumType: return _UseType(enumType).RuntimeName;
  166. case ClassType classType: return _UseType(classType).RuntimeName;
  167. default: throw new NotImplementedException(type.PersistentName);
  168. }
  169. }
  170. private string _GetConstantRuntimeName(SchemaType type)
  171. {
  172. switch (type)
  173. {
  174. case StringType strType: return $"const {typeof(string).Name}";
  175. case BlittableType blitType:
  176. {
  177. var tname = blitType.DataType.Name;
  178. if (blitType.DataType == typeof(int)) return $"const {tname}";
  179. if (blitType.DataType == typeof(float)) return $"const {tname}";
  180. if (blitType.DataType == typeof(double)) return $"const {tname}";
  181. return $"static readonly {tname}";
  182. }
  183. case EnumType enumType: return $"const {_UseType(enumType).RuntimeName}";
  184. case ArrayType aType: return $"static readonly {_UseType(aType).RuntimeName}";
  185. default: throw new NotImplementedException();
  186. }
  187. }
  188. internal Object _GetConstantRuntimeValue(SchemaType type, Object value)
  189. {
  190. ArgumentNullException.ThrowIfNull(value);
  191. switch (type)
  192. {
  193. case StringType _:
  194. return value is string
  195. ? value
  196. : Convert.ChangeType(value, typeof(string), System.Globalization.CultureInfo.InvariantCulture);
  197. case BlittableType btype:
  198. {
  199. if (btype.DataType == typeof(bool).GetTypeInfo())
  200. {
  201. if (value is bool) return value;
  202. var str = value as string;
  203. if (str.Equals("FALSE", StringComparison.OrdinalIgnoreCase)) return false;
  204. if (str.Equals("TRUE", StringComparison.OrdinalIgnoreCase)) return true;
  205. throw new NotImplementedException();
  206. }
  207. return value is string
  208. ? value
  209. : Convert.ChangeType(value, btype.DataType.AsType(), System.Globalization.CultureInfo.InvariantCulture);
  210. }
  211. case EnumType etype:
  212. {
  213. var etypeName = _GetRuntimeName(type);
  214. if (value is string) return $"{etypeName}.{value}";
  215. else return $"({etypeName}){value}";
  216. }
  217. case ArrayType aType:
  218. {
  219. var atypeName = _GetRuntimeName(type);
  220. return value.ToString();
  221. }
  222. default: throw new NotImplementedException();
  223. }
  224. }
  225. #endregion
  226. #region emit
  227. public string EmitContext(SchemaType.Context context)
  228. {
  229. var sb = new StringBuilder();
  230. sb.AppendLine("// <auto-generated/>");
  231. sb.AppendLine();
  232. sb.AppendLine("//------------------------------------------------------------------------------------------------");
  233. sb.AppendLine("// This file has been programatically generated; DON´T EDIT!");
  234. sb.AppendLine("//------------------------------------------------------------------------------------------------");
  235. sb.AppendLine();
  236. sb.AppendLine("#pragma warning disable SA1001");
  237. sb.AppendLine("#pragma warning disable SA1027");
  238. sb.AppendLine("#pragma warning disable SA1028");
  239. sb.AppendLine("#pragma warning disable SA1121");
  240. sb.AppendLine("#pragma warning disable SA1205");
  241. sb.AppendLine("#pragma warning disable SA1309");
  242. sb.AppendLine("#pragma warning disable SA1402");
  243. sb.AppendLine("#pragma warning disable SA1505");
  244. sb.AppendLine("#pragma warning disable SA1507");
  245. sb.AppendLine("#pragma warning disable SA1508");
  246. sb.AppendLine("#pragma warning disable SA1652");
  247. sb.AppendLine();
  248. sb.AppendLine("using System;");
  249. sb.AppendLine("using System.Collections.Generic;");
  250. sb.AppendLine("using System.Linq;");
  251. sb.AppendLine("using System.Text;");
  252. sb.AppendLine("using System.Numerics;");
  253. sb.AppendLine("using System.Text.Json;");
  254. sb.AppendLine();
  255. sb.AppendLine("using JSONREADER = System.Text.Json.Utf8JsonReader;");
  256. sb.AppendLine("using JSONWRITER = System.Text.Json.Utf8JsonWriter;");
  257. sb.AppendLine("using FIELDINFO = SharpGLTF.Reflection.FieldInfo;");
  258. sb.AppendLine();
  259. string currentNamespace = null;
  260. void _setCurrentNamespace(string ns)
  261. {
  262. if (currentNamespace == ns) return;
  263. if (currentNamespace != null) sb.AppendLine("}");
  264. currentNamespace = ns;
  265. if (currentNamespace != null)
  266. {
  267. sb.AppendLine();
  268. sb.AppendLine($"namespace {currentNamespace}");
  269. sb.AppendLine("{");
  270. sb.AppendLine("using Collections;".Indent(1));
  271. sb.AppendLine();
  272. }
  273. }
  274. foreach (var etype in context.Enumerations)
  275. {
  276. _setCurrentNamespace(GetRuntimeNamespace(etype.PersistentName));
  277. var cout = EmitEnum(etype);
  278. sb.AppendLine(cout);
  279. sb.AppendLine();
  280. }
  281. foreach (var ctype in context.Classes)
  282. {
  283. if (ctype.IgnoredByEmitter) continue;
  284. _setCurrentNamespace(GetRuntimeNamespace(ctype.PersistentName));
  285. var cout = EmitClass(ctype);
  286. sb.AppendLine(cout);
  287. sb.AppendLine();
  288. }
  289. _setCurrentNamespace(null);
  290. return sb.ToString();
  291. }
  292. public string EmitEnum(EnumType type)
  293. {
  294. var sb = new StringBuilder();
  295. foreach (var l in type.Description.EmitSummary(0)) sb.EmitLine(1, l);
  296. sb.EmitLine(1, $"public enum {_GetRuntimeName(type)}");
  297. sb.EmitLine(1, "{");
  298. if (type.UseIntegers)
  299. {
  300. foreach (var kvp in type.Values)
  301. {
  302. var k = kvp.Key;
  303. sb.EmitLine(2, $"{k} = {kvp.Value},");
  304. }
  305. }
  306. else
  307. {
  308. foreach (var kvp in type.Values)
  309. {
  310. var k = kvp.Key;
  311. sb.EmitLine(2, $"{k},");
  312. }
  313. }
  314. sb.EmitLine(1, "}");
  315. return sb.ToString();
  316. }
  317. public string EmitClass(ClassType type)
  318. {
  319. var xclass = new CSharpClassEmitter(this)
  320. {
  321. ClassSummary = type.Description,
  322. SchemaName = type.ShortIdentifier,
  323. ClassDeclaration = _GetClassDeclaration(type),
  324. HasBaseClass = type.BaseClass != null
  325. };
  326. xclass.AddComments(type);
  327. xclass.AddFields(type);
  328. return String.Join("\r\n",xclass.EmitCode().Indent(1));
  329. }
  330. private string _GetClassDeclaration(ClassType type)
  331. {
  332. var classDecl = string.Empty;
  333. classDecl += "partial ";
  334. classDecl += "class ";
  335. classDecl += _GetRuntimeName(type);
  336. if (type.BaseClass != null) classDecl += $" : {_GetRuntimeName(type.BaseClass)}";
  337. return classDecl;
  338. }
  339. internal IEnumerable<string> _EmitClassField(FieldInfo f)
  340. {
  341. if (_FieldsBrowsableState.HasValue)
  342. {
  343. yield return $"[System.Diagnostics.DebuggerBrowsable({_FieldsBrowsableState.Value})]";
  344. }
  345. var tdecl = _GetRuntimeName(f.FieldType, _UseField(f));
  346. var fname = GetFieldRuntimeName(f);
  347. string defval = string.Empty;
  348. if (f.DefaultValue != null)
  349. {
  350. var tconst = _GetConstantRuntimeName(f.FieldType);
  351. var vconst = _GetConstantRuntimeValue(f.FieldType, f.DefaultValue);
  352. // fix boolean value
  353. if (vconst is Boolean bconst) vconst = bconst ? "true" : "false";
  354. defval = $"{fname}Default";
  355. yield return Invariant($"private {tconst} {defval} = {vconst};");
  356. }
  357. if (f.ExclusiveMinimumValue != null)
  358. {
  359. var tconst = _GetConstantRuntimeName(f.FieldType);
  360. var vconst = _GetConstantRuntimeValue(f.FieldType, f.ExclusiveMinimumValue);
  361. yield return Invariant($"private {tconst} {fname}ExclusiveMinimum = {vconst};");
  362. }
  363. if (f.InclusiveMinimumValue != null)
  364. {
  365. var tconst = _GetConstantRuntimeName(f.FieldType);
  366. var vconst = _GetConstantRuntimeValue(f.FieldType, f.InclusiveMinimumValue);
  367. yield return Invariant($"private {tconst} {fname}Minimum = {vconst};");
  368. }
  369. if (f.InclusiveMaximumValue != null)
  370. {
  371. var tconst = _GetConstantRuntimeName(f.FieldType);
  372. var vconst = _GetConstantRuntimeValue(f.FieldType, f.InclusiveMaximumValue);
  373. yield return Invariant($"private {tconst} {fname}Maximum = {vconst};");
  374. }
  375. if (f.ExclusiveMaximumValue != null)
  376. {
  377. var tconst = _GetConstantRuntimeName(f.FieldType);
  378. var vconst = _GetConstantRuntimeValue(f.FieldType, f.ExclusiveMaximumValue);
  379. yield return Invariant($"private {tconst} {fname}ExclusiveMaximum = {vconst};");
  380. }
  381. if (f.MinItems > 0)
  382. {
  383. yield return $"private const int {fname}MinItems = {f.MinItems};";
  384. }
  385. if (f.MaxItems > 0 && f.MaxItems < int.MaxValue)
  386. {
  387. yield return $"private const int {fname}MaxItems = {f.MaxItems};";
  388. }
  389. if (f.FieldType is EnumType etype && etype.IsNullable) tdecl = tdecl + "?";
  390. yield return string.IsNullOrEmpty(defval) ? $"private {tdecl} {fname};" : $"private {tdecl} {fname} = {defval};";
  391. yield return string.Empty;
  392. }
  393. #endregion
  394. }
  395. /// <summary>
  396. /// Utility class to emit a <see cref="SchemaReflection.ClassType"/>
  397. /// as c# source code
  398. /// </summary>
  399. class CSharpClassEmitter
  400. {
  401. #region constructor
  402. public CSharpClassEmitter(CSharpEmitter emitter)
  403. {
  404. _Emitter = emitter;
  405. }
  406. #endregion
  407. #region data
  408. private readonly CSharpEmitter _Emitter;
  409. private readonly List<string> _Comments = new List<string>();
  410. private readonly List<string> _Fields = new List<string>();
  411. private readonly List<string> _SerializerBody = new List<string>();
  412. private readonly List<string> _DeserializerSwitchBody = new List<string>();
  413. private readonly List<string> _FieldsNamesReflection = new List<string>();
  414. private readonly List<string> _FieldsSwitchReflection = new List<string>();
  415. public string ClassSummary { get; set; }
  416. /// <summary>
  417. /// The name used in the schema $id field, minus the prefix and suffix
  418. /// </summary>
  419. public string SchemaName { get; set; }
  420. /// <summary>
  421. /// Represents the Runtime Class Name
  422. /// </summary>
  423. public string ClassDeclaration { get; set; }
  424. public bool HasBaseClass { get; set; }
  425. private const string _READERMODIFIER = "ref ";
  426. #endregion
  427. #region API
  428. public void AddComments(ClassType type)
  429. {
  430. _Comments.AddRange(_Emitter.GetRuntimeComments(type));
  431. }
  432. public void AddFields(ClassType type)
  433. {
  434. foreach (var f in type.Fields)
  435. {
  436. var trname = _Emitter._GetRuntimeName(f.FieldType);
  437. var frname = _Emitter.GetFieldRuntimeName(f);
  438. _Fields.AddRange(_Emitter._EmitClassField(f));
  439. AddFieldReflection(f);
  440. // serialization
  441. if (f.FieldType is EnumType etype) // special case for enums
  442. {
  443. // emit serializer
  444. var smethod = etype.UseIntegers ? "SerializePropertyEnumValue" : "SerializePropertyEnumSymbol";
  445. smethod = $"{smethod}<{trname}>(writer, \"{f.PersistentName}\", {frname}";
  446. if (f.DefaultValue != null) smethod += $", {frname}Default";
  447. smethod += ");";
  448. this.AddFieldSerializerCase(smethod);
  449. // emit deserializer
  450. this.AddFieldDeserializerCase(f.PersistentName, $"{frname} = DeserializePropertyValue<{_Emitter._GetRuntimeName(etype)}>({_READERMODIFIER}reader);");
  451. continue;
  452. }
  453. this.AddFieldSerializerCase(_GetJSonSerializerMethod(f));
  454. this.AddFieldDeserializerCase(f.PersistentName, _GetJSonDeserializerMethod(f));
  455. }
  456. }
  457. private void AddFieldReflection(FieldInfo finfo)
  458. {
  459. var trname = _Emitter._GetRuntimeName(finfo.FieldType);
  460. var frname = _Emitter.GetFieldRuntimeName(finfo);
  461. trname = trname.Replace("?", ""); // since we're adding the default value, there's no need for nullable values.
  462. var vtype = $"typeof({trname})";
  463. var getter = $"instance => instance.{frname}";
  464. if (finfo.DefaultValue != null)
  465. {
  466. var vconst = _Emitter._GetConstantRuntimeValue(finfo.FieldType, finfo.DefaultValue);
  467. // fix boolean value
  468. if (vconst is Boolean bconst) vconst = bconst ? "true" : "false";
  469. getter += Invariant($" ?? {vconst}");
  470. }
  471. // _FieldsReflection.Add($"yield return FIELDINFO.From(\"{finfo.PersistentName}\",this, {getter});");
  472. _FieldsNamesReflection.Add(finfo.PersistentName);
  473. _FieldsSwitchReflection.Add($"case \"{finfo.PersistentName}\": value = FIELDINFO.From(\"{finfo.PersistentName}\",this, {getter}); return true;");
  474. }
  475. private string _GetJSonSerializerMethod(FieldInfo f)
  476. {
  477. var pname = f.PersistentName;
  478. var fname = _Emitter.GetFieldRuntimeName(f);
  479. if (f.FieldType is ClassType ctype)
  480. {
  481. return $"SerializePropertyObject(writer, \"{pname}\", {fname});";
  482. }
  483. if (f.FieldType is ArrayType atype)
  484. {
  485. if (f.MinItems > 0) return $"SerializeProperty(writer, \"{pname}\", {fname}, {fname}MinItems);";
  486. return $"SerializeProperty(writer,\"{pname}\",{fname});";
  487. }
  488. if (f.DefaultValue != null) return $"SerializeProperty(writer, \"{pname}\", {fname}, {fname}Default);";
  489. return $"SerializeProperty(writer, \"{pname}\", {fname});";
  490. }
  491. private string _GetJSonDeserializerMethod(FieldInfo f)
  492. {
  493. var fname = _Emitter.GetFieldRuntimeName(f);
  494. var ownerTypeName = _Emitter._GetRuntimeName(f.DeclaringClass);
  495. if (f.FieldType is ArrayType atype)
  496. {
  497. var titem = _Emitter._GetRuntimeName(atype.ItemType);
  498. return $"DeserializePropertyList<{ownerTypeName}, {titem}>({_READERMODIFIER}reader, this, {fname});";
  499. }
  500. else if (f.FieldType is DictionaryType dtype)
  501. {
  502. var titem = _Emitter._GetRuntimeName(dtype.ValueType);
  503. return $"DeserializePropertyDictionary<{ownerTypeName}, {titem}>({_READERMODIFIER}reader, this, {fname});";
  504. }
  505. var fieldTypeName = _Emitter._GetRuntimeName(f.FieldType);
  506. return $"DeserializePropertyValue<{ownerTypeName}, {fieldTypeName}>({_READERMODIFIER}reader, this, out {fname});";
  507. }
  508. public void AddFieldSerializerCase(string line) { _SerializerBody.Add(line); }
  509. public void AddFieldDeserializerCase(string persistentName, string line)
  510. {
  511. _DeserializerSwitchBody.Add($"case \"{persistentName}\": {line} break;");
  512. }
  513. public IEnumerable<string> EmitCode()
  514. {
  515. #if USENEWTONSOFT
  516. var readerType = "JsonReader";
  517. var writerType = "JsonWriter";
  518. #else
  519. var readerType = "ref JSONREADER";
  520. var writerType = "JSONWRITER";
  521. #endif
  522. foreach (var l in _Comments) yield return $"// {l}";
  523. foreach (var l in ClassSummary.EmitSummary(0)) yield return l;
  524. yield return "#if NET6_0_OR_GREATER";
  525. yield return "[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.NonPublicConstructors | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicConstructors)]";
  526. yield return "#endif";
  527. yield return "[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"SharpGLTF.CodeGen\", \"1.0.0.0\")]";
  528. yield return ClassDeclaration;
  529. yield return "{";
  530. yield return string.Empty;
  531. yield return "#region reflection".Indent(1);
  532. yield return string.Empty;
  533. if (this.HasBaseClass)
  534. {
  535. yield return $"public new const string SCHEMANAME = \"{SchemaName}\";".Indent(1);
  536. }
  537. else
  538. {
  539. yield return $"public const string SCHEMANAME = \"{SchemaName}\";".Indent(1);
  540. }
  541. var pointerPathModifier = HasBaseClass ? "override" : "virtual";
  542. yield return $"protected {pointerPathModifier} string GetSchemaName() => SCHEMANAME;".Indent(1);
  543. yield return string.Empty;
  544. yield return $"protected override IEnumerable<string> ReflectFieldsNames()".Indent(1);
  545. yield return "{".Indent(1);
  546. foreach (var l in _FieldsNamesReflection) yield return $"yield return \"{l}\";".Indent(2);
  547. if (HasBaseClass) yield return "foreach(var f in base.ReflectFieldsNames()) yield return f;".Indent(2);
  548. yield return "}".Indent(1);
  549. yield return $"protected override bool TryReflectField(string name, out FIELDINFO value)".Indent(1);
  550. yield return "{".Indent(1);
  551. yield return "switch(name)".Indent(2);
  552. yield return "{".Indent(2);
  553. foreach (var l in _FieldsSwitchReflection.Indent(3)) yield return l;
  554. if (HasBaseClass) yield return "default: return base.TryReflectField(name, out value);".Indent(3);
  555. yield return "}".Indent(2);
  556. yield return "}".Indent(1);
  557. yield return string.Empty;
  558. yield return "#endregion".Indent(1);
  559. yield return string.Empty;
  560. yield return "#region data".Indent(1);
  561. yield return string.Empty;
  562. foreach (var l in _Fields.Indent(1)) yield return l;
  563. yield return "#endregion".Indent(1);
  564. yield return string.Empty;
  565. yield return "#region serialization".Indent(1);
  566. yield return string.Empty;
  567. // yield return "/// <inheritdoc />".Indent(1);
  568. yield return $"protected override void SerializeProperties({writerType} writer)".Indent(1);
  569. yield return "{".Indent(1);
  570. if (HasBaseClass) yield return "base.SerializeProperties(writer);".Indent(2);
  571. foreach (var l in _SerializerBody.Indent(2)) yield return l;
  572. yield return "}".Indent(1);
  573. yield return string.Empty;
  574. // yield return "/// <inheritdoc />".Indent(1);
  575. yield return $"protected override void DeserializeProperty(string jsonPropertyName, {readerType} reader)".Indent(1);
  576. yield return "{".Indent(1);
  577. yield return "switch (jsonPropertyName)".Indent(2);
  578. yield return "{".Indent(2);
  579. foreach (var l in _DeserializerSwitchBody.Indent(3)) yield return l;
  580. if (HasBaseClass) yield return $"default: base.DeserializeProperty(jsonPropertyName,{_READERMODIFIER}reader); break;".Indent(3);
  581. else yield return "default: throw new NotImplementedException();".Indent(3);
  582. yield return "}".Indent(2);
  583. yield return "}".Indent(1);
  584. yield return string.Empty;
  585. yield return "#endregion".Indent(1);
  586. yield return string.Empty;
  587. yield return "}";
  588. }
  589. #endregion
  590. }
  591. }