This repository has been archived by the owner on Nov 3, 2023. It is now read-only.
/
AstEmitter.DefineDependentPropertiesEvaluation.n
416 lines (371 loc) · 15.2 KB
/
AstEmitter.DefineDependentPropertiesEvaluation.n
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
using Nitra.Typing;
using Nitra.Model;
using Nemerle;
using Nemerle.Collections;
using Nemerle.Compiler;
using Nemerle.Compiler.Parsetree;
using Nemerle.Compiler.Typedtree;
using Nemerle.Imperative;
using Nemerle.Text;
using Nemerle.Utility;
using System;
using System.Linq;
using SCG = System.Collections.Generic;
namespace Nitra.Compiler
{
internal abstract partial class AstEmitter
{
protected DefineDependentPropertiesEvaluation(tb : TypeBuilder, symbol : AstSymbol) : void
{
Util.locate(symbol.FirstLocation.NLocation(),
tb.Manager.MacroColors.InGlobalColor(fun()
{
def body = SCG.List();
when ((symbol : object) is IDependentPropertyAssignmentContainer as container)
{
def initializedOutProperties = SCG.HashSet(symbol.InitializedOutProperties);
when (symbol is ExtensionAstSymbol(BaseAst = SymbolRef.Some(baseSymbol)))
initializedOutProperties.UnionWith(baseSymbol.InitializedOutProperties);
foreach (p in symbol.AllProperties)
{
| DependentAstPropertySymbol(Direction = Out, LinkedProperty = SymbolRef.Some(inPropertySymbol)) as outPropertySymbol when symbol is ExtensibleAstSymbol =>
unless (initializedOutProperties.Contains(outPropertySymbol))
{
def loc = if (outPropertySymbol.DeclaringAst == symbol) outPropertySymbol.FirstLocation else symbol.FirstLocation;
container.AddAssignment(DependentPropertyAssignment(loc, [Identifier(symbol.FirstLocation, outPropertySymbol.Name)], <[ this.$(inPropertySymbol.Name : usesite) ]>))
}
| DependentAstPropertySymbol(Direction = Out) as outPropertySymbol =>
unless (initializedOutProperties.Contains(outPropertySymbol))
{
// TODO: FixMe: Bug! Инициализация может быть во вхождениях.
//def loc = if (outPropertySymbol.DeclaringAst == symbol) outPropertySymbol.FirstLocation else symbol.FirstLocation;
//Message.Error(loc.NLocation(), $"Output dependent property '$(outPropertySymbol.Name)' is never assigned to");
}
| _ => ()
}
foreach (assignment in container.GetAssignments())
body.Add(Util.locate(assignment.Location.NLocation(), <[ $(PExprUtils.FromQualifiedIdentifier(assignment.Path)) = $(assignment.Expression) ]>));
}
tb.Define(<[ decl:
public override EvalProperties($("context" : global) : Nitra.Declarations.DependentPropertyEvalContext) : void
{
..$body
}
]>);
def compileGraph(methodBuilder : MethodBuilder, graphNodes : Seq[Node]) : void
{
def cycled = Node.Sort(graphNodes);
if (cycled)
{
def cycledNodes = Node.FindCycling(graphNodes);
foreach (cycledNode in cycledNodes)
Message.Error(cycledNode.Location, "Is cycled.");
otherwise assert(false, "Cycled nodes not found");
}
else
{
def props = SCG.List();
foreach (s is SimpleAstPropertySymbol in symbol.AllProperties)
{
if (tb.LookupMember(s.Name).Find(m => m is IProperty) is Some(m))
props.Add(m :> IProperty);
else
assert(false, $"IProperty for symbol $s not found");
}
def graphNodes2 = AddDependencyOnAstProperties(graphNodes, props);
//CheckOutputPropertiesAssignment(symbol, newGraphNodes);
def code = GenerateCode(tb, graphNodes2);
if (symbol is ExtensionAstSymbol)
methodBuilder.Body = <[ $code; base.EvalProperties($("context" : usesite)); ]>
else
methodBuilder.Body = code;
throw RestartRunBodyTyperException()
}
}
def typingHandler(_ : object, args : StageEventArgs) : void
{
def func = args.Typer.CurrentFunction;
when (func.Name == "EvalProperties")
{
try
{
match (func.Body)
{
| FunBody.Typed(TExpr.Block(_, TExpr.Literal(Literal.Void))) =>
compileGraph(args.Typer.CurrentMethodBuilder, [])
| FunBody.Typed(TExpr.Block(_, bodyExpr)) =>
def expr = ValidateEvalFieldsCode(bodyExpr);
def nodesMap = MakeDependencyGraph(expr);
def graphNodes = nodesMap.Values.ToArray();
compileGraph(args.Typer.CurrentMethodBuilder, graphNodes)
| _ => Message.Error(args.Typer.CurrentFunction.Location, "Unsupported dependent properties syntax.")
}
}
finally
tb.MethodBeforeStage2 -= typingHandler
}
}
tb.MethodBeforeStage2 += typingHandler
}));
}
private static ErrorUnexpectedExpr(expr : TExpr) : void
{
assert2(false);
Message.FatalError(expr.Location, $"Unexpected expression '$expr' $(expr.GetType().Name)")
}
private static ValidateEvalFieldsCode(expr : TExpr) : TExpr
{
def walker = ExprWalker();
def checkInvalidExpre(info : ExprWalkInfo) : void
{
match (info.Node)
{
| TExpr.DefFunctionsIn as e
| TExpr.DefValIn as e
| TExpr.Block as e
| TExpr.Error as e
| TExpr.SelfTailCall as e
| TExpr.MultipleAssign as e
| TExpr.StaticEventRef as e
| TExpr.EventMember as e => ErrorUnexpectedExpr(e);
| _ => ()
}
}
walker.Walk(expr, checkInvalidExpre);
def removeDelayed(expr : TExpr) : TExpr
{
| PropertyMember as e =>
def newObj = e.obj.Walk(removeDelayed);
if (newObj : object != e.obj)
{
def res = TExpr.PropertyMember(e.Type, newObj, e.prop);
res.Location = e.Location;
res
}
else
e
| Typedtree.TExpr.StaticPropertyRef as e => e
| TExpr.Delayed as d when d.susp.IsResolved => d.susp.ResolutionResult
| _ => null
}
//assert2(false);
expr.Walk(removeDelayed)
}
private MakeDependencyGraph(expr : TExpr) : Hashtable[list[IProperty], Node]
{
def nodesMap = Hashtable();
def toKey(expr : TExpr, acc : list[IProperty] = []) : list[IProperty]
{
match (expr)
{
| TExpr.PropertyMember as e => toKey(e.obj, e.prop :: acc)
| TExpr.Base => acc
| TExpr.This => acc
| _ => ErrorUnexpectedExpr(expr); null
}
}
def addNodesDependentOnAssignedProperty(expr : TExpr, node : Node) : void
{
def walker = ExprWalker();
def walk(info : ExprWalkInfo) : void
{
match (info.Node)
{
| TExpr.PropertyMember as e =>
def propertyRef = Environment.LookupAstPropertySymbol(e.prop);
when (propertyRef != null)
{
def nodesMap = nodesMap;
def key = toKey(e);
mutable to;
unless (nodesMap.TryGetValue(key, out to))
{
to = Node.UseProp(e, propertyRef);
nodesMap[key] = to;
}
node.DependendOn.Add(to);
}
| TExpr.Delayed =>
// мы не можем производить преобразование, если у нас остались объкты отложенной типизации
assert(false);
| _ => ()
}
}
walker.Walk(expr, walk);
}
def addKey(assign : TExpr.Assign, debug : TExpr = null) : void
{
match (assign.target)
{
| TExpr.PropertyMember as e =>
def propertyRef = Environment.LookupAstPropertySymbol(e.prop);
if (propertyRef != null)
{
def key = toKey(e);
mutable existingNode;
if (nodesMap.TryGetValue(key, out existingNode))
{
Message.Warning(existingNode.Location, "Related message: First assingment of dependent property.");
Message.FatalError(e.Location, "Multiple assign of dependent property.");
}
else
{
def node = Node.AssignProp(assign, debug, e, propertyRef);
nodesMap[key] = node;
}
}
else
Message.FatalError(e.Location, "You can assign only a dependent property.");
| TExpr.Delayed => assert(false);
| _ => Message.FatalError(assign.target.Location, "You can assign only a dependent property.");
}
}
def processAssignProp(assign : TExpr.Assign) : void
{
match (assign.target)
{
| TExpr.PropertyMember as e =>
def propertyRef = Environment.LookupAstPropertySymbol(e.prop);
if (propertyRef != null)
{
when (propertyRef.Symbol.Direction == DependentPropertyDirection.In && e.obj is TExpr.This)
{
Message.FatalError(e.Location, "Assignment of input dependent property within its declaration is not allowed.");
}
def nodesMap = nodesMap;
def key = toKey(e);
def node = nodesMap[key] :> Node.AssignProp;
addNodesDependentOnAssignedProperty(assign.source, node);
}
else
Message.FatalError(e.Location, "You can assign only a dependent property.");
| TExpr.Delayed => assert(false);
| _ => Message.FatalError(assign.target.Location, "You can assign only a dependent property.");
}
}
def addAssigns(expr : TExpr, debug : TExpr = null) : void
{
match (expr)
{
| TExpr.Delayed => assert(false);
| TExpr.DebugInfo as e => addAssigns(e.expr, e)
| TExpr.Sequence as e => addAssigns(e.e1); addAssigns(e.e2);
| TExpr.Assign as e => addKey(e, debug);
| e => ErrorUnexpectedExpr(e)
}
}
def calcDependents(expr : TExpr) : void
{
| TExpr.Delayed => assert(false);
| TExpr.DebugInfo as e => calcDependents(e.expr)
| TExpr.Sequence as e => calcDependents(e.e1); calcDependents(e.e2);
| TExpr.Assign as e => processAssignProp(e);
| e => ErrorUnexpectedExpr(e)
}
addAssigns(expr);
calcDependents(expr);
nodesMap
}
private static AddDependencyOnAstProperties(dependencyGraph : Seq[Node], declaredProperties : Seq[IProperty]) : Seq[Node]
{
def declaredPropNodes = SCG.List();
foreach (p in declaredProperties)
declaredPropNodes.Add(Node.DeclaredProp(p));
def newDependencyGraph = SCG.List(dependencyGraph);
newDependencyGraph.AddRange(declaredPropNodes);
def getRootProp(expr : TExpr) : IProperty
{
| TExpr.PropertyMember as p => if (p.obj is TExpr.Base || p.obj is TExpr.This) p.prop else getRootProp(p.obj)
| _ => Message.FatalError(expr.Location, "Properties must only be used.")
}
//Node.Visualize(nodesMap.Values, "После добавления Node.DeclaredProp()");
def synthesizedProps = newDependencyGraph.OfType.[Node.UseProp]();
foreach (synthesizedProp in synthesizedProps)
{
def prop = getRootProp(synthesizedProp.Expr);
foreach (astProp in declaredPropNodes)
when (prop : object == astProp.Prop)
synthesizedProp.DependendOn.Add(astProp);
}
//visualize(": После добавления зависимостей с синтизируемых свойств");
def inheritedProps = newDependencyGraph.OfType.[Node.AssignProp]();
foreach (inheritedProp in inheritedProps)
{
def prop = getRootProp(inheritedProp.Expr.target);
foreach (astProp in declaredPropNodes)
when (prop : object == astProp.Prop)
astProp.DependendOn.Add(inheritedProp);
}
//Node.Visualize(nodesMap.Values, "После добавления зависимостей на наследуемые свойства");
def cycled2 = Node.Sort(newDependencyGraph);
when (cycled2)
{
foreach (astProp when astProp.State == NodeState.Cycling in declaredPropNodes)
_ = astProp.DependendOn.RemoveAll(inheritedProp => inheritedProp.State == NodeState.Cycling);
}
def cycled3 = Node.Sort(newDependencyGraph);
//visualize(": После удаления ЗАЦИКЛИВАЮЩИХСЯ зависимостей на наследуемые свойства");
assert2(!cycled3);
newDependencyGraph
}
private GenerateCode(tb : TypeBuilder, dependencyGraph : Seq[Node]) : PExpr
{
def orderedNodes = dependencyGraph.ToArray();
Array.Sort(orderedNodes, (l, r) => l.Order - r.Order);
//Node.Visualize(nodesMap.Values, typeBuilder.Name);
// Rendering code
def result = SCG.List();
result.Add(<[ _ = context ]>);
foreach (node in orderedNodes)
{
| AssignProp as a =>
def code =
if (a.DependendOn.Count > 0)
{
def conditions = a.DependendOn.Fold(<[ true ]>, (p, acc) => <[ $acc && $(GenerateHasValueCheck(p.Obj, p.PropertyRef)) ]>);
<[
unless ($(GenerateHasValueCheck(a.Obj, a.PropertyRef)))
if ($conditions)
{
$(a.Debug ?? a.Expr : typed);
context.CalculatedCountInc();
}
else
context.DeferredCountInc();
]>
}
else
{
<[
unless ($(GenerateHasValueCheck(a.Obj, a.PropertyRef)))
{
$(a.Expr : typed);
context.CalculatedCountInc();
}
]>
};
result.Add(code);
| UseProp => ()
| DeclaredProp(p) =>
def propertyType = tb.GetMemType().TypeOfMember(p);
when (propertyType.TryRequire(Environment.AstTypeVar))
result.Add(<[ this.$(p.Name : global).EvalProperties(context) ]>);
}
def code = <[ { ..$result } ]>;
code
}
private static GenerateHasValueCheck(obj : TExpr, propertyRef : DependentAstPropertyRef) : PExpr
{
GenerateHasValueCheck(<[ $(obj : typed) ]>, propertyRef)
}
private static GenerateHasValueCheck(obj : PExpr, propertyRef : DependentAstPropertyRef) : PExpr
{
match (propertyRef)
{
| Compiling(bit) when obj is <[ this ]> => bit.Read()
| _ when propertyRef.Index >= 0 => <[ $obj.IsPropertyEvaluated($(propertyRef.Index : int)) ]>
| _ => <[ $obj.$(GetIsEvaluatedPropertyName(propertyRef.Symbol) : usesite) ]>
}
}
}
}