This repository was archived by the owner on Jun 10, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathToStringTask.cs
More file actions
271 lines (238 loc) · 12.9 KB
/
Copy pathToStringTask.cs
File metadata and controls
271 lines (238 loc) · 12.9 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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using PostSharp.Reflection;
using PostSharp.Sdk.CodeModel;
using PostSharp.Sdk.CodeModel.Helpers;
using PostSharp.Sdk.Extensibility;
using PostSharp.Sdk.Extensibility.Compilers;
using PostSharp.Sdk.Extensibility.Tasks;
namespace PostSharp.Community.ToString.Weaver
{
[ExportTask(Phase = TaskPhase.CustomTransform, TaskName = nameof(ToStringTask))]
public class ToStringTask : Task
{
[ImportService]
private IAnnotationRepositoryService annotationRepositoryService;
[ImportService]
private ICompilerAdapterService compilerAdapterService;
private Assets assets;
public override string CopyrightNotice => "Simon Cropp, PostSharp Technologies, and contributors";
public override bool Execute()
{
assets = new Assets(this.Project.Module);
List<IAnnotationInstance> types = annotationRepositoryService.GetAnnotations(typeof(ToStringAttribute));
List<IAnnotationInstance> ignored = annotationRepositoryService.GetAnnotations(typeof(IgnoreDuringToStringAttribute));
HashSet<MetadataDeclaration> ignoredDeclarations = new HashSet<MetadataDeclaration>(ignored.Select(tuple => tuple.TargetElement));
var basicConfig = Configuration.FindGlobalConfiguration(annotationRepositoryService);
foreach (var tuple in types)
{
var config = Configuration.ReadConfiguration(tuple.Value, basicConfig);
AddToStringToType(tuple.TargetElement as TypeDefDeclaration, config, ignoredDeclarations);
}
return true;
}
private void AddToStringToType(TypeDefDeclaration enhancedType, Configuration config, HashSet<MetadataDeclaration> ignoredDeclarations)
{
if (enhancedType.Methods.Any<IMethod>(m => m.Name == "ToString" &&
!m.IsStatic &&
m.ParameterCount == 0))
{
// It's already present, just skip it.
return;
}
// Create signature
MethodDefDeclaration method = new MethodDefDeclaration
{
Name = "ToString",
CallingConvention = CallingConvention.HasThis,
Attributes = MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig
};
enhancedType.Methods.Add(method);
CompilerGeneratedAttributeHelper.AddCompilerGeneratedAttribute(method);
method.ReturnParameter = ParameterDeclaration.CreateReturnParameter(enhancedType.Module.Cache.GetIntrinsic(IntrinsicType.String));
var (fields, properties) = FindFieldsAndProperties(enhancedType, ignoredDeclarations, config);
// Generate code:
using (InstructionWriter writer = InstructionWriter.GetInstance())
{
CreatedEmptyMethod getHashCodeData = MethodBodyCreator.CreateModifiableMethodBody(writer, method);
writer.AttachInstructionSequence(getHashCodeData.PrincipalBlock.AddInstructionSequence());
// Create the format string and put it on the stack:
int numberOfArguments = fields.Count + properties.Count;
string formatString = ConstructFormatString(config, enhancedType, fields, properties);
writer.EmitInstructionString(OpCodeNumber.Ldstr, formatString);
// Create the argument array and put it on the stack:
writer.EmitInstructionInt32(OpCodeNumber.Ldc_I4, numberOfArguments);
writer.EmitInstructionType(OpCodeNumber.Newarr, enhancedType.Module.Cache.GetIntrinsic(IntrinsicType.Object));
// Put all the field and property values on the stack:
int i = 0;
foreach (var field in fields)
{
EmitLoadToString(writer, i, field);
i++;
}
bool enhancedTypeIsValueType = enhancedType.IsValueTypeSafe() == true;
foreach (var property in properties)
{
EmitLoadToString(writer, i, property, enhancedTypeIsValueType);
i++;
}
// Return string.Format(formatString, theArgumentArray):
writer.EmitInstructionMethod(OpCodeNumber.Call, assets.String_Format);
writer.EmitInstructionLocalVariable(OpCodeNumber.Stloc, getHashCodeData.ReturnVariable);
writer.EmitBranchingInstruction(OpCodeNumber.Br, getHashCodeData.ReturnSequence);
writer.DetachInstructionSequence();
}
}
/// <summary>
/// Finds all fields and properties in the type that should be put into ToString. This includes accessible
/// fields and properties in base classes, transitively, but it excludes ignored fields and properties.
/// </summary>
private (List<UsableField> fields, List<UsableProperty> properties) FindFieldsAndProperties(TypeDefDeclaration enhancedType,
HashSet<MetadataDeclaration> ignoredDeclarations, Configuration config)
{
List<UsableField> fields = new List<UsableField>();
List<UsableProperty> properties = new List<UsableProperty>();
TypeDefDeclaration processingType = enhancedType;
GenericMap mapToGetThere = enhancedType.GetGenericContext();
bool isInBaseType = false;
while (true)
{
foreach (FieldDefDeclaration field in processingType.Fields)
{
if (field.IsStatic || field.IsConst || ignoredDeclarations.Contains(field)) continue;
if (field.Visibility == Visibility.Private && !config.IncludePrivate) continue;
// Exclude inaccessible fields:
if (isInBaseType && !field.IsVisible(enhancedType)) continue;
// Exclude PostSharp and generated fields:
if (field.Name[0] == '<') continue;
// Exclude field-like events:
if (processingType.Events.Any(ev => ev.Name == field.Name)) continue;
fields.Add(new UsableField(field, mapToGetThere));
}
foreach (PropertyDeclaration property in processingType.Properties)
{
// For auto-implemented properties, consider the property only, not the field:
FieldDefDeclaration backingField = compilerAdapterService.GetBackingField(property);
if (backingField != null)
{
fields.RemoveAll(f => f.FieldDefinition == backingField);
}
// Exclude indexers:
if (property.IsStatic || ignoredDeclarations.Contains(property) || !property.CanRead ||
property.Getter.Parameters.Count != 0) continue;
if (property.Visibility == Visibility.Private && !config.IncludePrivate) continue;
// Exclude inaccessible properties:
if (isInBaseType && !property.IsVisible(enhancedType)) continue;
// Exclude PostSharp and generated fields that were lifted into properties:
if (property.Name[0] == '<') continue;
// Exclude base properties with the same name. This way, if a property is overridden, we output it
// only once:
if (properties.Any(prp => prp.PropertyDefinition.Name == property.Name)) continue;
// Exclude field-like events (whose fields were promoted to properties by PostSharp):
if (processingType.Events.Any(ev => ev.Name == property.Name)) continue;
properties.Add(new UsableProperty(property, mapToGetThere));
}
// Ends at System.Object:
if (processingType.BaseType == null)
{
break;
}
isInBaseType = true;
mapToGetThere = processingType.BaseType.GetGenericContext().Apply(mapToGetThere);
processingType = processingType.BaseType.GetTypeDefinition();
}
return (fields, properties);
}
private void EmitLoadToString(InstructionWriter writer, int index, UsableProperty property, bool enhancedTypeIsValueType)
{
EmitPrologueToLoad(writer, index);
// Load the value:
writer.EmitInstruction(OpCodeNumber.Ldarg_0);
writer.EmitInstructionMethod(enhancedTypeIsValueType ? OpCodeNumber.Call : OpCodeNumber.Callvirt,
property.PropertyDefinition.Getter
.GetGenericInstance(property.MapToAccessThisPropertyFromMostDerivedClass)
.TranslateMethod(this.Project.Module));
EmitEpilogueToLoad(writer, property.PropertyDefinition.PropertyType.TranslateType(this.Project.Module).MapGenericArguments(property.MapToAccessThisPropertyFromMostDerivedClass));
}
private void EmitLoadToString(InstructionWriter writer, int index, UsableField field)
{
EmitPrologueToLoad(writer, index);
// Load the value:
writer.EmitInstruction(OpCodeNumber.Ldarg_0);
IField usedField = field.FieldDefinition.Translate(this.Project.Module).GetGenericInstance(field.MapToAccessTheFieldFromMostDerivedClass);
writer.EmitInstructionField(OpCodeNumber.Ldfld, usedField);
EmitEpilogueToLoad(writer, usedField.FieldType.TranslateType(this.Project.Module).MapGenericArguments(field.MapToAccessTheFieldFromMostDerivedClass));
}
private void EmitPrologueToLoad(InstructionWriter writer, int index)
{
writer.EmitInstruction(OpCodeNumber.Dup); // puts a pointer to the argument array on the stack
writer.EmitInstructionInt32(OpCodeNumber.Ldc_I4, index); // puts an index into the argument array on the stack
}
private void EmitEpilogueToLoad(InstructionWriter writer, ITypeSignature type)
{
if (type.IsValueTypeSafe() == true || type.TypeSignatureElementKind == TypeSignatureElementKind.GenericParameterReference ||
type.TypeSignatureElementKind == TypeSignatureElementKind.GenericParameter)
{
writer.EmitInstructionType(OpCodeNumber.Box, type);
}
else
{
writer.EmitInstruction(OpCodeNumber.Dup);
// if null?
writer.IfNotZero(() =>
{
// ok, use the duplicate
},
() =>
{
writer.EmitInstruction(OpCodeNumber.Pop); // remove the duplicate
writer.EmitInstructionString(OpCodeNumber.Ldstr, "null"); // replace with null
});
}
// store the value onto the position in the argument array (position was put onto stack by the prologue)
writer.EmitInstruction(OpCodeNumber.Stelem_Ref);
}
private string ConstructFormatString(Configuration config, TypeDefDeclaration type, List<UsableField> fields, List<UsableProperty> properties)
{
StringBuilder sb = new StringBuilder();
bool isThereAnything = fields.Count > 0 || properties.Count > 0;
if (config.WrapWithBraces)
{
sb.Append("{{");
}
if (config.WriteTypeName)
{
sb.Append(type.ShortName + (isThereAnything ? "; " : ""));
}
var all = fields.Select(fld => fld.FieldDefinition).Concat<NamedMetadataDeclaration>(properties.Select(prp => prp.PropertyDefinition));
int i = 0;
foreach (NamedMetadataDeclaration item in all)
{
if (i != 0)
{
sb.Append(config.PropertiesSeparator);
}
string name = item.Name;
int lastDot = name.LastIndexOf('.');
if (lastDot != -1)
{
name = name.Substring(lastDot + 1);
}
sb.Append(name);
sb.Append(config.NameValueSeparator);
sb.Append("{");
sb.Append(i);
sb.Append("}");
i++;
}
if (config.WrapWithBraces)
{
sb.Append("}}");
}
return sb.ToString();
}
}
}