-
Notifications
You must be signed in to change notification settings - Fork 117
/
StateWrapperGenerator.cs
439 lines (385 loc) · 13.2 KB
/
StateWrapperGenerator.cs
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Stubble.Core.Builders;
namespace Comet.SourceGenerator
{
[Generator]
public class StateWrapperGenerator : ISourceGenerator
{
private const string attributeSource = @"
[System.AttributeUsage(System.AttributeTargets.Assembly | System.AttributeTargets.Class, AllowMultiple = true)]
public class GenerateStateClassAttribute : System.Attribute
{
public GenerateStateClassAttribute(){}
public GenerateStateClassAttribute(System.Type classType) => ClassType = classType;
public string ClassName { get; set; }
public System.Type ClassType { get; }
public string Namespace { get; set; }
}
";
const string classMustacheTemplate = @"
using System;
using Comet;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace {{NameSpace}} {
public partial class {{ClassName}} :INotifyPropertyRead, IAutoImplemented
{
public event PropertyChangedEventHandler PropertyRead;
public event PropertyChangedEventHandler PropertyChanged;
public readonly {{ClassType}} OriginalModel;
bool shouldNotifyChanged = true;
public {{ClassName}} ({{ClassType}} model)
{
OriginalModel = model;
InitStateProperties();
if (model is INotifyPropertyChanged inpc)
{
inpc.PropertyChanged += Inpc_PropertyChanged;
shouldNotifyChanged = false;
}
}
void Inpc_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
StateManager.OnPropertyChanged(sender, e.PropertyName, null);
PropertyChanged?.Invoke(sender, e);
}
void NotifyPropertyChanged(object value, [CallerMemberName] string memberName = null){
if (shouldNotifyChanged) {
StateManager.OnPropertyChanged(this, memberName, value);
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(memberName));
}
}
void NotifyPropertyRead([CallerMemberName] string memberName = null){
InitDirtyProperty(memberName);
StateManager.OnPropertyRead(this, memberName);
PropertyRead?.Invoke(this, new PropertyChangedEventArgs(memberName));
}
/// <summary>
/// Notifies Comet of all changes in the underlying model (OriginalModel) observed properties
/// </summary>
public void NotifyChanged(){
{{#Properties}}
{{#PropertiesUpdateAllFunc}}
{{/PropertiesUpdateAllFunc}}
{{/Properties}}
}
void InitStateProperties(){
{{#Properties}}
{{#PropertiesInitStateFunc}}
{{/PropertiesInitStateFunc}}
{{/Properties}}
}
void InitDirtyProperty([CallerMemberName] string memberName = null){
switch (memberName){
{{#Properties}}
{{#PropertiesInitFunc}}
{{/PropertiesInitFunc}}
{{/Properties}}
}
}
void UpdateDirtyProperty([CallerMemberName] string memberName = null){
switch (memberName){
{{#Properties}}
{{#PropertiesUpdateFunc}}
{{/PropertiesUpdateFunc}}
{{/Properties}}
}
}
{{#Properties}}
{{#PropertiesFunc}}
{{/PropertiesFunc}}
{{/Properties}}
}
}
";
static StateWrapperGenerator()
{
var interfacePropSupportMustache = @"
{{^HasState}}
bool {{LName}}IsObserved = false;
bool {{LName}}IsDirty => {{LName}}IsObserved && !OriginalModel.{{Name}}.Equals({{LName}}LastValue);
{{{Type}}} {{LName}}LastValue;
{{/HasState}}
";
var interfacePropertyMustache = interfacePropSupportMustache +
@" public {{{Type}}} {{Name}} {
{{#HasState}}
get;
{{/HasState}}
{{^HasState}}
get {
NotifyPropertyRead();
return OriginalModel.{{Name}};
}
{{/HasState}}
{{#HasState}}
private set;
{{/HasState}}
{{^HasState}}
set {
OriginalModel.{{Name}} = value;
{{LName}}LastValue = value;
NotifyPropertyChanged(value);
}
{{/HasState}}
}
";
var interfacePropertySetOnlyMustache = interfacePropSupportMustache +
@" public {{{Type}}} {{Name}} {
set {
OriginalModel.{{Name}} = value;
{{LName}}LastValue = value;
NotifyPropertyChanged(value);
}
}
";
var interfacePropertyGetOnlyMustache = interfacePropSupportMustache +
@" public {{{Type}}} {{Name}} {
get {
NotifyPropertyRead();
return OriginalModel.{{Name}};
}
}
";
interfacePropertyDictionary = new()
{
[(true, true)] = interfacePropertyMustache,
[(true, false)] = interfacePropertyGetOnlyMustache,
[(false, true)] = interfacePropertySetOnlyMustache,
};
}
Stubble.Core.StubbleVisitorRenderer stubble = new StubbleBuilder().Build();
static Dictionary<(bool HasGet, bool HasSet), string> interfacePropertyDictionary;
public void Execute(GeneratorExecutionContext context)
{
if (!(context.SyntaxContextReceiver is SyntaxReceiver rx) || !rx.TemplateInfo.Any())
return;
var st = context.Compilation.SyntaxTrees;
void addChildStateClasses(IEnumerable<INamedTypeSymbol> match)
{
var matchWith = match.ToList();
matchWith.AddRange(match.SelectMany(m => GetAllBaseTypes(m)));
//var parentStateClassesProps =
//select all the class SyntaxNodes for match classes
var classes = st.SelectMany(st => st.GetRoot().DescendantNodes()).Where(
sn => {
var select = false;
if (sn is ClassDeclarationSyntax cds)
{
var sm = context.Compilation.GetSemanticModel(cds.SyntaxTree);
var ts = sm.GetDeclaredSymbol(cds).OriginalDefinition as INamedTypeSymbol;
select = matchWith.Any(c => c == ts || c.OriginalDefinition == ts);
}
return select;
});
//select all property SyntaxNodes for matched state classes that return a user class to be wrapped
var props = classes.SelectMany(c => c.ChildNodes().Where(cn => {
var select = false;
if (cn is PropertyDeclarationSyntax pds)
{
var sm = context.Compilation.GetSemanticModel(pds.SyntaxTree);
var realClass = StateWrapperGenerator.GetType(sm, pds.Type);
select = !(pds.Type is NullableTypeSyntax) && IsUserClass(realClass);
}
return select;
}));
var parentStateClassesProps = props.Select(pds => {
var p = (PropertyDeclarationSyntax)pds;
var sm = context.Compilation.GetSemanticModel(p.SyntaxTree);
var realClass = StateWrapperGenerator.GetType(sm, p.Type);
return realClass;
}).ToList();
parentStateClassesProps.ForEach(itns => rx.AddTemplate(itns));
if (parentStateClassesProps.Any())
{
addChildStateClasses(parentStateClassesProps);
}
}
var match = rx.TemplateInfo.Select(x => x.classType);
addChildStateClasses(match);
var templates = rx.TemplateInfo.ToList();
foreach (var item in templates)
{
var input = GetModelData(item.name, item.classType, item.nameSpace, rx);
var classSource = stubble.Render(classMustacheTemplate, input);
context.AddSource($"{item.name}.g.cs", classSource);
}
}
bool IsUserClass(ITypeSymbol realClass) => realClass?.TypeKind == TypeKind.Class && realClass.SpecialType == SpecialType.None && !realClass.ToString().StartsWith("System"); //&& realClass.isnu;
IEnumerable<INamedTypeSymbol> GetAllBaseTypes(INamedTypeSymbol classType)
{
yield return classType;
if (classType.BaseType != null)
{
foreach (var baseType in GetAllBaseTypes(classType.BaseType))
yield return baseType;
}
}
dynamic GetModelData(string className, INamedTypeSymbol classType, string nameSpace, SyntaxReceiver sr)
{
var baseClasses = GetAllBaseTypes(classType).ToList();
List<(string Type, string Name)> properties = new();
List<(string Type, string Name)> methods = new();
List<string> propertiesWithSetters = new();
List<string> propertiesWithGetters = new();
List<string> propertiesWithState = new();
foreach (var i in baseClasses)
{
var members = i.GetMembers();
foreach (var m in members)
{
if (m is IPropertySymbol pi && pi.DeclaredAccessibility == Accessibility.Public)
{
string type = null;
string name = pi.Name;
bool isUserClass = IsUserClass(pi.Type);
bool isPublicSet = pi.OriginalDefinition.SetMethod?.DeclaredAccessibility == Accessibility.Public;
bool isAccessibleSet = isPublicSet && (!pi.IsReadOnly && !pi.OriginalDefinition.SetMethod.IsReadOnly && !pi.OriginalDefinition.SetMethod.IsInitOnly);
propertiesWithGetters.Add(name);
if (isAccessibleSet)
propertiesWithSetters.Add(name);
if (isUserClass)
{
var theType = CometViewSourceGenerator.GetFullName(pi.Type);
theType += "State";
var exists = sr.TemplateInfo.Any(i => $"{i.nameSpace}.{i.name}" == theType);
if (exists)
{
propertiesWithState.Add(name);
type = theType;
}
}
type ??= pi.Type.ToString();
var t = (type, name);
if (!properties.Contains(t))
properties.Add(t);
}
}
}
var interfacePropInitStateMustache =
@" {{Name}} = new {{Type}}(OriginalModel.{{Name}});
";
var interfacePropInitMustache =
@" case ""{{Name}}"":
if (!{{LName}}IsObserved){
{{LName}}LastValue = OriginalModel.{{Name}};
{{LName}}IsObserved = true;
}
break;
";
var interfacePropUpdateMustache =
@" case ""{{Name}}"":
{{#HasState}}
{{Name}}.NotifyChanged();
{{/HasState}}
{{^HasState}}
if ({{LName}}IsDirty){
{{LName}}LastValue = OriginalModel.{{Name}};
NotifyPropertyChanged({{LName}}LastValue, memberName);
}
{{/HasState}}
break;
";
var interfacePropUpdateAllMustache =
@" {{#HasState}}
UpdateDirtyProperty(""{{Name}}"");
{{/HasState}}
{{^HasState}}
if (shouldNotifyChanged && {{LName}}IsObserved) UpdateDirtyProperty(""{{Name}}"");
{{/HasState}}
";
var input = new {
ClassName = className,
ClassType = CometViewSourceGenerator.GetFullName(classType),
NameSpace = nameSpace,
Properties = properties.Select(x => new {
Type = x.Type,
Name = x.Name,
LName = x.Name.LowercaseFirst(),
HasSet = propertiesWithSetters.Contains(x.Name),
HasGet = propertiesWithGetters.Contains(x.Name),
HasState = propertiesWithState.Contains(x.Name)
}).Where(p => !p.Name.StartsWith("this")).ToList(),
PropertiesFunc = new Func<dynamic, string, object>((dyn, str) => {
var template = (dyn.HasGet || dyn.HasSet || dyn.HasState) ? interfacePropertyDictionary[(dyn.HasGet, (dyn.HasSet || dyn.HasState))] : "";
return stubble.Render(template, dyn);
}),
PropertiesUpdateFunc = new Func<dynamic, string, object>((dyn, str) => {
var template = dyn.HasGet ? interfacePropUpdateMustache : "";
return stubble.Render(template, dyn);
}),
PropertiesUpdateAllFunc = new Func<dynamic, string, object>((dyn, str) => {
var template = dyn.HasGet ? interfacePropUpdateAllMustache : "";
return stubble.Render(template, dyn);
}),
PropertiesInitFunc = new Func<dynamic, string, object>((dyn, str) => {
var template = dyn.HasGet && !dyn.HasState ? interfacePropInitMustache : "";
return stubble.Render(template, dyn);
}),
PropertiesInitStateFunc = new Func<dynamic, string, object>((dyn, str) => {
var template = dyn.HasState ? interfacePropInitStateMustache : "";
return stubble.Render(template, dyn);
})
};
return input;
}
public void Initialize(GeneratorInitializationContext context)
{
//if (!Debugger.IsAttached)
//{
// Debugger.Launch();
//}
context.RegisterForPostInitialization((pi) => pi.AddSource("GenerateStateClassAttribute__", attributeSource));
context.RegisterForSyntaxNotifications(() => new SyntaxReceiver());
}
class SyntaxReceiver : ISyntaxContextReceiver
{
public List<(string name, INamedTypeSymbol classType, string nameSpace)> TemplateInfo = new();
public void AddTemplate(INamedTypeSymbol classType)
{
string name = $"{classType.Name}State";
string nameSpace = CometViewSourceGenerator.GetFullName(classType.ContainingNamespace);
if (!TemplateInfo.Exists(t => t.name == name && t.nameSpace == nameSpace))
{
TemplateInfo.Add((name, classType, nameSpace));
}
}
public void OnVisitSyntaxNode(GeneratorSyntaxContext context)
{
INamedTypeSymbol realClass;
if (context.Node is ClassDeclarationSyntax cds && context.SemanticModel.GetDeclaredSymbol(cds).GetAttributes().Any(x => x.AttributeClass.Name == "GenerateStateClassAttribute"))
{
realClass = context.SemanticModel.GetDeclaredSymbol(cds).OriginalDefinition as INamedTypeSymbol;//GetType(context, f);
AddTemplate(realClass);
}
if (context.Node is AttributeSyntax attrib)
{
if (context.SemanticModel.GetTypeInfo(attrib).Type?.ToDisplayString() == "GenerateStateClassAttribute")
{
if (attrib.ArgumentList == null) return;
var f = attrib.ArgumentList.Arguments[0].Expression as TypeOfExpressionSyntax;
realClass = StateWrapperGenerator.GetType(context.SemanticModel, f);
AddTemplate(realClass);
}
}
}
}
static INamedTypeSymbol GetType(SemanticModel sm, TypeOfExpressionSyntax expression)
{
return GetType(sm, expression.Type);
}
static INamedTypeSymbol GetType(SemanticModel sm, TypeSyntax type)
{
SymbolInfo? interfaceType = sm.GetSymbolInfo(type);
var s = CometViewSourceGenerator.GetFullName(interfaceType?.Symbol);
return sm.Compilation.GetTypeByMetadataName(s);
}
}
}