Skip to content

Commit 5d753da

Browse files
authored
fix codegen of getter and setter of property (#19)
* fix codegen of getter and setter of property * set package versions
1 parent ac0042b commit 5d753da

File tree

9 files changed

+72
-37
lines changed

9 files changed

+72
-37
lines changed

Assets/Samples/TestAnySerialize.cs

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ public class TestAnySerialize : MonoBehaviour
3131
[AnySerialize] public Lazy<Dictionary<int, long[]>> LazyDictIntLongArray { get; }
3232

3333
#pragma warning disable UNT0001
34-
34+
3535
private void Awake()
3636
{
3737
Debug.Log($"{nameof(IntValue)} = {IntValue}");
@@ -42,6 +42,16 @@ private void Awake()
4242
Debug.Log($"{nameof(DictionaryStringInt)} = {string.Join(",", DictionaryStringInt.Select(t => $"{t.Key}=>{t.Value}"))}");
4343
Debug.Log($"{nameof(DictionaryStringDict)} = {string.Join(",", DictionaryStringDict.Select(t => $"{t.Key}=>({string.Join(",", t.Value.Select(x => $"{x.Key}=>{x.Value}"))})"))}");
4444
Debug.Log($"{nameof(AnyStringArray2)} = {string.Join(",", AnyStringArray2.SelectMany(arr => arr))}");
45+
Debug.Log($"{nameof(AnyIntArray3)} = {string.Join(",", AnyIntArray3.SelectMany(arr2 => arr2).SelectMany(arr => arr))}");
46+
Debug.Log($"{nameof(AnyClassArray)} = {string.Join(",", AnyClassArray.Select(a => a.ToString()))}");
47+
Debug.Log($"{nameof(A)} = {A}");
48+
Debug.Log($"{nameof(B)} = {B}");
49+
Debug.Log($"{nameof(BB)} = {BB}");
50+
Debug.Log($"{nameof(Vector2)} = {Vector2}");
51+
Debug.Log($"{nameof(Record)} = {Record}");
52+
Debug.Log($"{nameof(LazyInt)} = {LazyInt.Value}");
53+
Debug.Log($"{nameof(LazyIntArray)} = {string.Join(",", LazyIntArray.Value)}");
54+
Debug.Log($"{nameof(LazyDictIntLongArray)} = {LazyDictIntLongArray.Value}");
4555
}
4656

4757
#pragma warning restore UNT0001
@@ -56,6 +66,11 @@ public class A
5666
public int Int;
5767
// [AnySerialize] public string[][] StringArray { get; }
5868
public float Float;
69+
70+
public override string ToString()
71+
{
72+
return $"{{ {nameof(Int)} = {Int}, {nameof(Float)} = {Float} }}";
73+
}
5974
}
6075

6176
[Serializable]
@@ -65,11 +80,21 @@ public class B<T> : IB<T>
6580
public T[] TArray;
6681
public T[][] TArrayArray;
6782
public float ReadOnlyProperty { get; }
83+
84+
public override string ToString()
85+
{
86+
return $"{{ {nameof(ReadOnlyProperty)} = {ReadOnlyProperty}, {nameof(ReadOnlyTValue)} = {ReadOnlyTValue}, {nameof(TArray)} = {string.Join(",", TArray)}, {nameof(TArrayArray)} = {string.Join(",", TArrayArray.SelectMany(arr => arr))} }}";
87+
}
6888
}
6989

7090
[Serializable]
7191
public record R
7292
{
7393
public int Int { get; } = 123;
94+
95+
public override string ToString()
96+
{
97+
return $"{{ {nameof(Int)} = {Int} }}";
98+
}
7499
}
75100
}

Packages/com.quabug.any-processor/CodeGen/Extension/Extensions.cs

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -48,18 +48,26 @@ public static TypeReference CreateGenericTypeReference(this TypeDefinition type,
4848
.SelectMany(t => t.Resolve()!.Methods.Select(m => (type, method: m)))
4949
.FirstOrDefault(t => t.method!.Name == methodName)
5050
;
51-
logger?.Info($"{declaringType.FullName}({declaringType.HasGenericParameters})");
51+
logger?.Debug($"[{nameof(GetMethodReference)}] {declaringType}: {method}@{method.DeclaringType}");
5252
if (method == null) return null;
5353

5454
var methodReference = declaringType.Module!.ImportReference(method);
55-
if (!declaringType.IsGenericInstance) return methodReference;
56-
var parameters = ((GenericInstanceType)declaringType).GenericArguments;
57-
logger?.Info($"{declaringType.FullName}({declaringType.HasGenericParameters}): {string.Join(",", parameters.Select(p => p.Name))}");
58-
return methodReference!.CreateGenericMethodReference(parameters.ToArray()!);
55+
if (methodReference.DeclaringType.IsConcreteType()) return methodReference;
56+
57+
while (!methodReference.DeclaringType.Resolve().TypeEquals(declaringType.Resolve()))
58+
{
59+
logger?.Debug($"[{nameof(GetMethodReference)}] find {method.DeclaringType} {declaringType.Resolve()}:{declaringType.Resolve()!.BaseType}");
60+
declaringType = declaringType.Resolve()!.BaseType;
61+
}
62+
63+
var parameters = ((GenericInstanceType)declaringType).GenericArguments.Select(argument => type.Module!.ImportReference(argument));
64+
logger?.Debug($"[{nameof(GetMethodReference)}] {declaringType}<{string.Join(",", parameters.Select(p => p.Name))}>");
65+
return methodReference.CreateGenericMethodReference(parameters.ToArray(), logger);
5966
}
6067

61-
public static MethodReference CreateGenericMethodReference(this MethodReference method, TypeReference[] genericArguments)
68+
public static MethodReference CreateGenericMethodReference(this MethodReference method, TypeReference[] genericArguments, ILPostProcessorLogger? logger = null)
6269
{
70+
logger?.Debug($"[{nameof(CreateGenericMethodReference)}] {method.Name}: {method.DeclaringType}");
6371
var reference = new MethodReference(method.Name!, method.ReturnType!) {
6472
DeclaringType = method.DeclaringType!.MakeGenericInstanceType(genericArguments),
6573
HasThis = method.HasThis,
@@ -171,13 +179,13 @@ public static FieldDefinition CreateOrReplaceBackingField(this PropertyDefinitio
171179
{
172180
var backingFieldName = property.GetBackingFieldName();
173181
var backingField = property.DeclaringType!.Fields!.FirstOrDefault(field => field.Name == backingFieldName)
174-
?? property.CreateSerializeReferenceField(fieldType);
182+
?? property.CreateBackingField(fieldType);
175183
backingField.FieldType = fieldType;
176184
backingField.IsInitOnly = false;
177185
return backingField;
178186
}
179187

180-
public static FieldDefinition CreateSerializeReferenceField(this PropertyDefinition property, TypeReference fieldType)
188+
public static FieldDefinition CreateBackingField(this PropertyDefinition property, TypeReference fieldType)
181189
{
182190
//.field private class AnySerialize.Tests.TestMonoBehavior/__generic_serialize_reference_GenericInterface__/IBase _GenericInterface
183191
// .custom instance void [UnityEngine.CoreModule]UnityEngine.SerializeReference::.ctor()
@@ -191,7 +199,7 @@ public static FieldDefinition CreateSerializeReferenceField(this PropertyDefinit
191199
return serializedField;
192200
}
193201

194-
public static void ReplacePropertyGetterByFieldMethod(this PropertyDefinition property, FieldDefinition serializedField, string fieldMethodName)
202+
public static void ReplacePropertyGetterByFieldMethod(this PropertyDefinition property, FieldDefinition serializedField, string fieldMethodName, ILPostProcessorLogger? logger = null)
195203
{
196204
// before
197205
// IL_0000: ldarg.0 // this
@@ -204,7 +212,7 @@ public static void ReplacePropertyGetterByFieldMethod(this PropertyDefinition pr
204212
// IL_0006: callvirt instance !0/*object*/ class [AnySerialize]AnySerialize.AnyValue`1<object>::get_Value()
205213
// IL_000b: ret
206214
var instructions = property.GetMethod!.Body!.Instructions;
207-
var getValueMethod = serializedField.FieldType!.GetMethodReference(fieldMethodName);
215+
var getValueMethod = serializedField.FieldType!.GetMethodReference(fieldMethodName, logger);
208216
getValueMethod = property.Module!.ImportReference(getValueMethod!);
209217
instructions!.Clear();
210218
instructions.Add(Instruction.Create(OpCodes.Ldarg_0));

Packages/com.quabug.any-processor/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "com.quabug.any-processor",
3-
"version": "0.2.0",
3+
"version": "0.1.0",
44
"unity": "2021.3",
55
"displayName": "AnyProcessor",
66
"type": "library",

Packages/com.quabug.any-serialize/CodeGen/AnySerializePostProcessor.cs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using System.Linq;
22
using AnyProcessor.CodeGen;
3+
using JetBrains.Annotations;
34
using Mono.Cecil;
45
using Mono.Cecil.Rocks;
56
using OneShot;
@@ -10,6 +11,7 @@
1011

1112
namespace AnySerialize.CodeGen
1213
{
14+
[UsedImplicitly]
1315
public class AnySerializePostProcessor : ILPostProcessor
1416
{
1517
public override ILPostProcessor GetInstance()
@@ -58,12 +60,12 @@ void GenerateField(PropertyDefinition property, CustomAttribute attribute)
5860
attribute,
5961
(propertyType, typeof(TargetLabel<>))
6062
);
61-
processor.Logger.Debug($"field type: {fieldType?.FullName}");
63+
processor.Logger.Debug($"field type: {fieldType.FullName}");
6264
fieldType = processor.Module.ImportReference(fieldType);
6365
var serializedField = property.CreateOrReplaceBackingField(fieldType);
6466
serializedField.AddCustomAttribute<SerializeField>(property.Module);
6567
processor.Logger.Info($"serialize field type: {serializedField.FullName}");
66-
property.ReplacePropertyGetterByFieldMethod(serializedField, "get_Value");
68+
property.ReplacePropertyGetterByFieldMethod(serializedField, "get_Value", processor.Logger);
6769
if (property.SetMethod != null) property.ReplacePropertySetterByFieldMethod(serializedField, "set_Value");
6870

6971
TypeReference CreatePropertyType()

Packages/com.quabug.any-serialize/CodeGen/ITypeSearcher.cs

Lines changed: 18 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,14 @@
22
using System.Collections.Generic;
33
using System.Linq;
44
using AnyProcessor.CodeGen;
5-
using JetBrains.Annotations;
65
using Mono.Cecil;
76
using OneShot;
87

98
namespace AnySerialize.CodeGen
109
{
1110
public interface ITypeSearcher
1211
{
13-
[CanBeNull] TypeReference Search();
12+
TypeReference? Search();
1413
}
1514

1615
public interface ITypeSearcher<T> : ITypeSearcher where T : Attribute, IAnyTypeSearcherAttribute {}
@@ -29,55 +28,55 @@ from @interface in @base.GetInterfaces()
2928
where @interface.IsGenericType && @interface.GetGenericTypeDefinition() == typeof(ITypeSearcher<>)
3029
select (searcher: type, attribute: @interface.GenericTypeArguments[0])
3130
;
32-
_value = searchers.ToDictionary(t => t.attribute.FullName, t => t.searcher);
31+
_value = searchers.ToDictionary(t => t.attribute!.FullName, t => t.searcher);
3332
}
3433

35-
public static TypeReference Search(this Container container, CustomAttribute attribute, params object[] instances)
34+
public static TypeReference? Search(this Container container, CustomAttribute attribute, params object[] instances)
3635
{
37-
return container.CreateSearcher(attribute, instances.Select(instance => (instance, (Type)null))).Search();
36+
return container.CreateSearcher(attribute, instances.Select(instance => (instance, (Type?)null))).Search();
3837
}
3938

40-
public static TypeReference Search(this Container container, CustomAttribute attribute, params (object instance, Type label)[] instances)
39+
public static TypeReference? Search(this Container container, CustomAttribute attribute, params (object instance, Type? label)[] instances)
4140
{
4241
return container.CreateSearcher(attribute, instances).Search();
4342
}
4443

45-
public static TypeReference Search<T>(this Container container) where T : ITypeSearcher
44+
public static TypeReference? Search<T>(this Container container) where T : ITypeSearcher
4645
{
4746
return container.CreateSearcher(typeof(T), Enumerable.Empty<(object instance, Type label)>()).Search();
4847
}
4948

50-
public static TypeReference Search<T>(this Container container, params object[] instances) where T : ITypeSearcher
49+
public static TypeReference? Search<T>(this Container container, params object[] instances) where T : ITypeSearcher
5150
{
52-
return container.CreateSearcher(typeof(T), instances.Select(instance => (instance, (Type)null))).Search();
51+
return container.CreateSearcher(typeof(T), instances.Select(instance => (instance, (Type?)null))!).Search();
5352
}
5453

55-
public static TypeReference Search<T>(this Container container, params (object instance, Type label)[] instances) where T : ITypeSearcher
54+
public static TypeReference? Search<T>(this Container container, params (object instance, Type? label)[] instances) where T : ITypeSearcher
5655
{
57-
return container.CreateSearcher(typeof(T), instances).Search();
56+
return container.CreateSearcher(typeof(T), instances!).Search();
5857
}
5958

60-
private static ITypeSearcher CreateSearcher(this Container container, CustomAttribute attribute, IEnumerable<(object instance, Type label)> instances)
59+
private static ITypeSearcher CreateSearcher(this Container container, CustomAttribute attribute, IEnumerable<(object instance, Type? label)> instances)
6160
{
62-
var searcher = _value[attribute.AttributeType.FullName];
61+
var searcher = _value[attribute.AttributeType!.FullName];
6362
container = container.CreateChildContainer();
64-
container.RegisterInstance(container).AsSelf();
63+
container.RegisterInstance(container)!.AsSelf();
6564

66-
foreach (var attributeArgument in attribute.ConstructorArguments) container.RegisterInstance(attributeArgument.Value)
65+
foreach (var attributeArgument in attribute.ConstructorArguments!) container.RegisterInstance(attributeArgument.Value)!
6766
.AsSelf(typeof(AttributeLabel<>))
6867
.AsBases(typeof(AttributeLabel<>))
6968
.AsInterfaces(typeof(AttributeLabel<>))
7069
;
7170

72-
foreach (var (instance, label) in instances) container.RegisterInstance(instance).AsSelf(label).AsBases(label).AsInterfaces(label);
73-
return (ITypeSearcher)container.Instantiate(searcher);
71+
foreach (var (instance, label) in instances) container.RegisterInstance(instance)!.AsSelf(label).AsBases(label).AsInterfaces(label);
72+
return (ITypeSearcher)container.Instantiate(searcher!)!;
7473
}
7574

7675
private static ITypeSearcher CreateSearcher(this Container container, Type searcherType, IEnumerable<(object instance, Type label)> instances)
7776
{
7877
container = container.CreateChildContainer();
79-
foreach (var (instance, label) in instances) container.RegisterInstance(instance).AsSelf(label).AsBases().AsInterfaces();
80-
return (ITypeSearcher)container.Instantiate(searcherType);
78+
foreach (var (instance, label) in instances) container.RegisterInstance(instance)!.AsSelf(label).AsBases().AsInterfaces();
79+
return (ITypeSearcher)container.Instantiate(searcherType)!;
8180
}
8281
}
8382
}

Packages/com.quabug.any-serialize/Runtime/AnySerializeUnity.tt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
<#@ template language="C#" #>
22
<#@ output extension=".cs" #>
3-
<#@ assembly name="C:/Program Files/Unity/Hub/Editor/2021.3.6f1/Editor/Data/Managed/UnityEngine/UnityEngine.CoreModule.dll" #>
3+
<#@ assembly name="C:/Program Files/Unity/Hub/Editor/2021.3.9f1/Editor/Data/Managed/UnityEngine/UnityEngine.CoreModule.dll" #>
44
<#@ assembly name="$(SolutionDir)/Library/ScriptAssemblies/Unity.Mathematics.dll" #>
55
<#@ import namespace="System" #>
66
<#@ import namespace="Unity.Mathematics" #>

Packages/com.quabug.any-serialize/Runtime/ReadOnlyAnyDictionary.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ public Dictionary<TKey, TValue> Value
2424
if (_cache != null) return _cache;
2525
#endif
2626
_cache ??= new Dictionary<TKey, TValue>();
27+
_cache.Clear();
2728
foreach (var pair in _pairs) _cache.Add(pair.Value.Key, pair.Value.Value);
2829
return _cache;
2930
}
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
{
22
"name": "com.quabug.any-serialize",
33
"description": "Generate serializable code of any properties for Unity3D serializer",
4-
"version": "0.3.0",
4+
"version": "0.1.0",
55
"unity": "2021.3",
66
"displayName": "AnySerialize",
77
"type": "library",
88
"dependencies": {
99
"com.unity.nuget.mono-cecil": "1.11.4",
10-
"com.quabug.any-processor": "0.2.0",
10+
"com.quabug.any-processor": "0.1.0",
1111
"com.quabug.one-shot-injection": "2.2.0"
1212
}
1313
}

Packages/packages-lock.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
"source": "embedded",
1515
"dependencies": {
1616
"com.unity.nuget.mono-cecil": "1.11.4",
17-
"com.quabug.any-processor": "0.2.0",
17+
"com.quabug.any-processor": "0.1.0",
1818
"com.quabug.one-shot-injection": "2.2.0"
1919
}
2020
},

0 commit comments

Comments
 (0)