feat: Source generated Serialization/Deserialization (#550)

### Features
* Fully abstracts serialization by using compile-time attributes.
* Supports serializing the following:
  - Primitives (integers, strings, etc)
  - IP Addresses
  - BigDecimal
  - DateTime, Delta DateTimes
  - TimeSpan
  - Server.Race
  - Server.Map
  - Point2D, Point3D, Rect2D, Rect3D
  - Existing/New `ISerializable` references
  - Lists/Sets of serializable types
  - Type with a `Serialize` method and constructor that takes an `IGenericReader`
* Supports forward-only migration
* Supports existing RunUO deserialization for older versions by changing to the following signature:
  - `public void OldDeserialize(IGenericReader reader, int version)`
  - Must remove deserializing the version since this is already done
* Supports serializing from private fields or custom made properties.
* Types do not require inheriting Item/Mobile. Code gen will fully create `ISerializable` information.
  - This is not recommended yet, since it requires wiring to `Persistence` which will cause lots of unresolved symbol errors until code gen is built.

### Example
```cs
using System.Collections.Generic;

namespace Server.Items
{
    [Serializable(1)]
    public partial class TestItem1 : Item
    {
        [SerializableField(1)]
        [SerializableFieldAttr("[CommandProperty(AccessLevel.Administrator)]")]
        private List<Item> _someProperty;

        private void Deserialize(IGenericReader reader, int version)
        {
        }
    }
}
```

Generates this:
```cs
namespace Server.Items
{
    public partial class TestItem1
    {
#pragma warning disable 0414
        private const int _version = 1;
#pragma warning restore 0414

        [CommandProperty(AccessLevel.Administrator)]
        public System.Collections.Generic.List<Server.Item> SomeProperty
        {
            get => _someProperty;
            set
            {
                if (value != _someProperty)
                {
                    ((ISerializable)this).MarkDirty();
                    _someProperty = value;
                }
            }
        }

        public TestItem1(Serial serial) : base(serial)
        {
        }

        public override void Serialize(IGenericWriter writer)
        {
            var savePosition = ((Server.ISerializable)this).SavePosition;
            if (savePosition > -1)
            {
                writer.Seek(savePosition, System.IO.SeekOrigin.Begin);
                return;
            }
            writer.WriteEncodedInt(_version);
            writer.Write(_someProperty);
        }

        public override void Deserialize(IGenericReader reader)
        {
            var version = reader.ReadEncodedInt();
            if (version < 1)
            {
                OldDeserialize(reader, version);
                ((Server.ISerializable)this).MarkDirty();
                return;
            }
            SomeProperty = reader.ReadEntityList<Server.Item>();
        }
    }
}
```

And this:
```json
{
  "version": 1,
  "type": "TestItem1",
  "properties": [
    {
      "name": "SomeProperty",
      "type": "System.Collections.Generic.List\u003CServer.Item\u003E",
      "rule": "ListMigrationRule",
      "ruleArguments": [
        "Server.Item",
        "SerializableInterfaceMigrationRule"
      ]
    }
  ]
}
```
This commit is contained in:
Kamron Batman 2021-05-23 21:06:23 -07:00 committed by GitHub
parent cb66bef0e5
commit 9afa4e4cab
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
61 changed files with 3203 additions and 142 deletions

View file

@ -0,0 +1,46 @@
/*************************************************************************
* ModernUO *
* Copyright 2019-2021 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: SerializableMigrationRule.cs *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System.Collections.Immutable;
using System.Text;
using Microsoft.CodeAnalysis;
namespace SerializationGenerator
{
public interface ISerializableMigrationRule
{
string RuleName { get; }
bool GenerateRuleState(
Compilation compilation,
ISymbol symbol,
ImmutableArray<AttributeData> attributes,
ImmutableArray<INamedTypeSymbol> serializableTypes,
out string[] ruleArguments
);
void GenerateDeserializationMethod(
StringBuilder source,
string indent,
SerializableProperty property
);
void GenerateSerializationMethod(
StringBuilder source,
string indent,
SerializableProperty property
);
}
}

View file

@ -0,0 +1,121 @@
/*************************************************************************
* ModernUO *
* Copyright 2019-2021 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: ArrayMigrationRule.cs *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Collections.Immutable;
using System.Text;
using Microsoft.CodeAnalysis;
namespace SerializationGenerator
{
public class ArrayMigrationRule : ISerializableMigrationRule
{
public string RuleName => nameof(ArrayMigrationRule);
public bool GenerateRuleState(
Compilation compilation,
ISymbol symbol,
ImmutableArray<AttributeData> attributes,
ImmutableArray<INamedTypeSymbol> serializableTypes,
out string[] ruleArguments
)
{
if (symbol is not IArrayTypeSymbol arrayTypeSymbol)
{
ruleArguments = null;
return false;
}
var serializableArrayType = SerializableMigrationRulesEngine.GenerateSerializableProperty(
compilation,
"ArrayEntry",
arrayTypeSymbol.ElementType,
attributes,
serializableTypes
);
var length = serializableArrayType.RuleArguments.Length;
ruleArguments = new string[length + 2];
ruleArguments[0] = arrayTypeSymbol.ElementType.ToDisplayString();
ruleArguments[1] = serializableArrayType.Rule;
Array.Copy(serializableArrayType.RuleArguments, 0, ruleArguments, 2, length);
return true;
}
public void GenerateDeserializationMethod(StringBuilder source, string indent, SerializableProperty property)
{
const string expectedRule = nameof(ArrayMigrationRule);
var ruleName = property.Rule;
if (expectedRule != ruleName)
{
throw new ArgumentException($"Invalid rule applied to property {ruleName}. Expecting {expectedRule}, but received {ruleName}.");
}
var ruleArguments = property.RuleArguments;
var arrayElementRule = SerializableMigrationRulesEngine.Rules[ruleArguments[1]];
var arrayElementRuleArguments = new string[ruleArguments.Length - 2];
Array.Copy(ruleArguments, 2, arrayElementRuleArguments, 0, ruleArguments.Length - 2);
var propertyIndex = $"{property.Name}Index";
source.AppendLine($"{indent}{property.Name} = new {ruleArguments[0]}[reader.ReadEncodedInt()];");
source.AppendLine($"{indent}for (var {propertyIndex} = 0; {propertyIndex} < {property.Name}.Length; {propertyIndex}++)");
source.AppendLine($"{indent}{{");
var serializableArrayElement = new SerializableProperty
{
Name = $"{property.Name}[{propertyIndex}]",
Type = ruleArguments[0],
Rule = arrayElementRule.RuleName,
RuleArguments = arrayElementRuleArguments
};
arrayElementRule.GenerateDeserializationMethod(source, $"{indent} ", serializableArrayElement);
source.AppendLine($"{indent}}}");
}
public void GenerateSerializationMethod(StringBuilder source, string indent, SerializableProperty property)
{
const string expectedRule = nameof(ArrayMigrationRule);
var ruleName = property.Rule;
if (expectedRule != ruleName)
{
throw new ArgumentException($"Invalid rule applied to property {ruleName}. Expecting {expectedRule}, but received {ruleName}.");
}
var ruleArguments = property.RuleArguments;
var arrayElementRule = SerializableMigrationRulesEngine.Rules[ruleArguments[1]];
var arrayElementRuleArguments = new string[ruleArguments.Length - 2];
Array.Copy(ruleArguments, 2, arrayElementRuleArguments, 0, ruleArguments.Length - 2);
var propertyIndex = $"{property.Name}Index";
source.AppendLine($"{indent}writer.WriteEncodedInt({property.Name}.Length);");
source.AppendLine($"{indent}for (var {propertyIndex} = 0; {propertyIndex} < {property.Name}.Length; {propertyIndex}++)");
source.AppendLine($"{indent}{{");
var serializableArrayElement = new SerializableProperty
{
Name = $"{property.Name}[{propertyIndex}]",
Type = ruleArguments[0],
Rule = arrayElementRule.RuleName,
RuleArguments = arrayElementRuleArguments
};
arrayElementRule.GenerateSerializationMethod(source, $"{indent} ", serializableArrayElement);
source.AppendLine($"{indent}}}");
}
}
}

View file

@ -0,0 +1,134 @@
/*************************************************************************
* ModernUO *
* Copyright 2019-2021 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: HashSetMigrationRule.cs *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Collections.Immutable;
using System.Text;
using Microsoft.CodeAnalysis;
namespace SerializationGenerator
{
public class HashSetMigrationRule : ISerializableMigrationRule
{
public string RuleName => nameof(HashSetMigrationRule);
public bool GenerateRuleState(
Compilation compilation,
ISymbol symbol,
ImmutableArray<AttributeData> attributes,
ImmutableArray<INamedTypeSymbol> serializableTypes,
out string[] ruleArguments
)
{
if (symbol is not INamedTypeSymbol namedTypeSymbol || !symbol.IsHashSet(compilation))
{
ruleArguments = null;
return false;
}
var setTypeSymbol = namedTypeSymbol.TypeArguments[0];
var serializableSetType = SerializableMigrationRulesEngine.GenerateSerializableProperty(
compilation,
"SetEntry",
setTypeSymbol,
attributes,
serializableTypes
);
var length = serializableSetType.RuleArguments.Length;
ruleArguments = new string[length + 2];
ruleArguments[0] = setTypeSymbol.ToDisplayString();
ruleArguments[1] = serializableSetType.Rule;
Array.Copy(serializableSetType.RuleArguments, 0, ruleArguments, 2, length);
return true;
}
public void GenerateDeserializationMethod(StringBuilder source, string indent, SerializableProperty property)
{
const string expectedRule = nameof(HashSetMigrationRule);
var ruleName = property.Rule;
if (expectedRule != ruleName)
{
throw new ArgumentException($"Invalid rule applied to property {ruleName}. Expecting {expectedRule}, but received {ruleName}.");
}
var ruleArguments = property.RuleArguments;
var setElementRule = SerializableMigrationRulesEngine.Rules[ruleArguments[1]];
var setElementRuleArguments = new string[ruleArguments.Length - 2];
Array.Copy(ruleArguments, 2, setElementRuleArguments, 0, ruleArguments.Length - 2);
var propertyName = property.Name;
var propertyVarPrefix = $"{char.ToLower(propertyName[0])}{propertyName.Substring(1, propertyName.Length - 1)}";
var propertyIndex = $"{propertyVarPrefix}Index";
var propertyEntry = $"{propertyVarPrefix}Entry";
var propertyCount = $"{propertyVarPrefix}Count";
source.AppendLine($"{indent}{ruleArguments[0]} {propertyEntry};");
source.AppendLine($"{indent}var {propertyCount} = reader.ReadEncodedInt();");
source.AppendLine($"{indent}{property.Name} = new System.Collections.Generic.HashSet<{ruleArguments[0]}>({propertyCount});");
source.AppendLine($"{indent}for (var {propertyIndex} = 0; i < {propertyCount}; {propertyIndex}++)");
source.AppendLine($"{indent}{{");
var serializableSetElement = new SerializableProperty
{
Name = propertyEntry,
Type = ruleArguments[0],
Rule = setElementRule.RuleName,
RuleArguments = setElementRuleArguments
};
setElementRule.GenerateDeserializationMethod(source, $"{indent} ", serializableSetElement);
source.AppendLine($"{indent} {property.Name}.Add({propertyEntry});");
source.AppendLine($"{indent}}}");
}
public void GenerateSerializationMethod(StringBuilder source, string indent, SerializableProperty property)
{
const string expectedRule = nameof(HashSetMigrationRule);
var ruleName = property.Rule;
if (expectedRule != ruleName)
{
throw new ArgumentException($"Invalid rule applied to property {ruleName}. Expecting {expectedRule}, but received {ruleName}.");
}
var ruleArguments = property.RuleArguments;
var setElementRule = SerializableMigrationRulesEngine.Rules[ruleArguments[1]];
var setElementRuleArguments = new string[ruleArguments.Length - 2];
Array.Copy(ruleArguments, 2, setElementRuleArguments, 0, ruleArguments.Length - 2);
var propertyName = property.Name;
var propertyVarPrefix = $"{char.ToLower(propertyName[0])}{propertyName.Substring(1, propertyName.Length - 1)}";
var propertyEntry = $"{propertyVarPrefix}Entry";
source.AppendLine($"{indent}writer.WriteEncodedInt({property.Name}.Count);");
source.AppendLine($"{indent}foreach (var {propertyEntry} in {property.Name});");
source.AppendLine($"{indent}{{");
var serializableSetElement = new SerializableProperty
{
Name = propertyEntry,
Type = ruleArguments[0],
Rule = setElementRule.RuleName,
RuleArguments = setElementRuleArguments
};
setElementRule.GenerateSerializationMethod(source, $"{indent} ", serializableSetElement);
source.AppendLine($"{indent}}}");
}
}
}

View file

@ -0,0 +1,179 @@
/*************************************************************************
* ModernUO *
* Copyright 2019-2021 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: KeyValuePairMigrationRule.cs *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Collections.Immutable;
using System.Text;
using Microsoft.CodeAnalysis;
namespace SerializationGenerator
{
public class KeyValuePairMigrationRule : ISerializableMigrationRule
{
public string RuleName => nameof(KeyValuePairMigrationRule);
public bool GenerateRuleState(
Compilation compilation,
ISymbol symbol,
ImmutableArray<AttributeData> attributes,
ImmutableArray<INamedTypeSymbol> serializableTypes,
out string[] ruleArguments
)
{
if (symbol is not INamedTypeSymbol namedTypeSymbol || !symbol.IsKeyValuePair(compilation))
{
ruleArguments = null;
return false;
}
var typeArguments = namedTypeSymbol.TypeArguments;
var keySerializedProperty = SerializableMigrationRulesEngine.GenerateSerializableProperty(
compilation,
"key",
typeArguments[0],
attributes,
serializableTypes
);
var valueSerializedProperty = SerializableMigrationRulesEngine.GenerateSerializableProperty(
compilation,
"value",
typeArguments[1],
attributes,
serializableTypes
);
// Key
ruleArguments = new string[5 + keySerializedProperty.RuleArguments.Length + valueSerializedProperty.RuleArguments.Length];
ruleArguments[0] = typeArguments[0].ToDisplayString();
ruleArguments[1] = keySerializedProperty.Rule;
ruleArguments[2] = keySerializedProperty.RuleArguments.Length.ToString();
Array.Copy(keySerializedProperty.RuleArguments, 0, ruleArguments, 2, keySerializedProperty.RuleArguments.Length);
// Value
var valueIndex = 3 + keySerializedProperty.RuleArguments.Length;
ruleArguments[valueIndex++] = typeArguments[1].ToDisplayString();
ruleArguments[valueIndex++] = valueSerializedProperty.Rule;
Array.Copy(valueSerializedProperty.RuleArguments, 0, ruleArguments, valueIndex, valueSerializedProperty.RuleArguments.Length);
return true;
}
public void GenerateDeserializationMethod(StringBuilder source, string indent, SerializableProperty property)
{
const string expectedRule = nameof(KeyValuePairMigrationRule);
var ruleName = property.Rule;
if (expectedRule != ruleName)
{
throw new ArgumentException($"Invalid rule applied to property {ruleName}. Expecting {expectedRule}, but received {ruleName}.");
}
var ruleArguments = property.RuleArguments;
var keyType = ruleArguments[0];
var keyRule = SerializableMigrationRulesEngine.Rules[ruleArguments[1]];
var keyRuleArguments = new string[int.Parse(ruleArguments[2])];
Array.Copy(ruleArguments, 3, keyRuleArguments, 0, keyRuleArguments.Length);
var serializableKeyProperty = new SerializableProperty
{
Name = "key",
Type = keyType,
Rule = keyRule.RuleName,
RuleArguments = keyRuleArguments
};
keyRule.GenerateDeserializationMethod(
source,
indent,
serializableKeyProperty
);
var valueIndex = 3 + keyRuleArguments.Length;
var valueType = ruleArguments[valueIndex++];
var valueRule = SerializableMigrationRulesEngine.Rules[ruleArguments[valueIndex++]];
var valueRuleArguments = new string[ruleArguments.Length - valueIndex];
Array.Copy(ruleArguments, valueIndex, valueRuleArguments, 0, valueRuleArguments.Length);
var serializableValueProperty = new SerializableProperty
{
Name = "value",
Type = valueType,
Rule = valueRule.RuleName,
RuleArguments = valueRuleArguments
};
keyRule.GenerateDeserializationMethod(
source,
indent,
serializableValueProperty
);
source.AppendLine(
$"{indent}{property.Name} = new {SerializableEntityGeneration.KEYVALUEPAIR_STRUCT}<{keyType}, {valueType}>(key, value);"
);
}
public void GenerateSerializationMethod(StringBuilder source, string indent, SerializableProperty property)
{
const string expectedRule = nameof(KeyValuePairMigrationRule);
var ruleName = property.Rule;
if (expectedRule != ruleName)
{
throw new ArgumentException($"Invalid rule applied to property {ruleName}. Expecting {expectedRule}, but received {ruleName}.");
}
var ruleArguments = property.RuleArguments;
var keyType = ruleArguments[0];
var keyRule = SerializableMigrationRulesEngine.Rules[ruleArguments[1]];
var keyRuleArguments = new string[int.Parse(ruleArguments[2])];
Array.Copy(ruleArguments, 3, keyRuleArguments, 0, keyRuleArguments.Length);
var serializableKeyProperty = new SerializableProperty
{
Name = $"{property.Name}.Key",
Type = keyType,
Rule = keyRule.RuleName,
RuleArguments = keyRuleArguments
};
keyRule.GenerateSerializationMethod(
source,
indent,
serializableKeyProperty
);
var valueIndex = 3 + keyRuleArguments.Length;
var valueType = ruleArguments[valueIndex++];
var valueRule = SerializableMigrationRulesEngine.Rules[ruleArguments[valueIndex++]];
var valueRuleArguments = new string[ruleArguments.Length - valueIndex];
Array.Copy(ruleArguments, valueIndex, valueRuleArguments, 0, valueRuleArguments.Length);
var serializableValueProperty = new SerializableProperty
{
Name = $"{property.Name}.Value",
Type = valueType,
Rule = valueRule.RuleName,
RuleArguments = valueRuleArguments
};
keyRule.GenerateSerializationMethod(
source,
indent,
serializableValueProperty
);
}
}
}

View file

@ -0,0 +1,133 @@
/*************************************************************************
* ModernUO *
* Copyright 2019-2021 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: ListMigrationRule.cs *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Collections.Immutable;
using System.Text;
using Microsoft.CodeAnalysis;
namespace SerializationGenerator
{
public class ListMigrationRule : ISerializableMigrationRule
{
public string RuleName => nameof(ListMigrationRule);
public bool GenerateRuleState(
Compilation compilation,
ISymbol symbol,
ImmutableArray<AttributeData> attributes,
ImmutableArray<INamedTypeSymbol> serializableTypes,
out string[] ruleArguments
)
{
if (symbol is not INamedTypeSymbol namedTypeSymbol || !symbol.IsList(compilation))
{
ruleArguments = null;
return false;
}
var listTypeSymbol = namedTypeSymbol.TypeArguments[0];
var serializableListType = SerializableMigrationRulesEngine.GenerateSerializableProperty(
compilation,
"ListEntry",
listTypeSymbol,
attributes,
serializableTypes
);
var length = serializableListType.RuleArguments.Length;
ruleArguments = new string[length + 2];
ruleArguments[0] = listTypeSymbol.ToDisplayString();
ruleArguments[1] = serializableListType.Rule;
Array.Copy(serializableListType.RuleArguments, 0, ruleArguments, 2, length);
return true;
}
public void GenerateDeserializationMethod(StringBuilder source, string indent, SerializableProperty property)
{
const string expectedRule = nameof(ListMigrationRule);
var ruleName = property.Rule;
if (expectedRule != ruleName)
{
throw new ArgumentException($"Invalid rule applied to property {ruleName}. Expecting {expectedRule}, but received {ruleName}.");
}
var ruleArguments = property.RuleArguments;
var listElementRule = SerializableMigrationRulesEngine.Rules[ruleArguments[1]];
var listElementRuleArguments = new string[ruleArguments.Length - 2];
Array.Copy(ruleArguments, 2, listElementRuleArguments, 0, ruleArguments.Length - 2);
var propertyName = property.Name;
var propertyVarPrefix = $"{char.ToLower(propertyName[0])}{propertyName.Substring(1, propertyName.Length - 1)}";
var propertyIndex = $"{propertyVarPrefix}Index";
var propertyEntry = $"{propertyVarPrefix}Entry";
var propertyCount = $"{propertyVarPrefix}Count";
source.AppendLine($"{indent}{ruleArguments[0]} {propertyEntry};");
source.AppendLine($"{indent}var {propertyCount} = reader.ReadEncodedInt();");
source.AppendLine($"{indent}{propertyName} = new System.Collections.Generic.List<{ruleArguments[0]}>({propertyCount});");
source.AppendLine($"{indent}for (var {propertyIndex} = 0; {propertyIndex} < {propertyCount}; {propertyIndex}++)");
source.AppendLine($"{indent}{{");
var serializableListElement = new SerializableProperty
{
Name = propertyEntry,
Type = ruleArguments[0],
Rule = listElementRule.RuleName,
RuleArguments = listElementRuleArguments
};
listElementRule.GenerateDeserializationMethod(source, $"{indent} ", serializableListElement);
source.AppendLine($"{indent} {propertyName}.Add({propertyEntry});");
source.AppendLine($"{indent}}}");
}
public void GenerateSerializationMethod(StringBuilder source, string indent, SerializableProperty property)
{
const string expectedRule = nameof(ListMigrationRule);
var ruleName = property.Rule;
if (expectedRule != ruleName)
{
throw new ArgumentException($"Invalid rule applied to property {ruleName}. Expecting {expectedRule}, but received {ruleName}.");
}
var ruleArguments = property.RuleArguments;
var listElementRule = SerializableMigrationRulesEngine.Rules[ruleArguments[1]];
var listElementRuleArguments = new string[ruleArguments.Length - 2];
Array.Copy(ruleArguments, 2, listElementRuleArguments, 0, ruleArguments.Length - 2);
var propertyName = property.Name;
var propertyEntry = $"{char.ToLower(propertyName[0])}{propertyName.Substring(1, propertyName.Length - 1)}Entry";
source.AppendLine($"{indent}writer.WriteEncodedInt({propertyName}.Count);");
source.AppendLine($"{indent}foreach (var {propertyEntry} in {propertyName})");
source.AppendLine($"{indent}{{");
var serializableListElement = new SerializableProperty
{
Name = propertyEntry,
Type = ruleArguments[0],
Rule = listElementRule.RuleName,
RuleArguments = listElementRuleArguments
};
listElementRule.GenerateSerializationMethod(source, $"{indent} ", serializableListElement);
source.AppendLine($"{indent}}}");
}
}
}

View file

@ -0,0 +1,159 @@
/*************************************************************************
* ModernUO *
* Copyright 2019-2021 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: PrimitiveTypeMigrationRule.cs *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis;
namespace SerializationGenerator
{
public class PrimitiveTypeMigrationRule : ISerializableMigrationRule
{
public string RuleName => nameof(PrimitiveTypeMigrationRule);
public bool GenerateRuleState(
Compilation compilation,
ISymbol symbol,
ImmutableArray<AttributeData> attributes,
ImmutableArray<INamedTypeSymbol> serializableTypes,
out string[] ruleArguments
)
{
if (symbol.IsIpAddress(compilation))
{
ruleArguments = new[] { "IPAddress" };
return true;
}
if (symbol is not ITypeSymbol typeSymbol)
{
ruleArguments = null;
return false;
}
if (
typeSymbol.SpecialType is
SpecialType.System_Boolean or
SpecialType.System_SByte or
SpecialType.System_Int16 or
SpecialType.System_Int32 or
SpecialType.System_Int64 or
SpecialType.System_Byte or
SpecialType.System_UInt16 or
SpecialType.System_UInt32 or
SpecialType.System_UInt64 or
SpecialType.System_Single or
SpecialType.System_Double or
SpecialType.System_String or
SpecialType.System_Decimal or
SpecialType.System_DateTime
)
{
ruleArguments = new[] { typeSymbol.SpecialType.ToString() };
return true;
}
if (typeSymbol.SpecialType == SpecialType.System_DateTime)
{
ruleArguments = attributes.Any(a => a.IsDeltaDateTime(compilation))
? new[] { typeSymbol.SpecialType.ToString(), "DeltaTime" }
: new[] { typeSymbol.SpecialType.ToString() };
return true;
}
ruleArguments = null;
return false;
}
public void GenerateDeserializationMethod(StringBuilder source, string indent, SerializableProperty property)
{
const string expectedRule = nameof(PrimitiveTypeMigrationRule);
var ruleName = property.Rule;
if (expectedRule != ruleName)
{
throw new ArgumentException($"Invalid rule applied to property {ruleName}. Expecting {expectedRule}, but received {ruleName}.");
}
var propertyName = property.Name;
var ruleType = property.RuleArguments[0];
string readMethod;
if (ruleType == "IPAddress")
{
readMethod = "ReadIPAddress";
}
else
{
if (!Enum.TryParse<SpecialType>(ruleType, out var specialType))
{
throw new ArgumentException($"Invalid rule state for property {propertyName} ({ruleType})");
}
readMethod = specialType switch
{
SpecialType.System_Boolean => "ReadBool",
SpecialType.System_SByte => "ReadSByte",
SpecialType.System_Int16 => "ReadShort",
SpecialType.System_Int32 => "ReadInt",
SpecialType.System_Int64 => "ReadLong",
SpecialType.System_Byte => "ReadByte",
SpecialType.System_UInt16 => "ReadUShort",
SpecialType.System_UInt32 => "ReadUInt",
SpecialType.System_UInt64 => "ReadULong",
SpecialType.System_Single => "ReadFloat",
SpecialType.System_Double => "ReadDouble",
SpecialType.System_String => "ReadString",
SpecialType.System_Decimal => "ReadDecimal",
SpecialType.System_DateTime => property.RuleArguments.Length >= 2 &&
property.RuleArguments[1] == "DeltaTime" ?
"ReadDeltaTime" :
"ReadDateTime"
};
}
source.AppendLine($"{indent}{propertyName} = reader.{readMethod}()");
}
public void GenerateSerializationMethod(StringBuilder source, string indent, SerializableProperty property)
{
const string expectedRule = nameof(PrimitiveTypeMigrationRule);
var ruleName = property.Rule;
if (expectedRule != ruleName)
{
throw new ArgumentException($"Invalid rule applied to property {ruleName}. Expecting {expectedRule}, but received {ruleName}.");
}
var propertyName = property.Name;
var ruleType = property.RuleArguments[0];
if (!Enum.TryParse<SpecialType>(ruleType, out var specialType))
{
throw new ArgumentException($"Invalid rule state for property {propertyName} ({ruleType})");
}
if (specialType == SpecialType.System_DateTime && property.RuleArguments[1] == "DeltaTime")
{
source.AppendLine($"{indent}writer.WriteDeltaTime({propertyName});");
}
else
{
source.AppendLine($"{indent}writer.Write({propertyName});");
}
}
}
}

View file

@ -0,0 +1,75 @@
/*************************************************************************
* ModernUO *
* Copyright 2019-2021 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: PrimitiveUOTypeMigrationRule.cs *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Collections.Immutable;
using System.Text;
using Microsoft.CodeAnalysis;
namespace SerializationGenerator
{
public class PrimitiveUOTypeMigrationRule : ISerializableMigrationRule
{
public string RuleName => nameof(PrimitiveUOTypeMigrationRule);
public bool GenerateRuleState(
Compilation compilation,
ISymbol symbol,
ImmutableArray<AttributeData> attributes,
ImmutableArray<INamedTypeSymbol> serializableTypes,
out string[] ruleArguments
)
{
ruleArguments = symbol switch
{
_ when symbol.IsPoint2D(compilation) => new[] { "Point2D" },
_ when symbol.IsPoint3D(compilation) => new[] { "Point3D" },
_ when symbol.IsRectangle2D(compilation) => new[] { "Rect2D" },
_ when symbol.IsRectangle3D(compilation) => new[] { "Rect3D" },
_ when symbol.IsRace(compilation) => new[] { "Race" },
_ when symbol.IsMap(compilation) => new[] { "Map" },
_ => null
};
return ruleArguments != null;
}
public void GenerateDeserializationMethod(StringBuilder source, string indent, SerializableProperty property)
{
const string expectedRule = nameof(PrimitiveUOTypeMigrationRule);
var ruleName = property.Rule;
if (expectedRule != ruleName)
{
throw new ArgumentException($"Invalid rule applied to property {ruleName}. Expecting {expectedRule}, but received {ruleName}.");
}
var propertyName = property.Name;
source.AppendLine($"{indent}{propertyName} = reader.Read{property.RuleArguments[0]}()");
}
public void GenerateSerializationMethod(StringBuilder source, string indent, SerializableProperty property)
{
const string expectedRule = nameof(PrimitiveUOTypeMigrationRule);
var ruleName = property.Rule;
if (expectedRule != ruleName)
{
throw new ArgumentException($"Invalid rule applied to property {ruleName}. Expecting {expectedRule}, but received {ruleName}.");
}
var propertyName = property.Name;
source.AppendLine($"{indent}writer.Write({propertyName});");
}
}
}

View file

@ -0,0 +1,71 @@
/*************************************************************************
* ModernUO *
* Copyright 2019-2021 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: SerializableInterfaceMigrationRule.cs *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Collections.Immutable;
using System.Text;
using Microsoft.CodeAnalysis;
namespace SerializationGenerator
{
public class SerializableInterfaceMigrationRule : ISerializableMigrationRule
{
public string RuleName => nameof(SerializableInterfaceMigrationRule);
public bool GenerateRuleState(
Compilation compilation,
ISymbol symbol,
ImmutableArray<AttributeData> attributes,
ImmutableArray<INamedTypeSymbol> serializableTypes,
out string[] ruleArguments
)
{
if (symbol is ITypeSymbol typeSymbol && typeSymbol.HasSerializableInterface(compilation, serializableTypes))
{
ruleArguments = Array.Empty<string>();
return true;
}
ruleArguments = null;
return false;
}
public void GenerateDeserializationMethod(StringBuilder source, string indent, SerializableProperty property)
{
const string expectedRule = nameof(SerializableInterfaceMigrationRule);
var ruleName = property.Rule;
if (expectedRule != ruleName)
{
throw new ArgumentException($"Invalid rule applied to property {ruleName}. Expecting {expectedRule}, but received {ruleName}.");
}
var propertyName = property.Name;
source.AppendLine($"{indent}{propertyName} = reader.ReadEntity<{property.Type}>();");
}
public void GenerateSerializationMethod(StringBuilder source, string indent, SerializableProperty property)
{
const string expectedRule = nameof(SerializableInterfaceMigrationRule);
var ruleName = property.Rule;
if (expectedRule != ruleName)
{
throw new ArgumentException($"Invalid rule applied to property {ruleName}. Expecting {expectedRule}, but received {ruleName}.");
}
var propertyName = property.Name;
source.AppendLine($"{indent}writer.Write({propertyName});");
}
}
}

View file

@ -0,0 +1,81 @@
/*************************************************************************
* ModernUO *
* Copyright 2019-2021 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: SerializationMethodSignatureMigrationRule.cs *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Collections.Immutable;
using System.Text;
using Microsoft.CodeAnalysis;
namespace SerializationGenerator
{
public class SerializationMethodSignatureMigrationRule : ISerializableMigrationRule
{
public string RuleName => nameof(SerializationMethodSignatureMigrationRule);
public bool GenerateRuleState(
Compilation compilation,
ISymbol symbol,
ImmutableArray<AttributeData> attributes,
ImmutableArray<INamedTypeSymbol> serializableTypes,
out string[] ruleArguments
)
{
if ((symbol as ITypeSymbol)?.HasPublicSerializeMethod(compilation, serializableTypes) != true)
{
ruleArguments = null;
return false;
}
if (symbol is not INamedTypeSymbol namedTypeSymbol ||
!namedTypeSymbol.HasGenericReaderCtor(compilation, out var requiresParent))
{
ruleArguments = null;
return false;
}
ruleArguments = requiresParent ? new[] { "DeserializationRequiresParent" } : Array.Empty<string>();
return true;
}
public void GenerateDeserializationMethod(StringBuilder source, string indent, SerializableProperty property)
{
const string expectedRule = nameof(SerializationMethodSignatureMigrationRule);
var ruleName = property.Rule;
if (expectedRule != ruleName)
{
throw new ArgumentException($"Invalid rule applied to property {ruleName}. Expecting {expectedRule}, but received {ruleName}.");
}
var propertyName = property.Name;
var argument = property.RuleArguments.Length >= 1 &&
property.RuleArguments[0] == "DeserializationRequiresParent" ? ", this" : "";
source.AppendLine($"{indent}{propertyName} = new {property.Type}(reader{argument})");
}
public void GenerateSerializationMethod(StringBuilder source, string indent, SerializableProperty property)
{
const string expectedRule = nameof(SerializationMethodSignatureMigrationRule);
var ruleName = property.Rule;
if (expectedRule != ruleName)
{
throw new ArgumentException($"Invalid rule applied to property {ruleName}. Expecting {expectedRule}, but received {ruleName}.");
}
var propertyName = property.Name;
source.AppendLine($"{indent}{propertyName}.Serialize(writer);");
}
}
}

View file

@ -0,0 +1,32 @@
/*************************************************************************
* ModernUO *
* Copyright 2019-2021 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: SerializableMigration.cs *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System.Collections.Generic;
using System.Text.Json.Serialization;
namespace SerializationGenerator
{
public class SerializableMetadata
{
[JsonPropertyName("version")]
public int Version { get; set; }
[JsonPropertyName("type")]
public string Type { get; set; }
[JsonPropertyName("properties")]
public List<SerializableProperty> Properties { get; set; }
}
}

View file

@ -0,0 +1,27 @@
using System.Collections.Generic;
namespace SerializationGenerator
{
public class SerializableMetadataComparer : IComparer<SerializableMetadata>
{
public int Compare(SerializableMetadata x, SerializableMetadata y)
{
if (ReferenceEquals(x, y))
{
return 0;
}
if (ReferenceEquals(null, y))
{
return 1;
}
if (ReferenceEquals(null, x))
{
return -1;
}
return x.Version.CompareTo(y.Version);
}
}
}

View file

@ -0,0 +1,53 @@
/*************************************************************************
* ModernUO *
* Copyright 2019-2021 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: SerializableMigration.ContentStruct.cs *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System.Text;
namespace SerializationGenerator
{
public static partial class SerializableMigration
{
public static void GenerateMigrationContentStruct(
this StringBuilder source,
SerializableMetadata migration
)
{
const string indent = " ";
source.AppendLine($"{indent}ref struct V{migration.Version}Content");
source.AppendLine($"{indent}{{");
foreach (var serializableProperty in migration.Properties)
{
source.AppendLine($"{indent} internal readonly {serializableProperty.Type} {serializableProperty.Name};");
}
source.AppendLine($"{indent} internal V{migration.Version}Content(IGenericReader reader)");
source.AppendLine($"{indent} {{");
foreach (var serializableProperty in migration.Properties)
{
SerializableMigrationRulesEngine.Rules[serializableProperty.Rule].GenerateDeserializationMethod(
source,
$"{indent} ",
serializableProperty
);
}
source.AppendLine($"{indent} }}");
source.AppendLine($"{indent}}}");
}
}
}

View file

@ -0,0 +1,78 @@
/*************************************************************************
* ModernUO *
* Copyright 2019-2021 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: SerializableMigration.cs *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using Microsoft.CodeAnalysis;
namespace SerializationGenerator
{
public static partial class SerializableMigration
{
public static JsonSerializerOptions GetJsonSerializerOptions(Compilation compilation) =>
new()
{
WriteIndented = true,
AllowTrailingCommas = true,
IgnoreNullValues = true,
ReadCommentHandling = JsonCommentHandling.Skip
};
public static string GetMigrationPath(GeneratorExecutionContext context)
{
context.AnalyzerConfigOptions.GlobalOptions.TryGetValue(
"build_property.SerializableMigrationPath",
out var migrationPath
);
return migrationPath;
}
public static List<SerializableMetadata> GetMigrations(
string migrationPath,
INamedTypeSymbol typeSymbol,
int version,
JsonSerializerOptions options
)
{
var typeName = typeSymbol.ToDisplayString();
var migrations = new SortedSet<SerializableMetadata>(new SerializableMetadataComparer());
var migrationFiles = Directory.GetFiles(migrationPath, $"{typeName}.v*.json");
foreach (var migrationFile in migrationFiles)
{
var text = File.ReadAllText(migrationFile, Encoding.UTF8);
var migration = JsonSerializer.Deserialize<SerializableMetadata>(text, options);
if (typeName == migration!.Type && version > migration.Version)
{
migrations.Add(migration);
}
}
return migrations.ToList();
}
public static void WriteMigration(string migrationPath, SerializableMetadata metadata, JsonSerializerOptions options)
{
Directory.CreateDirectory(migrationPath);
var filePath = Path.Combine(migrationPath, $"{metadata.Type}.v{metadata.Version}.json");
File.WriteAllText(filePath, JsonSerializer.Serialize(metadata, options));
}
}
}

View file

@ -0,0 +1,78 @@
/*************************************************************************
* ModernUO *
* Copyright 2019-2021 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: SerializableMigrationRulesEngine.cs *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
namespace SerializationGenerator
{
public static class SerializableMigrationRulesEngine
{
public static readonly Dictionary<string, ISerializableMigrationRule> Rules = new();
static SerializableMigrationRulesEngine()
{
var rules = new ISerializableMigrationRule[]
{
new ArrayMigrationRule(),
new HashSetMigrationRule(),
new KeyValuePairMigrationRule(),
new ListMigrationRule(),
new PrimitiveTypeMigrationRule(),
new PrimitiveUOTypeMigrationRule(),
new SerializableInterfaceMigrationRule(),
new SerializationMethodSignatureMigrationRule()
};
foreach (var rule in rules)
{
Rules.Add(rule.RuleName, rule);
}
}
public static SerializableProperty GenerateSerializableProperty(
Compilation compilation,
string propertyName,
ISymbol propertyType,
ImmutableArray<AttributeData> attributes,
ImmutableArray<INamedTypeSymbol> serializableTypes
)
{
foreach (var rule in Rules.Values)
{
if (rule.GenerateRuleState(
compilation,
propertyType,
attributes,
serializableTypes,
out var ruleArguments
))
{
return new SerializableProperty
{
Name = propertyName,
Type = propertyType.ToDisplayString(),
Rule = rule.RuleName,
RuleArguments = ruleArguments
};
}
}
throw new Exception($"No rule found for property {propertyName} of type {propertyType} ({Rules.Count})");
}
}
}

View file

@ -0,0 +1,34 @@
/*************************************************************************
* ModernUO *
* Copyright 2019-2021 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: SerializableProperty.cs *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System.Text.Json.Serialization;
namespace SerializationGenerator
{
public class SerializableProperty
{
[JsonPropertyName("name")]
public string Name { get; init; }
[JsonPropertyName("type")]
public string Type { get; init; }
[JsonPropertyName("rule")]
public string Rule { get; init; }
[JsonPropertyName("ruleArguments")]
public string[] RuleArguments { get; init; }
}
}