-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathFieldIdAssignmentHelper.cs
More file actions
203 lines (175 loc) · 8.13 KB
/
FieldIdAssignmentHelper.cs
File metadata and controls
203 lines (175 loc) · 8.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
#nullable enable
using System;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.CodeAnalysis;
using Orleans.CodeGenerator.Hashing;
using Orleans.CodeGenerator.Model;
using Orleans.CodeGenerator.SyntaxGeneration;
namespace Orleans.CodeGenerator;
internal class FieldIdAssignmentHelper
{
private readonly GenerateFieldIds _implicitMemberSelectionStrategy;
private readonly ImmutableArray<IParameterSymbol> _constructorParameters;
private readonly LibraryTypes _libraryTypes;
private readonly ISymbol[] _memberSymbols;
private readonly Dictionary<ISymbol, (uint, bool)> _symbols = new(SymbolEqualityComparer.Default);
public bool IsValidForSerialization { get; }
public string? FailureReason { get; private set; }
public IEnumerable<ISymbol> Members => _memberSymbols;
public FieldIdAssignmentHelper(INamedTypeSymbol typeSymbol, ImmutableArray<IParameterSymbol> constructorParameters,
GenerateFieldIds implicitMemberSelectionStrategy, LibraryTypes libraryTypes)
{
_constructorParameters = constructorParameters;
_implicitMemberSelectionStrategy = implicitMemberSelectionStrategy;
_libraryTypes = libraryTypes;
_memberSymbols = GetMembers(typeSymbol).ToArray();
IsValidForSerialization = _implicitMemberSelectionStrategy != GenerateFieldIds.None && !HasMemberWithIdAnnotation() ? GenerateImplicitFieldIds() : ExtractFieldIdAnnotations();
}
public bool TryGetSymbolKey(ISymbol symbol, out (uint, bool) key) => _symbols.TryGetValue(symbol, out key);
private bool HasMemberWithIdAnnotation() => Array.Exists(_memberSymbols, member => member.HasAnyAttribute(_libraryTypes.IdAttributeTypes));
private IEnumerable<ISymbol> GetMembers(INamedTypeSymbol symbol)
{
foreach (var member in symbol.GetMembers().OrderBy(m => m.MetadataName))
{
if (member.IsStatic || member.IsAbstract)
{
continue;
}
if (member is not (IFieldSymbol or IPropertySymbol))
{
continue;
}
if (member.HasAttribute(_libraryTypes.NonSerializedAttribute))
{
continue;
}
yield return member;
}
}
private bool ExtractFieldIdAnnotations()
{
foreach (var member in _memberSymbols)
{
if (member is IPropertySymbol prop)
{
var id = CodeGenerator.GetId(_libraryTypes, prop);
if (id.HasValue)
{
_symbols[member] = (id.Value, false);
}
else if (PropertyUtility.GetMatchingPrimaryConstructorParameter(prop, _constructorParameters) is { } prm)
{
// Check for [Id] attribute on the primary constructor parameter
id = CodeGenerator.GetId(_libraryTypes, prm);
if (id.HasValue)
{
_symbols[member] = (id.Value, true);
}
else
{
_symbols[member] = ((uint)_constructorParameters.IndexOf(prm), true);
}
}
}
if (member is IFieldSymbol field)
{
var id = CodeGenerator.GetId(_libraryTypes, field);
var isConstructorParameter = false;
if (!id.HasValue)
{
var property = PropertyUtility.GetMatchingProperty(field, _memberSymbols);
if (property is null)
{
continue;
}
id = CodeGenerator.GetId(_libraryTypes, property);
if (!id.HasValue)
{
var constructorParameter = _constructorParameters.FirstOrDefault(x => x.Name.Equals(property.Name, StringComparison.OrdinalIgnoreCase));
if (constructorParameter is not null)
{
// Check for [Id] attribute on the constructor parameter
id = CodeGenerator.GetId(_libraryTypes, constructorParameter);
if (!id.HasValue)
{
id = (uint)_constructorParameters.IndexOf(constructorParameter);
}
isConstructorParameter = true;
}
}
}
if (id.HasValue)
{
_symbols[member] = (id.Value, isConstructorParameter);
}
}
}
return true;
}
private static (string, uint) GetCanonicalNameAndFieldId(ITypeSymbol typeSymbol, string name)
{
name = PropertyUtility.GetCanonicalName(name);
// compute the hash from the type name (without namespace, to allow it to move around) and name
var typeName = typeSymbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat);
var hashCode = ComputeHash($"{typeName}%{name}");
return (name, (uint)hashCode);
static unsafe uint ComputeHash(string data)
{
uint hash;
var input = BitConverter.IsLittleEndian ? MemoryMarshal.AsBytes(data.AsSpan()) : Encoding.Unicode.GetBytes(data);
XxHash32.TryHash(input, new Span<byte>((byte*)&hash, sizeof(uint)), out _);
return BitConverter.IsLittleEndian ? hash : BinaryPrimitives.ReverseEndianness(hash);
}
}
private bool GenerateImplicitFieldIds()
{
var constructorFieldIds = new Dictionary<string, uint>();
foreach (var parameter in _constructorParameters)
{
var (canonicalName, fieldId) = GetCanonicalNameAndFieldId(parameter.Type, parameter.Name);
constructorFieldIds[canonicalName] = fieldId;
}
var success = _implicitMemberSelectionStrategy switch
{
GenerateFieldIds.PublicProperties => GenerateFromProperties(_memberSymbols.OfType<IPropertySymbol>()),
_ => false
};
// validate - we can only use generated field ids if there were no collisions
if (success && _symbols.Values.Distinct().Count() != _symbols.Count)
{
FailureReason = "hash collision (consider using explicit [Id] annotations for this type)";
return false;
}
return success;
bool GenerateFromProperties(IEnumerable<IPropertySymbol> properties)
{
foreach (var property in properties)
{
var (canonicalName, fieldId) = GetCanonicalNameAndFieldId(property.Type, property.Name);
var isConstructorParameter = constructorFieldIds.TryGetValue(canonicalName, out var constructorFieldId);
// abort when inconsistencies are detected
if (isConstructorParameter && fieldId != constructorFieldId)
{
FailureReason = $"type mismatch for property {property.Name} and its corresponding constructor parameter";
return false;
}
// for immutable types we must currently use the backing field of the public property, as the serialization
// engine does not call a custom constructor to recreate the instance
var mustUseField = property.SetMethod == null || property.IsReadOnly
|| property.SetMethod.IsInitOnly
|| property.IsStatic
|| property.SetMethod.IsAbstract;
ISymbol? symbol = mustUseField ? PropertyUtility.GetMatchingField(property, _memberSymbols) : property;
if (symbol == null)
continue;
_symbols[symbol] = (fieldId, isConstructorParameter);
}
return _symbols.Count > 0;
}
}
}