-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathRuleProcessor.CollectionProcessing.cs
More file actions
559 lines (460 loc) · 27 KB
/
RuleProcessor.CollectionProcessing.cs
File metadata and controls
559 lines (460 loc) · 27 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
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
// -------------------------------------------------------------------------------------------------
// <copyright file="RuleProcessor.CollectionProcessing.cs" company="Starion Group S.A.">
//
// Copyright 2022-2026 Starion Group S.A.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// </copyright>
// ------------------------------------------------------------------------------------------------
namespace SysML2.NET.CodeGenerator.HandleBarHelpers
{
using System;
using System.Collections.Generic;
using System.Linq;
using HandlebarsDotNet;
using SysML2.NET.CodeGenerator.Extensions;
using SysML2.NET.CodeGenerator.Grammar.Model;
using uml4net.Classification;
using uml4net.CommonStructure;
using uml4net.Extensions;
using uml4net.StructuredClassifiers;
/// <summary>
/// Collection loop emission, type resolution, and optional condition logic
/// </summary>
internal sealed partial class RuleProcessor
{
/// <summary>
/// Emits a while loop for a collection non-terminal.
/// </summary>
private void EmitCollectionNonTerminalLoop(EncodedTextWriter writer, IClass umlClass, NonTerminalElement nonTerminalElement, TextualNotationRule referencedRule, string typeTarget, RuleGenerationContext ruleGenerationContext)
{
if (referencedRule != null)
{
var collectionPropertyNames = referencedRule.QueryCollectionPropertyNames(ruleGenerationContext.AllRules);
if (collectionPropertyNames.Count == 1)
{
var propertyName = collectionPropertyNames.Single();
var allProperties = umlClass.QueryAllProperties();
var targetProperty = allProperties.SingleOrDefault(x => string.Equals(x.Name, propertyName, StringComparison.OrdinalIgnoreCase));
if (targetProperty != null && targetProperty.QueryIsEnumerable())
{
var existingCursor = ruleGenerationContext.DefinedCursors.SingleOrDefault(x => x.IsCursorValidForProperty(targetProperty));
string cursorVariableName;
if (existingCursor != null)
{
cursorVariableName = existingCursor.CursorVariableName;
}
else
{
var cursorDefinition = new CursorDefinition { DefinedForProperty = targetProperty };
var propertyAccessName = targetProperty.QueryPropertyNameBasedOnUmlProperties();
writer.WriteSafeString($"var {cursorDefinition.CursorVariableName} = writerContext.CursorCache.GetOrCreateCursor({ruleGenerationContext.CurrentVariableName}.Id, \"{targetProperty.Name}\", {ruleGenerationContext.CurrentVariableName}.{propertyAccessName});{Environment.NewLine}");
ruleGenerationContext.DefinedCursors.Add(cursorDefinition);
cursorVariableName = cursorDefinition.CursorVariableName;
}
var perItemCall = this.ResolveBuilderCall(umlClass, nonTerminalElement, typeTarget, ruleGenerationContext);
var whileTypeExclusion = this.ResolveCollectionWhileTypeCondition(cursorVariableName, umlClass, referencedRule, ruleGenerationContext);
string whileCondition;
if (!string.IsNullOrWhiteSpace(whileTypeExclusion))
{
whileCondition = whileTypeExclusion;
}
else
{
var allElements = referencedRule?.Alternatives.SelectMany(alt => alt.Elements).ToList();
var hasNonAssignmentElements = allElements?.Any(element =>
element is NonTerminalElement or GroupElement) == true;
List<string> assignmentTargetTypes = null;
if (!hasNonAssignmentElements)
{
assignmentTargetTypes = allElements?
.OfType<AssignmentElement>()
.Where(assignmentElement => assignmentElement.Operator == "+=" && assignmentElement.Value is NonTerminalElement)
.Select(assignmentElement =>
{
var valueNonTerminal = (NonTerminalElement)assignmentElement.Value;
var refRule = ruleGenerationContext.FindRule(valueNonTerminal.Name);
var targetName = refRule != null ? refRule.EffectiveTarget : null;
if (targetName != null)
{
var targetClass = RuleQueryUtilities.FindClass(umlClass.Cache, targetName);
return targetClass?.QueryFullyQualifiedTypeName();
}
return null;
})
.Where(typeName => typeName != null)
.Distinct()
.ToList();
}
if (assignmentTargetTypes?.Count == 1)
{
var contentTypeGuard = this.ResolveContentTypeGuard(cursorVariableName, referencedRule, propertyName, umlClass, ruleGenerationContext);
if (!string.IsNullOrWhiteSpace(contentTypeGuard))
{
whileCondition = contentTypeGuard;
}
else
{
whileCondition = $"{cursorVariableName}.Current != null && {cursorVariableName}.Current is {assignmentTargetTypes[0]}";
}
}
else
{
whileCondition = $"{cursorVariableName}.Current != null";
}
}
if (perItemCall != null)
{
writer.WriteSafeString($"while ({whileCondition}){Environment.NewLine}");
writer.WriteSafeString($"{{{Environment.NewLine}");
writer.WriteSafeString(perItemCall);
writer.WriteSafeString($"{Environment.NewLine}}}{Environment.NewLine}");
}
else
{
writer.WriteSafeString($"while ({whileCondition}){Environment.NewLine}");
writer.WriteSafeString($"{{{Environment.NewLine}");
var previousCaller = ruleGenerationContext.CallerRule;
var previousName = ruleGenerationContext.CurrentVariableName;
ruleGenerationContext.CallerRule = nonTerminalElement;
this.ProcessAlternatives(writer, umlClass, referencedRule.Alternatives, ruleGenerationContext);
ruleGenerationContext.CallerRule = previousCaller;
ruleGenerationContext.CurrentVariableName = previousName;
writer.WriteSafeString($"{Environment.NewLine}}}{Environment.NewLine}");
}
return;
}
}
}
var handCodedRuleName = nonTerminalElement.TextualNotationRule?.RuleName ?? nonTerminalElement.Name;
this.EmitHandCodedFallback(writer, handCodedRuleName, ruleGenerationContext, true);
writer.WriteSafeString(Environment.NewLine);
}
/// <summary>
/// Resolves the type condition for a collection while loop.
/// </summary>
private string ResolveCollectionWhileTypeCondition(string cursorVariableName, IClass umlClass, TextualNotationRule collectionRule, RuleGenerationContext ruleGenerationContext)
{
var siblings = ruleGenerationContext.CurrentSiblingElements;
var currentIndex = ruleGenerationContext.CurrentElementIndex;
if (siblings == null || currentIndex + 1 >= siblings.Count)
{
return "";
}
if (collectionRule != null)
{
var allElements = collectionRule.Alternatives.SelectMany(alternative => alternative.Elements).ToList();
var assignmentNonTerminals = allElements
.OfType<AssignmentElement>()
.Where(assignment => assignment.Operator == "+=")
.Select(assignment => assignment.Value)
.OfType<NonTerminalElement>()
.ToList();
var hasOnlyAssignments = allElements.All(element => element is AssignmentElement or NonParsingAssignmentElement);
if (assignmentNonTerminals.Count > 0 && hasOnlyAssignments)
{
var itemRule = ruleGenerationContext.FindRule(assignmentNonTerminals[0].Name);
var itemTypeTarget = itemRule != null ? itemRule.EffectiveTarget : null;
if (itemTypeTarget != null)
{
var itemTargetClass = umlClass.Cache.Values.OfType<INamedElement>()
.SingleOrDefault(x => x.Name == itemTypeTarget) as IClass;
if (itemTargetClass != null)
{
return $"{cursorVariableName}.Current is {itemTargetClass.QueryFullyQualifiedTypeName()}";
}
}
}
}
var nextSibling = siblings[currentIndex + 1];
NonTerminalElement nextNonTerminal = null;
switch (nextSibling)
{
case NonTerminalElement nonTerminal:
nextNonTerminal = nonTerminal;
break;
case AssignmentElement { Value: NonTerminalElement assignmentNonTerminal }:
nextNonTerminal = assignmentNonTerminal;
break;
case GroupElement groupElement:
nextNonTerminal = groupElement.Alternatives
.SelectMany(alternative => alternative.Elements)
.OfType<AssignmentElement>()
.Select(assignment => assignment.Value)
.OfType<NonTerminalElement>()
.FirstOrDefault();
break;
}
if (nextNonTerminal == null)
{
return "";
}
var nextRule = ruleGenerationContext.FindRule(nextNonTerminal.Name);
var nextTypeTarget = nextRule != null ? nextRule.EffectiveTarget : null;
if (nextTypeTarget == null)
{
return "";
}
var nextTargetClass = umlClass.Cache.Values.OfType<INamedElement>()
.SingleOrDefault(x => x.Name == nextTypeTarget) as IClass;
if (nextTargetClass == null)
{
return "";
}
return $"{cursorVariableName}.Current is not null and not {nextTargetClass.QueryFullyQualifiedTypeName()}";
}
/// <summary>
/// Resolves a content-aware type guard for collection while loops.
/// </summary>
private string ResolveContentTypeGuard(string cursorVariableName, TextualNotationRule referencedRule, string outerPropertyName, IClass umlClass, RuleGenerationContext ruleGenerationContext)
{
if (referencedRule == null)
{
return null;
}
var outerTargetName = referencedRule.EffectiveTarget;
var outerTargetClass = RuleQueryUtilities.FindClass(umlClass.Cache, outerTargetName);
if (outerTargetClass == null)
{
return null;
}
var allClassesInHierarchy = new List<IClass> { outerTargetClass };
allClassesInHierarchy.AddRange(outerTargetClass.QueryAllGeneralClassifiers().OfType<IClass>());
var compositeProperties = allClassesInHierarchy
.SelectMany(c => c.OwnedAttribute)
.Where(p => p.IsComposite && !p.IsDerived)
.ToList();
var complementaryProperty = compositeProperties
.FirstOrDefault(p => !string.Equals(p.Name, outerPropertyName, StringComparison.OrdinalIgnoreCase));
if (complementaryProperty == null)
{
var samePropertyAssignment = referencedRule.Alternatives
.SelectMany(alt => alt.Elements)
.OfType<AssignmentElement>()
.FirstOrDefault(a => (a.Operator == "+=" || a.Operator == "=")
&& string.Equals(a.Property, outerPropertyName, StringComparison.OrdinalIgnoreCase)
&& a.Value is NonTerminalElement);
if (samePropertyAssignment?.Value is NonTerminalElement innerNonTerminal)
{
var innerRule = ruleGenerationContext.FindRule(innerNonTerminal.Name);
if (innerRule != null)
{
return this.ResolveContentTypeGuard(cursorVariableName, innerRule, outerPropertyName, umlClass, ruleGenerationContext);
}
}
return null;
}
var contentAssignment = referencedRule.Alternatives
.SelectMany(alt => alt.Elements)
.OfType<AssignmentElement>()
.FirstOrDefault(a => (a.Operator == "+=" || a.Operator == "=")
&& string.Equals(a.Property, complementaryProperty.Name, StringComparison.OrdinalIgnoreCase)
&& a.Value is NonTerminalElement);
if (contentAssignment == null)
{
return null;
}
var contentNonTerminal = (NonTerminalElement)contentAssignment.Value;
var contentRule = ruleGenerationContext.FindRule(contentNonTerminal.Name);
var contentTargetName = contentRule != null
? contentRule.EffectiveTarget
: contentNonTerminal.Name;
var contentTargetClass = RuleQueryUtilities.FindClass(umlClass.Cache, contentTargetName);
if (contentTargetClass == null)
{
return null;
}
var outerTypeName = outerTargetClass.QueryFullyQualifiedTypeName();
var contentTypeName = contentTargetClass.QueryFullyQualifiedTypeName();
var complementaryAccessor = complementaryProperty.QueryPropertyNameBasedOnUmlProperties();
var guardVarName = $"{outerTargetClass.Name.LowerCaseFirstLetter()}Guard";
return $"{cursorVariableName}.Current is {outerTypeName} {guardVarName} && {guardVarName}.{complementaryAccessor}.OfType<{contentTypeName}>().Any()";
}
/// <summary>
/// Resolves the builder method call string for a non-terminal element.
/// </summary>
private string ResolveBuilderCall(IClass umlClass, NonTerminalElement nonTerminalElement, string typeTarget, RuleGenerationContext ruleGenerationContext)
{
if (typeTarget == ruleGenerationContext.NamedElementToGenerate.Name)
{
return $"Build{nonTerminalElement.Name}({ruleGenerationContext.CurrentVariableName}, writerContext, stringBuilder);";
}
var targetType = RuleQueryUtilities.FindNamedElement(umlClass.Cache, typeTarget);
if (targetType is IClass targetClass)
{
if (umlClass.QueryAllGeneralClassifiers().Contains(targetClass))
{
return $"{targetType.Name}TextualNotationBuilder.Build{nonTerminalElement.Name}({ruleGenerationContext.CurrentVariableName}, writerContext, stringBuilder);";
}
return null;
}
return $"Build{nonTerminalElement.Name}({ruleGenerationContext.CurrentVariableName}, writerContext, stringBuilder);";
}
/// <summary>
/// Generates an inline condition expression for an optional non-terminal reference.
/// For enumerable properties whose consumption type can be resolved from the referenced
/// rule's <c>+=</c> assignments, emits a cursor-typed guard
/// (<c>{prop}Cursor.Current is T</c>) — declaring the cursor immediately into
/// <paramref name="writer" /> when not already present in
/// <see cref="RuleGenerationContext.DefinedCursors" />. The cursor principle aligns the
/// caller's guard with the position the called rule will actually consume from. When the
/// type cannot be resolved or <paramref name="variableName"/> is not the top-level
/// <c>poco</c>, the legacy <c>{var}.{Property}.Count != 0</c> form is preserved.
/// </summary>
/// <param name="writer">The <see cref="EncodedTextWriter" /> used to emit any required cursor declarations</param>
/// <param name="referencedRule">The optional non-terminal's referenced rule</param>
/// <param name="targetClass">The host class (provides UML metadata)</param>
/// <param name="ruleGenerationContext">The current <see cref="RuleGenerationContext" /></param>
/// <param name="variableName">The variable name from which the property is accessed (typically <c>poco</c>)</param>
/// <returns>The condition expression, or <c>null</c> when no property names are referenced</returns>
private string GenerateInlineOptionalCondition(EncodedTextWriter writer, TextualNotationRule referencedRule, IClass targetClass, RuleGenerationContext ruleGenerationContext, string variableName)
{
var propertyNames = referencedRule.QueryAllReferencedPropertyNames(ruleGenerationContext.AllRules);
if (propertyNames.Count == 0)
{
return null;
}
var allProperties = targetClass.QueryAllProperties();
var conditionParts = new List<string>();
foreach (var propertyName in propertyNames)
{
var property = allProperties.FirstOrDefault(x => string.Equals(x.Name, propertyName, StringComparison.OrdinalIgnoreCase));
if (property == null)
{
continue;
}
var umlPropertyName = property.QueryPropertyNameBasedOnUmlProperties();
if (property.QueryIsEnumerable())
{
var cursorTypedCheck = TryBuildCursorTypedCheck(writer, referencedRule, targetClass, property, propertyName, ruleGenerationContext, variableName);
if (cursorTypedCheck != null)
{
conditionParts.Add(cursorTypedCheck);
}
else if (referencedRule.QueryAllReferencedCollectionAssignments(propertyName, ruleGenerationContext.AllRules).Count > 0)
{
// The referenced rule has += consumptions of this property but the cursor
// types could not be resolved — fall back to the legacy collection-level
// non-empty check rather than skip the clause entirely.
conditionParts.Add($"{variableName}.{umlPropertyName}.Count != 0");
}
// No += consumptions exist for this property anywhere in the referenced rule
// tree (the property name reached the result set via a scalar `=` reference,
// typically pulled in by a transitive non-terminal walk). Skipping the clause
// tightens the guard to reflect what the called rule will actually consume
// and avoids evaluating derived properties that the caller never reads.
}
else
{
conditionParts.Add(property.QueryIfStatementContentForNonEmpty(variableName));
}
}
return conditionParts.Count != 0 ? string.Join(" || ", conditionParts) : null;
}
/// <summary>
/// Resolves the runtime types the referenced rule's <c>+=</c> assignments consume from the
/// supplied <paramref name="property" /> and, when all are resolvable AND
/// <paramref name="variableName" /> is <c>poco</c>, returns a cursor-typed boolean
/// expression (declaring or reusing a cursor as needed). Returns <c>null</c> to signal
/// that the caller should fall back to the legacy <c>.Count != 0</c> form.
/// </summary>
/// <param name="writer">The <see cref="EncodedTextWriter" /> used to emit a cursor declaration when one is required</param>
/// <param name="referencedRule">The optional non-terminal's referenced rule</param>
/// <param name="targetClass">The host class (provides the UML cache for class-name resolution)</param>
/// <param name="property">The host class property targeted by the rule's <c>+=</c> consumptions</param>
/// <param name="propertyName">The matching grammar property name</param>
/// <param name="ruleGenerationContext">The current <see cref="RuleGenerationContext" /></param>
/// <param name="variableName">The variable name the host method uses for the POCO</param>
/// <returns>The cursor-typed boolean expression, or <c>null</c> if the legacy fallback should be used</returns>
private static string TryBuildCursorTypedCheck(EncodedTextWriter writer, TextualNotationRule referencedRule, IClass targetClass, IProperty property, string propertyName, RuleGenerationContext ruleGenerationContext, string variableName)
{
if (!string.Equals(variableName, "poco", StringComparison.Ordinal))
{
return null;
}
var collectionAssignments = referencedRule.QueryAllReferencedCollectionAssignments(propertyName, ruleGenerationContext.AllRules);
if (collectionAssignments.Count == 0)
{
return null;
}
var resolvedTypeNames = new List<string>();
foreach (var assignmentElement in collectionAssignments)
{
var typeName = ResolveAssignmentTargetTypeName(assignmentElement, targetClass, ruleGenerationContext);
if (typeName == null)
{
return null;
}
if (!resolvedTypeNames.Contains(typeName))
{
resolvedTypeNames.Add(typeName);
}
}
var cursorVariableName = EnsureCursorDeclared(writer, property, ruleGenerationContext);
if (resolvedTypeNames.Count == 1)
{
return $"{cursorVariableName}.Current is {resolvedTypeNames[0]}";
}
var typeChecks = resolvedTypeNames.Select(typeName => $"{cursorVariableName}.Current is {typeName}");
return $"({string.Join(" || ", typeChecks)})";
}
/// <summary>
/// Returns the cursor variable name for <paramref name="property" />, reusing an
/// already-declared cursor when one is present in
/// <see cref="RuleGenerationContext.DefinedCursors" /> and emitting a new declaration into
/// <paramref name="writer" /> otherwise. The new declaration is registered in
/// <see cref="RuleGenerationContext.DefinedCursors" /> so subsequent host-rule elements
/// targeting the same property reuse it.
/// </summary>
/// <param name="writer">The <see cref="EncodedTextWriter" /> that receives the cursor declaration line when emitted</param>
/// <param name="property">The property whose cursor is needed</param>
/// <param name="ruleGenerationContext">The current <see cref="RuleGenerationContext" /></param>
/// <returns>The cursor variable name to use in the guard expression</returns>
private static string EnsureCursorDeclared(EncodedTextWriter writer, IProperty property, RuleGenerationContext ruleGenerationContext)
{
var existingCursor = ruleGenerationContext.DefinedCursors.FirstOrDefault(x => x.IsCursorValidForProperty(property));
if (existingCursor != null)
{
return existingCursor.CursorVariableName;
}
var cursorDefinition = new CursorDefinition { DefinedForProperty = property };
var propertyAccessName = property.QueryPropertyNameBasedOnUmlProperties();
writer.WriteSafeString($"var {cursorDefinition.CursorVariableName} = writerContext.CursorCache.GetOrCreateCursor(poco.Id, \"{property.Name}\", poco.{propertyAccessName});{Environment.NewLine}");
ruleGenerationContext.DefinedCursors.Add(cursorDefinition);
return cursorDefinition.CursorVariableName;
}
/// <summary>
/// Emits an optional condition wrapping block for an optional NonTerminal element.
/// </summary>
private bool TryEmitOptionalCondition(EncodedTextWriter writer, NonTerminalElement nonTerminalElement, TextualNotationRule referencedRule, IClass targetClass, RuleGenerationContext ruleGenerationContext, string variableName)
{
if (!nonTerminalElement.IsOptional || nonTerminalElement.IsCollection)
{
return false;
}
if (referencedRule == null)
{
return false;
}
var condition = this.GenerateInlineOptionalCondition(writer, referencedRule, targetClass, ruleGenerationContext, variableName);
if (condition == null)
{
return false;
}
writer.WriteSafeString($"{Environment.NewLine}if ({condition}){Environment.NewLine}");
writer.WriteSafeString($"{{{Environment.NewLine}");
return true;
}
}
}