Code Reformat

This commit is contained in:
Samuele Lorefice
2025-03-11 19:09:47 +01:00
parent 0fee1f10d2
commit 3756f864ed

View File

@@ -26,8 +26,8 @@ namespace CodeGenerator {
private const string Namespace = "BlendFile";
private static HashSet<string> _customTypes;
private static readonly string[] ListMarkerStr = {"list", "array"};
private static readonly string[] ListLenghtStr = {"num", "len", "size"};
private static readonly string[] ListMarkerStr = { "list", "array" };
private static readonly string[] ListLenghtStr = { "num", "len", "size" };
private static ConcurrentQueue<Tuple<string, LogType>> _logQueue = new();
@@ -39,12 +39,14 @@ namespace CodeGenerator {
private static void LogNow(string message, LogType type = LogType.Info) {
string msg = $"{DateTime.Now:yy-MM-dd HH:mm:ss}|{type.ToString()}|{message}";
lock (Sb){ Sb.AppendLine(msg); }
lock (Sb) {
Sb.AppendLine(msg);
}
Console.WriteLine(msg);
}
private static void Log(string message, LogType type = LogType.Info) {
_logQueue.Enqueue(new (message, type));
_logQueue.Enqueue(new(message, type));
}
public static void Main(string[] args) {
@@ -54,7 +56,8 @@ namespace CodeGenerator {
long start = 0;
bool loggerExit = false;
Thread logger = new(() => {
Thread logger = new(() =>
{
start = sw.ElapsedTicks;
LogNow($"Logger started! In {sw.ElapsedMilliseconds}ms");
// ReSharper disable once AccessToModifiedClosure LoopVariableIsNeverChangedInsideLoop
@@ -90,16 +93,17 @@ namespace CodeGenerator {
Log("Finished generating C# code!");
Log($"""
Timings:
Initialization: {(decimal)initTime/ TimeSpan.TicksPerMillisecond,10:N4} ms
Initialization: {(decimal)initTime / TimeSpan.TicksPerMillisecond,10:N4} ms
Logger Startup: {(decimal)start / TimeSpan.TicksPerMillisecond,10:N4} ms
Reading: {(decimal)readTime/ TimeSpan.TicksPerMillisecond,10:N4} ms
Generating: {(decimal)genTime/ TimeSpan.TicksPerMillisecond,10:N4} ms
Writing: {(decimal)writeTime/ TimeSpan.TicksPerMillisecond,10:N4} ms
Reading: {(decimal)readTime / TimeSpan.TicksPerMillisecond,10:N4} ms
Generating: {(decimal)genTime / TimeSpan.TicksPerMillisecond,10:N4} ms
Writing: {(decimal)writeTime / TimeSpan.TicksPerMillisecond,10:N4} ms
----------------------------
Total: {(decimal)(initTime+readTime+genTime+writeTime) / TimeSpan.TicksPerMillisecond,10:N4} ms
Total: {(decimal)(initTime + readTime + genTime + writeTime) / TimeSpan.TicksPerMillisecond,10:N4} ms
""");
loggerExit = true;
while(logger.IsAlive) { }
while (logger.IsAlive) {
}
Thread.Sleep(1000);
lock (Sb) {
File.AppendAllText("Log.txt", Sb.ToString());
@@ -115,8 +119,7 @@ namespace CodeGenerator {
$"DNA1: {_blendfile.SdnaStructs.Count} structures\n");
}
private static int AddNormalField(DnaField field, ref CodeTypeDeclaration ctd, int index, int totalSize)
{
private static int AddNormalField(DnaField field, ref CodeTypeDeclaration ctd, int index, int totalSize) {
CodeMemberField cmf;
string name = field.Name;
if (name.Contains("()")) return 0;
@@ -161,7 +164,7 @@ namespace CodeGenerator {
private static CodeNamespace GenerateTypes(out CodeNamespace additionalNs) {
//Initialize the namespaces
CodeNamespace rootNs = new CodeNamespace(Namespace);
CodeNamespace ns = new CodeNamespace(Namespace+".DNA");
CodeNamespace ns = new CodeNamespace(Namespace + ".DNA");
//Fill the attribute types then add them to the namespaces
rootNs.Types.AddRange(GenerateTypeDeclarations());
ns.Imports.Add(new(rootNs.Name));
@@ -174,18 +177,17 @@ namespace CodeGenerator {
//Create a new type declaration
var ctd = new CodeTypeDeclaration(type.Type);
ctd.CustomAttributes.Add(new ("DNAClassAttribute",
ctd.CustomAttributes.Add(new("DNAClassAttribute",
new CodeAttributeArgument(new CodePrimitiveExpression(type.IdxType)),
new CodeAttributeArgument(new CodePrimitiveExpression(type.Type))
));
Log($"Generating type from struct {type.Type}");
if(IsClass(type)) {
if (IsClass(type)) {
Log($"Marking {type.Type} as class");
ctd.IsClass = true;
}
else {
} else {
Log($"Marking {type.Type} as struct");
ctd.IsStruct = !ctd.IsClass;
}
@@ -227,14 +229,17 @@ namespace CodeGenerator {
//Retrieve the index of the list length field
int sizeIndex = type.Fields.IndexOf(listLength);
totalSize += AddListField(ref ctd, totalSize, index, listLenghtOffset, listPointer, listLength, sizeIndex);
totalSize += AddListField(ref ctd, totalSize, index, listLenghtOffset, listPointer, listLength,
sizeIndex);
} else if (listFields.Select(f => f.Item2).Contains(field)) {
//update the size of the list attribute
string fName = field.Name.ParseFName();
//retrieve the name of the list pointer
string listPointerName = listFields.First(f => f.Item2.Name.ParseFName() == fName).Item1.Name.ParseFName();
string listPointerName =
listFields.First(f => f.Item2.Name.ParseFName() == fName).Item1.Name.ParseFName();
//Try seeing if the list attribute is already present
var x = ctd.Members.OfType<CodeMemberField>().FirstOrDefault(member => member.Name.ParseFName() == listPointerName);
var x = ctd.Members.OfType<CodeMemberField>()
.FirstOrDefault(member => member.Name.ParseFName() == listPointerName);
if (x != null) //Update the existing list attribute
x.CustomAttributes[0].Arguments[9] = new(new CodePrimitiveExpression(totalSize));
@@ -247,10 +252,10 @@ namespace CodeGenerator {
}
}
ctd.CustomAttributes[0].Arguments.Add(new (new CodePrimitiveExpression(totalSize)));
ctd.CustomAttributes[0].Arguments.Add(new(new CodePrimitiveExpression(totalSize)));
Log("Generating Parameterless constructor");
if(ctd.Members.Count > 0)
if (ctd.Members.Count > 0)
ctd.Members.Add(GenerateParameterlessConstructor(type, ctd));
Log("Generating Default Constructor");
@@ -299,7 +304,6 @@ namespace CodeGenerator {
foreach (var field in dnaFields) {
if (ListMarkerStr.Any(s => field.Name.Contains(s)) &&
!ListLenghtStr.Any(s2 => field.Name.Contains(s2))) {
Log($"Found list field {field.Name}");
Log($"Searching for list length field");
@@ -313,7 +317,7 @@ namespace CodeGenerator {
listFields.Add((field, listLengthField));
//Remove the list length field from the normal fields (if present)
if(normalFields.Remove(listLengthField))
if (normalFields.Remove(listLengthField))
Log($"Removed list length field {listLengthField.Name}");
}
continue;
@@ -340,14 +344,14 @@ namespace CodeGenerator {
var typeDeclarations = new[] {
attributeBuilder.New().SetName("DNAAttribute")
.SetAttributeUsage(new (new CodeSnippetExpression("AttributeTargets.All")))
.SetAttributeUsage(new(new CodeSnippetExpression("AttributeTargets.All")))
.DeriveFromClass()
.AddAutoProperty(typeof(int), "OriginalIndex")
.AddAutoProperty(typeof(string), "OriginalName")
.AddPropertiesConstructor()
.Build(),
attributeBuilder.New().SetName("DNAFieldAttribute")
.SetAttributeUsage(new (new CodeSnippetExpression("AttributeTargets.Field")))
.SetAttributeUsage(new(new CodeSnippetExpression("AttributeTargets.Field")))
.DeriveFromClass($"{Namespace}.DNAAttribute")
.AddAutoProperty(typeof(int), "Size")
.AddAutoProperty(typeof(string), "OriginalType")
@@ -360,7 +364,7 @@ namespace CodeGenerator {
.AddBaseConstructorParams(["OriginalIndex", "OriginalName"])
.Build(),
attributeBuilder.New().SetName("DNAArrayAttribute")
.SetAttributeUsage(new (new CodeSnippetExpression("AttributeTargets.Field")))
.SetAttributeUsage(new(new CodeSnippetExpression("AttributeTargets.Field")))
.DeriveFromClass($"{Namespace}.DNAAttribute")
.AddAutoProperty(typeof(int), "Size")
.AddAutoProperty(typeof(string), "OriginalType")
@@ -373,7 +377,7 @@ namespace CodeGenerator {
.AddBaseConstructorParams(["OriginalIndex", "OriginalName"])
.Build(),
attributeBuilder.New().SetName("DNAClassAttribute")
.SetAttributeUsage(new (new CodeSnippetExpression("AttributeTargets.Class | AttributeTargets.Struct")))
.SetAttributeUsage(new(new CodeSnippetExpression("AttributeTargets.Class | AttributeTargets.Struct")))
.DeriveFromClass($"{Namespace}.DNAAttribute")
.AddAutoProperty(typeof(int), "OriginalIndex")
.AddAutoProperty(typeof(string), "OriginalName")
@@ -382,7 +386,7 @@ namespace CodeGenerator {
.AddBaseConstructorParams(["OriginalIndex", "OriginalName"])
.Build(),
attributeBuilder.New().SetName("DNAListAttribute")
.SetAttributeUsage(new (new CodeSnippetExpression("AttributeTargets.Property | AttributeTargets.Field")))
.SetAttributeUsage(new(new CodeSnippetExpression("AttributeTargets.Property | AttributeTargets.Field")))
.DeriveFromClass($"{Namespace}.DNAAttribute")
.AddAutoProperty(typeof(int), "Size")
.AddAutoProperty(typeof(string), "OriginalType")
@@ -408,8 +412,7 @@ namespace CodeGenerator {
size = body.Lengths[field.IdxType];
string t = field.Type;
if (field.Name.StartsWith('*'))
{
if (field.Name.StartsWith('*')) {
size = 8;
isPointer = true;
}
@@ -438,7 +441,7 @@ namespace CodeGenerator {
var sb = new StringBuilder();
sb.Append(amf.Type.BaseType);
sb.Append('[');
for(int i=1; i<amf.Type.ArrayRank; i++) {
for (int i = 1; i < amf.Type.ArrayRank; i++) {
sb.Append(',');
}
sb.Append(']');
@@ -446,7 +449,7 @@ namespace CodeGenerator {
var dimensions = GetArrayDimensions(field.Name);
int length = 0;
foreach(int dim in dimensions) {
foreach (int dim in dimensions) {
length += dim;
size *= dim;
}
@@ -466,15 +469,14 @@ namespace CodeGenerator {
private static CodeAttributeDeclaration GenerateDnaListAttribute(int listIndex, DnaField listField, int lenghtIndex,
DnaField lenghtField, int ptrOffset, int countOffset, out int size) {
size = 8;
var cad = new CodeAttributeDeclaration("DNAListAttribute");
cad.Arguments.AddRange(new CodeAttributeArgumentCollection() {
new(new CodeSnippetExpression("8")),//pointer size
new(new CodeSnippetExpression("8")), //pointer size
new(new CodePrimitiveExpression(listField.Type)),
new(new CodePrimitiveExpression(listField.Name)),
new(new CodePrimitiveExpression(listIndex)),
new(new CodePrimitiveExpression(listField.Type)),//TODO: double check this
new(new CodePrimitiveExpression(listField.Type)), //TODO: double check this
new(new CodePrimitiveExpression(lenghtField.Type)),
new(new CodePrimitiveExpression(lenghtField.Name)),
new(new CodePrimitiveExpression(lenghtIndex)),
@@ -532,10 +534,12 @@ namespace CodeGenerator {
CodeTypeReference ctr = new(typeof(List<>));
//Check if the type is a built-in type or a custom type
if (t != null) { //Built-in type
if (t != null) {
//Built-in type
ctr.TypeArguments.Add(t);
cmf = new(ctr, field.Name.ParseFName());
} else { //Custom type
} else {
//Custom type
ctr.TypeArguments.Add(new CodeTypeReference(field.Type));
cmf = new(ctr, field.Name.ParseFName());
}
@@ -543,8 +547,7 @@ namespace CodeGenerator {
return cmf;
}
private static List<int> GetArrayDimensions(string name)
{
private static List<int> GetArrayDimensions(string name) {
var dimensions = new List<int>();
int startIndex = 0;
// Get all array dimensions