-
Notifications
You must be signed in to change notification settings - Fork 214
/
CommonLanguageRefiner.cs
1559 lines (1509 loc) · 83.9 KB
/
CommonLanguageRefiner.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
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
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Kiota.Builder.CodeDOM;
using Kiota.Builder.Configuration;
using Kiota.Builder.Extensions;
namespace Kiota.Builder.Refiners;
public abstract class CommonLanguageRefiner : ILanguageRefiner
{
protected static readonly char[] UnderscoreArray = new[] { '_' };
protected CommonLanguageRefiner(GenerationConfiguration configuration)
{
ArgumentNullException.ThrowIfNull(configuration);
_configuration = configuration;
}
public abstract Task Refine(CodeNamespace generatedCode, CancellationToken cancellationToken);
/// <summary>
/// This method adds the imports for the default serializers and deserializers to the api client class.
/// It also updates the module names to replace the fully qualified class name by the class name without the namespace.
/// </summary>
protected void AddSerializationModulesImport(CodeElement generatedCode, string[]? serializationWriterFactoryInterfaceAndRegistrationFullName = default, string[]? parseNodeFactoryInterfaceAndRegistrationFullName = default, char separator = '.')
{
serializationWriterFactoryInterfaceAndRegistrationFullName ??= Array.Empty<string>();
parseNodeFactoryInterfaceAndRegistrationFullName ??= Array.Empty<string>();
if (generatedCode is CodeMethod currentMethod &&
currentMethod.IsOfKind(CodeMethodKind.ClientConstructor) &&
currentMethod.Parent is CodeClass currentClass &&
currentClass.StartBlock is ClassDeclaration declaration)
{
var cumulatedSymbols = currentMethod.DeserializerModules
.Union(currentMethod.SerializerModules)
.Union(serializationWriterFactoryInterfaceAndRegistrationFullName)
.Union(parseNodeFactoryInterfaceAndRegistrationFullName)
.Where(x => !string.IsNullOrEmpty(x))
.ToList();
currentMethod.DeserializerModules = currentMethod.DeserializerModules.Select(x => x.Split(separator).Last()).ToHashSet(StringComparer.OrdinalIgnoreCase);
currentMethod.SerializerModules = currentMethod.SerializerModules.Select(x => x.Split(separator).Last()).ToHashSet(StringComparer.OrdinalIgnoreCase);
declaration.AddUsings(cumulatedSymbols.Select(x => new CodeUsing
{
Name = x.Split(separator).Last(),
Declaration = new CodeType
{
Name = x.Split(separator).SkipLast(1).Aggregate((x, y) => $"{x}{separator}{y}"),
IsExternal = true,
}
}).ToArray());
return;
}
CrawlTree(generatedCode, x => AddSerializationModulesImport(x, serializationWriterFactoryInterfaceAndRegistrationFullName, parseNodeFactoryInterfaceAndRegistrationFullName, separator));
}
protected static void ReplaceDefaultSerializationModules(CodeElement generatedCode, HashSet<string> defaultValues, HashSet<string> newModuleNames)
{
ArgumentNullException.ThrowIfNull(defaultValues);
if (ReplaceSerializationModules(generatedCode, static x => x.SerializerModules, (x, y) => x.SerializerModules = y, defaultValues, newModuleNames))
return;
CrawlTree(generatedCode, x => ReplaceDefaultSerializationModules(x, defaultValues, newModuleNames));
}
protected static void ReplaceDefaultDeserializationModules(CodeElement generatedCode, HashSet<string> defaultValues, HashSet<string> newModuleNames)
{
ArgumentNullException.ThrowIfNull(defaultValues);
if (ReplaceSerializationModules(generatedCode, static x => x.DeserializerModules, (x, y) => x.DeserializerModules = y, defaultValues, newModuleNames))
return;
CrawlTree(generatedCode, x => ReplaceDefaultDeserializationModules(x, defaultValues, newModuleNames));
}
private static bool ReplaceSerializationModules(CodeElement generatedCode, Func<CodeMethod, HashSet<string>> propertyGetter, Action<CodeMethod, HashSet<string>> propertySetter, HashSet<string> initialNames, HashSet<string> moduleNames)
{
if (generatedCode is CodeMethod currentMethod &&
currentMethod.IsOfKind(CodeMethodKind.ClientConstructor))
{
var modules = propertyGetter.Invoke(currentMethod);
if (modules.Count == initialNames.Count &&
modules.All(initialNames.Contains))
{
propertySetter.Invoke(currentMethod, moduleNames);
return true;
}
}
return false;
}
protected static void CorrectCoreTypesForBackingStore(CodeElement currentElement, string defaultPropertyValue, bool hasPrefix = true)
{
if (currentElement is CodeClass currentClass && currentClass.IsOfKind(CodeClassKind.Model, CodeClassKind.RequestBuilder)
&& currentClass.StartBlock is ClassDeclaration currentDeclaration)
{
var backedModelImplements = currentDeclaration.Implements.FirstOrDefault(x => "IBackedModel".Equals(x.Name, StringComparison.OrdinalIgnoreCase));
if (backedModelImplements != null)
backedModelImplements.Name = backedModelImplements.Name[1..]; //removing the "I"
var backingStoreProperty = currentClass.GetPropertyOfKind(CodePropertyKind.BackingStore);
if (backingStoreProperty != null)
{
backingStoreProperty.DefaultValue = defaultPropertyValue;
backingStoreProperty.NamePrefix = hasPrefix ? backingStoreProperty.NamePrefix : string.Empty;
}
}
CrawlTree(currentElement, x => CorrectCoreTypesForBackingStore(x, defaultPropertyValue, hasPrefix));
}
private static bool DoesAnyParentHaveAPropertyWithDefaultValue(CodeClass current)
{
if (current.StartBlock is ClassDeclaration currentDeclaration &&
currentDeclaration.Inherits?.TypeDefinition is CodeClass parentClass)
{
if (parentClass.Properties.Any(static x => !string.IsNullOrEmpty(x.DefaultValue)))
return true;
return DoesAnyParentHaveAPropertyWithDefaultValue(parentClass);
}
return false;
}
protected static void CorrectNames(CodeElement current, Func<string, string> refineName,
bool classNames = true,
bool enumNames = true)
{
ArgumentNullException.ThrowIfNull(refineName);
if (current is CodeClass currentClass && classNames &&
refineName(currentClass.Name) is string refinedClassName &&
!currentClass.Name.Equals(refinedClassName, StringComparison.Ordinal) &&
currentClass.Parent is IBlock parentBlock)
{
parentBlock.RenameChildElement(currentClass.Name, refinedClassName);
}
else if (current is CodeEnum currentEnum &&
enumNames &&
refineName(currentEnum.Name) is string refinedEnumName &&
!currentEnum.Name.Equals(refinedEnumName, StringComparison.Ordinal) &&
currentEnum.Parent is IBlock parentBlock2)
{
parentBlock2.RenameChildElement(currentEnum.Name, refinedEnumName);
}
CrawlTree(current, x => CorrectNames(x, refineName));
}
protected static void ReplacePropertyNames(CodeElement current, HashSet<CodePropertyKind> propertyKindsToReplace, Func<string, string> refineAccessorName)
{
ArgumentNullException.ThrowIfNull(refineAccessorName);
if (propertyKindsToReplace is null || propertyKindsToReplace.Count == 0) return;
if (current is CodeProperty currentProperty &&
!currentProperty.ExistsInBaseType &&
propertyKindsToReplace!.Contains(currentProperty.Kind) &&
current.Parent is CodeClass parentClass &&
currentProperty.Access == AccessModifier.Public)
{
var refinedName = refineAccessorName(currentProperty.Name);
if (!refinedName.Equals(currentProperty.Name, StringComparison.Ordinal) &&
!parentClass.Properties.Any(property => !currentProperty.Name.Equals(property.Name, StringComparison.Ordinal) &&
refinedName.Equals(property.Name, StringComparison.OrdinalIgnoreCase)))// ensure the refinement won't generate a duplicate
{
if (string.IsNullOrEmpty(currentProperty.SerializationName))
currentProperty.SerializationName = currentProperty.Name;
parentClass.RenameChildElement(currentProperty.Name, refinedName);
}
}
CrawlTree(current, x => ReplacePropertyNames(x, propertyKindsToReplace!, refineAccessorName));
}
protected static void AddGetterAndSetterMethods(CodeElement current, HashSet<CodePropertyKind> propertyKindsToAddAccessors, Func<CodeElement, string, string> refineAccessorName, bool removeProperty, bool parameterAsOptional, string getterPrefix, string setterPrefix, string fieldPrefix = "_", AccessModifier propertyAccessModifier = AccessModifier.Private)
{
ArgumentNullException.ThrowIfNull(refineAccessorName);
var isSetterPrefixEmpty = string.IsNullOrEmpty(setterPrefix);
var isGetterPrefixEmpty = string.IsNullOrEmpty(getterPrefix);
if (propertyKindsToAddAccessors is null || propertyKindsToAddAccessors.Count == 0) return;
if (current is CodeProperty currentProperty &&
!currentProperty.ExistsInBaseType &&
propertyKindsToAddAccessors!.Contains(currentProperty.Kind) &&
current.Parent is CodeClass parentClass &&
!parentClass.IsOfKind(CodeClassKind.QueryParameters))
{
if (removeProperty && currentProperty.IsOfKind(CodePropertyKind.Custom, CodePropertyKind.AdditionalData)) // we never want to remove backing stores
parentClass.RemoveChildElement(currentProperty);
else
{
currentProperty.Access = propertyAccessModifier;
if (!string.IsNullOrEmpty(fieldPrefix))
currentProperty.NamePrefix = fieldPrefix;
}
var accessorName = refineAccessorName(current, currentProperty.Name.ToFirstCharacterUpperCase());
currentProperty.Getter = parentClass.AddMethod(new CodeMethod
{
Name = $"{(isGetterPrefixEmpty ? "get-" : getterPrefix)}{accessorName}",
Access = AccessModifier.Public,
IsAsync = false,
Kind = CodeMethodKind.Getter,
ReturnType = (CodeTypeBase)currentProperty.Type.Clone(),
Documentation = new(currentProperty.Documentation.TypeReferences.ToDictionary(static x => x.Key, static x => x.Value))
{
DescriptionTemplate = $"Gets the {currentProperty.WireName} property value. {currentProperty.Documentation.DescriptionTemplate}",
},
AccessedProperty = currentProperty,
Deprecation = currentProperty.Deprecation,
}).First();
if (isGetterPrefixEmpty)
currentProperty.Getter.Name = $"{getterPrefix}{accessorName}"; // so we don't get an exception for duplicate names when no prefix
currentProperty.Setter = parentClass.AddMethod(new CodeMethod
{
Name = $"{(isSetterPrefixEmpty ? "set-" : setterPrefix)}{accessorName}",
Access = AccessModifier.Public,
IsAsync = false,
Kind = CodeMethodKind.Setter,
Documentation = new(currentProperty.Documentation.TypeReferences.ToDictionary(static x => x.Key, static x => x.Value))
{
DescriptionTemplate = $"Sets the {currentProperty.WireName} property value. {currentProperty.Documentation.DescriptionTemplate}",
},
AccessedProperty = currentProperty,
ReturnType = new CodeType
{
Name = "void",
IsNullable = false,
IsExternal = true,
},
Deprecation = currentProperty.Deprecation,
}).First();
if (isSetterPrefixEmpty)
currentProperty.Setter.Name = $"{setterPrefix}{accessorName}"; // so we don't get an exception for duplicate names when no prefix
currentProperty.Setter.AddParameter(new CodeParameter
{
Name = "value",
Kind = CodeParameterKind.SetterValue,
Documentation = new()
{
DescriptionTemplate = $"Value to set for the {currentProperty.WireName} property.",
},
Optional = parameterAsOptional,
Type = (CodeTypeBase)currentProperty.Type.Clone(),
});
}
CrawlTree(current, x => AddGetterAndSetterMethods(x, propertyKindsToAddAccessors!, refineAccessorName, removeProperty, parameterAsOptional, getterPrefix, setterPrefix, fieldPrefix, propertyAccessModifier));
}
protected static void AddConstructorsForDefaultValues(CodeElement current, bool addIfInherited, bool forceAdd = false, CodeClassKind[]? classKindsToExclude = null)
{
if (current is CodeClass currentClass &&
!currentClass.IsOfKind(CodeClassKind.RequestBuilder, CodeClassKind.QueryParameters) &&
(classKindsToExclude == null || !currentClass.IsOfKind(classKindsToExclude)) &&
(forceAdd ||
currentClass.Properties.Any(static x => !string.IsNullOrEmpty(x.DefaultValue)) ||
addIfInherited && DoesAnyParentHaveAPropertyWithDefaultValue(currentClass)) &&
!currentClass.Methods.Any(x => x.IsOfKind(CodeMethodKind.ClientConstructor)))
currentClass.AddMethod(new CodeMethod
{
Name = "constructor",
Kind = CodeMethodKind.Constructor,
ReturnType = new CodeType
{
Name = "void"
},
IsAsync = false,
Documentation = new(new() {
{ "TypeName", new CodeType() {
IsExternal = false,
TypeDefinition = current,
}}
})
{
DescriptionTemplate = "Instantiates a new {TypeName} and sets the default values.",
},
});
CrawlTree(current, x => AddConstructorsForDefaultValues(x, addIfInherited, forceAdd, classKindsToExclude));
}
protected static void ReplaceReservedModelTypes(CodeElement current, IReservedNamesProvider provider, Func<string, string> replacement) =>
ReplaceReservedNames(current,
provider,
replacement,
codeElementExceptions: new HashSet<Type> { typeof(CodeNamespace) },
shouldReplaceCallback: codeElement => codeElement is CodeClass
|| codeElement is CodeMethod
|| codeElement is CodeEnum codeEnum && provider.ReservedNames.Contains(codeEnum.Name)); // only replace enum type names not enum member names
protected static void ReplaceReservedNamespaceTypeNames(CodeElement current, IReservedNamesProvider provider, Func<string, string> replacement) =>
ReplaceReservedNames(current, provider, replacement, shouldReplaceCallback: codeElement => codeElement is CodeNamespace || codeElement is CodeClass);
private static Func<string, string> CheckReplacementNameIsNotAlreadyInUse(CodeNamespace parentNamespace, CodeElement originalItem, Func<string, string> replacement)
{
var newReplacement = replacement;
var index = 0;
while (true)
{
if (index > 0)
newReplacement = name => $"{replacement(name)}{index}";
if (parentNamespace.FindChildByName<CodeElement>(newReplacement(originalItem.Name), false) is null)
return newReplacement;
index++;
}
}
protected static void ReplaceReservedExceptionPropertyNames(CodeElement current, IReservedNamesProvider provider, Func<string, string> replacement)
{
ReplaceReservedNames(
current,
provider,
replacement,
null,
x => (((x is CodeProperty prop && prop.IsOfKind(CodePropertyKind.Custom)) || x is CodeMethod) && x.Parent is CodeClass parent && parent.IsOfKind(CodeClassKind.Model) && parent.IsErrorDefinition) // rename properties or method of error classes matching the reserved names.
|| (x is CodeClass codeClass && codeClass.IsOfKind(CodeClassKind.Model) && codeClass.IsErrorDefinition
&& codeClass.Properties.FirstOrDefault(classProp => provider.ReservedNames.Contains(classProp.Name)) is { } matchingProperty && matchingProperty.Name.Equals(codeClass.Name, StringComparison.OrdinalIgnoreCase)) // rename the a class if it has a matching property and the class has the same name as the property.
);
}
protected static void ReplaceReservedNames(CodeElement current, IReservedNamesProvider provider, Func<string, string> replacement, HashSet<Type>? codeElementExceptions = null, Func<CodeElement, bool>? shouldReplaceCallback = null)
{
ArgumentNullException.ThrowIfNull(current);
ArgumentNullException.ThrowIfNull(provider);
ArgumentNullException.ThrowIfNull(replacement);
var shouldReplace = shouldReplaceCallback?.Invoke(current) ?? true;
var isNotInExceptions = !codeElementExceptions?.Contains(current.GetType()) ?? true;
if (current is CodeClass currentClass &&
isNotInExceptions &&
shouldReplace &&
currentClass.StartBlock is ClassDeclaration currentDeclaration)
{
replacement = CheckReplacementNameIsNotAlreadyInUse(currentClass.GetImmediateParentOfType<CodeNamespace>(), current, replacement);
// if we are don't have a CodeNamespace exception, the namespace segments are also being replaced
// in the CodeNamespace if-block so we also need to update the using references
if (!codeElementExceptions?.Contains(typeof(CodeNamespace)) ?? true)
ReplaceReservedCodeUsingNamespaceSegmentNames(currentDeclaration, provider, replacement);
// we don't need to rename the inheritance name as it's either external and shouldn't change or it's generated and the code type maps directly to the source
}
else if (current is CodeNamespace currentNamespace &&
isNotInExceptions &&
shouldReplace &&
!string.IsNullOrEmpty(currentNamespace.Name))
ReplaceReservedNamespaceSegments(currentNamespace, provider, replacement);
else if (current is CodeMethod currentMethod &&
isNotInExceptions &&
shouldReplace &&
provider.ReservedNames.Contains(currentMethod.Name) &&
current.Parent is IBlock parentBlock)
{
parentBlock.RenameChildElement(current.Name, replacement.Invoke(currentMethod.Name));
}
// we don't need to property type name as it's either external and shouldn't change or it's generated and the code type maps directly to the source
// Check if the current name meets the following conditions to be replaced
// 1. In the list of reserved names
// 2. If it is a reserved name, make sure that the CodeElement type is worth replacing(not on the blocklist)
// 3. There's not a very specific condition preventing from replacement
if (provider.ReservedNames.Contains(current.Name) &&
isNotInExceptions &&
(shouldReplaceCallback?.Invoke(current) ?? true))// re-invoke the callback if present as conditions above may have renamed dependencies.
{
if (current is CodeProperty currentProperty &&
currentProperty.IsOfKind(CodePropertyKind.Custom) &&
string.IsNullOrEmpty(currentProperty.SerializationName))
{
currentProperty.SerializationName = currentProperty.Name;
}
if (current is CodeEnumOption currentEnumOption &&
string.IsNullOrEmpty(currentEnumOption.SerializationName))
{
currentEnumOption.SerializationName = currentEnumOption.Name;
}
var replacementName = replacement.Invoke(current.Name);
if (current.Parent is IBlock parentBlock)
parentBlock.RenameChildElement(current.Name, replacementName);
else
current.Name = replacementName;
}
CrawlTree(current, x => ReplaceReservedNames(x, provider, replacement, codeElementExceptions, shouldReplaceCallback));
}
private static void ReplaceReservedCodeUsingNamespaceSegmentNames(ClassDeclaration currentDeclaration, IReservedNamesProvider provider, Func<string, string> replacement)
{
// replace the using namespace segment names that are internally defined by the generator
currentDeclaration.Usings
.Where(static codeUsing => codeUsing is { IsExternal: false })
.Select(static codeUsing => new Tuple<CodeUsing, string[]>(codeUsing, codeUsing.Name.Split('.')))
.Where(tuple => tuple.Item2.Any(x => provider.ReservedNames.Contains(x)))
.ToList()
.ForEach(tuple =>
{
tuple.Item1.Name = tuple.Item2.Select(x => provider.ReservedNames.Contains(x) ? replacement.Invoke(x) : x)
.Aggregate(static (x, y) => $"{x}.{y}");
});
}
private static void ReplaceReservedNamespaceSegments(CodeNamespace currentNamespace, IReservedNamesProvider provider, Func<string, string> replacement)
{
var segments = currentNamespace.Name.Split('.');
if (Array.Exists(segments, provider.ReservedNames.Contains) && currentNamespace.Parent is CodeNamespace parentNamespace)
{
parentNamespace.RenameChildElement(currentNamespace.Name, segments.Select(x => provider.ReservedNames.Contains(x) ?
replacement.Invoke(x) :
x)
.Aggregate((x, y) => $"{x}.{y}"));
}
}
private static IEnumerable<CodeUsing> usingSelector(AdditionalUsingEvaluator x) =>
x.ImportSymbols.Select(y =>
new CodeUsing
{
Name = y,
Declaration = new CodeType { Name = x.NamespaceName, IsExternal = true },
IsErasable = x.IsErasable,
});
protected static void AddDefaultImports(CodeElement current, IEnumerable<AdditionalUsingEvaluator> evaluators)
{
ArgumentNullException.ThrowIfNull(current);
var usingsToAdd = evaluators.Where(x => x.CodeElementEvaluator.Invoke(current))
.SelectMany(usingSelector)
.ToArray();
if (usingsToAdd.Length != 0)
{
var parentBlock = current.GetImmediateParentOfType<IBlock>();
var targetBlock = parentBlock.Parent is CodeClass parentClassParent ? parentClassParent : parentBlock;
targetBlock.AddUsing(usingsToAdd);
}
CrawlTree(current, c => AddDefaultImports(c, evaluators));
}
private static readonly HashSet<string> BinaryTypes = new(StringComparer.OrdinalIgnoreCase) { "binary", "base64", "base64url" };
protected static void ReplaceBinaryByNativeType(CodeElement currentElement, string symbol, string ns, bool addDeclaration = false, bool isNullable = false)
{
if (currentElement is CodeMethod currentMethod)
{
var shouldInsertUsing = false;
if (!string.IsNullOrEmpty(currentMethod.ReturnType?.Name) && BinaryTypes.Contains(currentMethod.ReturnType.Name))
{
currentMethod.ReturnType.Name = symbol;
currentMethod.ReturnType.IsNullable = isNullable;
shouldInsertUsing = !string.IsNullOrWhiteSpace(ns);
}
var binaryParameter = currentMethod.Parameters.FirstOrDefault(static x => BinaryTypes.Contains(x.Type?.Name ?? string.Empty));
if (binaryParameter != null)
{
binaryParameter.Type.Name = symbol;
binaryParameter.Type.IsNullable = isNullable;
shouldInsertUsing = !string.IsNullOrWhiteSpace(ns);
}
if (shouldInsertUsing && currentMethod.Parent is CodeClass parentClass)
{
var newUsing = new CodeUsing
{
Name = addDeclaration ? symbol : ns,
};
if (addDeclaration)
newUsing.Declaration = new CodeType
{
Name = ns,
IsExternal = true,
};
parentClass.AddUsing(newUsing);
}
}
CrawlTree(currentElement, c => ReplaceBinaryByNativeType(c, symbol, ns, addDeclaration, isNullable));
}
protected static void ConvertUnionTypesToWrapper(CodeElement currentElement, bool usesBackingStore, Func<string, string> refineMethodName, bool supportInnerClasses = true, string markerInterfaceNamespace = "", string markerInterfaceName = "", string markerMethodName = "")
{
ArgumentNullException.ThrowIfNull(currentElement);
ArgumentNullException.ThrowIfNull(refineMethodName);
if (currentElement.Parent is CodeClass parentClass)
{
if (currentElement is CodeMethod currentMethod)
{
currentMethod.Name = refineMethodName(currentMethod.Name);
if (currentMethod.ReturnType is CodeComposedTypeBase currentUnionType)
currentMethod.ReturnType = ConvertComposedTypeToWrapper(parentClass, currentUnionType, usesBackingStore, refineMethodName, supportInnerClasses, markerInterfaceNamespace, markerInterfaceName, markerMethodName);
if (currentMethod.Parameters.Any(static x => x.Type is CodeComposedTypeBase))
foreach (var currentParameter in currentMethod.Parameters.Where(static x => x.Type is CodeComposedTypeBase))
currentParameter.Type = ConvertComposedTypeToWrapper(parentClass, (CodeComposedTypeBase)currentParameter.Type, usesBackingStore, refineMethodName, supportInnerClasses, markerInterfaceNamespace, markerInterfaceName, markerMethodName);
if (currentMethod.ErrorMappings.Select(static x => x.Value).OfType<CodeComposedTypeBase>().Any())
foreach (var errorUnionType in currentMethod.ErrorMappings.Select(static x => x.Value).OfType<CodeComposedTypeBase>())
currentMethod.ReplaceErrorMapping(errorUnionType, ConvertComposedTypeToWrapper(parentClass, errorUnionType, usesBackingStore, refineMethodName, supportInnerClasses, markerInterfaceNamespace, markerInterfaceName, markerMethodName));
}
else if (currentElement is CodeIndexer currentIndexer && currentIndexer.ReturnType is CodeComposedTypeBase currentUnionType)
currentIndexer.ReturnType = ConvertComposedTypeToWrapper(parentClass, currentUnionType, usesBackingStore, refineMethodName, supportInnerClasses, markerInterfaceNamespace, markerInterfaceName, markerMethodName);
else if (currentElement is CodeProperty currentProperty && currentProperty.Type is CodeComposedTypeBase currentPropUnionType)
currentProperty.Type = ConvertComposedTypeToWrapper(parentClass, currentPropUnionType, usesBackingStore, refineMethodName, supportInnerClasses, markerInterfaceNamespace, markerInterfaceName, markerMethodName);
}
CrawlTree(currentElement, x => ConvertUnionTypesToWrapper(x, usesBackingStore, refineMethodName, supportInnerClasses, markerInterfaceNamespace, markerInterfaceName, markerMethodName));
}
private static CodeType ConvertComposedTypeToWrapper(CodeClass codeClass, CodeComposedTypeBase codeComposedType, bool usesBackingStore, Func<string, string> refineMethodName, bool supportsInnerClasses, string markerInterfaceNamespace, string markerInterfaceName, string markerMethodName)
{
ArgumentNullException.ThrowIfNull(codeClass);
ArgumentNullException.ThrowIfNull(codeComposedType);
CodeClass newClass;
var description =
"Composed type wrapper for classes {TypesList}";
if (!supportsInnerClasses)
{
var @namespace = codeClass.GetImmediateParentOfType<CodeNamespace>();
if (@namespace.FindChildByName<CodeClass>(codeComposedType.Name, false) is CodeClass { OriginalComposedType: null })
codeComposedType.Name = $"{codeComposedType.Name}Wrapper";
newClass = @namespace.AddClass(new CodeClass
{
Name = codeComposedType.Name,
Documentation = new(new() {
{ "TypesList", codeComposedType }
})
{
DescriptionTemplate = description,
},
Deprecation = codeComposedType.Deprecation,
}).Last();
}
else if (codeComposedType.TargetNamespace is CodeNamespace targetNamespace)
{
newClass = targetNamespace.AddClass(new CodeClass
{
Name = codeComposedType.Name,
Documentation = new(new() {
{ "TypesList", codeComposedType }
})
{
DescriptionTemplate = description
},
})
.First();
newClass.AddUsing(codeComposedType.AllTypes
.SelectMany(static c => (c.TypeDefinition as CodeClass)?.Usings ?? Enumerable.Empty<CodeUsing>())
.Where(static x => x.IsExternal)
.Select(static u => (CodeUsing)u.Clone())
.ToArray());
}
else
{
if (codeComposedType.Name.Equals(codeClass.Name, StringComparison.OrdinalIgnoreCase) || codeClass.FindChildByName<CodeProperty>(codeComposedType.Name, false) is not null)
codeComposedType.Name = $"{codeComposedType.Name}Wrapper";
newClass = codeClass.AddInnerClass(new CodeClass
{
Name = codeComposedType.Name,
Documentation = new(new() {
{ "TypesList", codeComposedType }
})
{
DescriptionTemplate = description
},
})
.First();
}
newClass.AddProperty(codeComposedType
.Types
.Select(static x => new CodeProperty
{
Name = x.Name,
Type = x,
Documentation = new(new() {
{ "TypeName", x }
})
{
DescriptionTemplate = "Composed type representation for type {TypeName}"
},
}).ToArray());
if (codeComposedType.Types.All(static x => x.TypeDefinition is CodeClass targetClass && targetClass.IsOfKind(CodeClassKind.Model) ||
x.TypeDefinition is CodeEnum || x.TypeDefinition is null))
{
KiotaBuilder.AddSerializationMembers(newClass, false, usesBackingStore, refineMethodName);
newClass.Kind = CodeClassKind.Model;
}
newClass.OriginalComposedType = codeComposedType;
if (!string.IsNullOrEmpty(markerInterfaceName) && !string.IsNullOrEmpty(markerInterfaceNamespace))
{
newClass.StartBlock.AddImplements(new CodeType
{
Name = markerInterfaceName
});
newClass.AddUsing(new CodeUsing
{
Name = markerInterfaceName,
Declaration = new()
{
Name = markerInterfaceNamespace,
IsExternal = true,
}
});
}
if (!string.IsNullOrEmpty(markerMethodName))
{
newClass.AddMethod(new CodeMethod
{
Name = markerMethodName,
ReturnType = new CodeType
{
Name = "boolean",
IsNullable = false,
},
Kind = CodeMethodKind.ComposedTypeMarker,
Access = AccessModifier.Public,
IsAsync = false,
IsStatic = false,
Documentation = new()
{
DescriptionTemplate = "Determines if the current object is a wrapper around a composed type",
},
});
}
// Add the discriminator function to the wrapper as it will be referenced.
KiotaBuilder.AddDiscriminatorMethod(newClass, codeComposedType.DiscriminatorInformation.DiscriminatorPropertyName, codeComposedType.DiscriminatorInformation.DiscriminatorMappings, refineMethodName);
return new CodeType
{
Name = newClass.Name,
TypeDefinition = newClass,
CollectionKind = codeComposedType.CollectionKind,
IsNullable = codeComposedType.IsNullable,
ActionOf = codeComposedType.ActionOf,
};
}
protected static void MoveClassesWithNamespaceNamesUnderNamespace(CodeElement currentElement)
{
if (currentElement is CodeClass currentClass &&
!string.IsNullOrEmpty(currentClass.Name) &&
currentClass.Parent is CodeNamespace parentNamespace)
{
var childNamespaceWithClassName = parentNamespace.GetChildElements(true)
.OfType<CodeNamespace>()
.FirstOrDefault(x => x.Name
.EndsWith(currentClass.Name, StringComparison.OrdinalIgnoreCase));
if (childNamespaceWithClassName != null)
{
parentNamespace.RemoveChildElement(currentClass);
childNamespaceWithClassName.AddClass(currentClass);
}
}
CrawlTree(currentElement, MoveClassesWithNamespaceNamesUnderNamespace);
}
protected static void ReplaceIndexersByMethodsWithParameter(CodeElement currentElement, bool parameterNullable, Func<string, string> methodNameCallback, Func<string, string> parameterNameCallback, GenerationLanguage language)
{
if (currentElement is CodeIndexer currentIndexer &&
currentElement.Parent is CodeClass indexerParentClass)
{
if (indexerParentClass.ContainsMember(currentElement.Name)) // TODO remove condition for v2 necessary because of the second case of Go block
indexerParentClass.RemoveChildElement(currentElement);
//TODO remove whole block except for last else if body for v2
if (language == GenerationLanguage.Go)
{
if (currentIndexer.IsLegacyIndexer)
{
if (indexerParentClass.Indexer is CodeIndexer specificIndexer && specificIndexer != currentIndexer && !specificIndexer.IsLegacyIndexer)
{
indexerParentClass.RemoveChildElement(specificIndexer);
indexerParentClass.AddMethod(CodeMethod.FromIndexer(specificIndexer, methodNameCallback, parameterNameCallback, parameterNullable, true));
}
indexerParentClass.AddMethod(CodeMethod.FromIndexer(currentIndexer, methodNameCallback, parameterNameCallback, parameterNullable));
}
else
{
var foundLegacyIndexer = indexerParentClass.Methods.Any(x => x.Kind is CodeMethodKind.IndexerBackwardCompatibility && x.OriginalIndexer is not null && x.OriginalIndexer.IsLegacyIndexer);
if (!foundLegacyIndexer && indexerParentClass.GetChildElements(true).OfType<CodeIndexer>().FirstOrDefault(static x => x.IsLegacyIndexer) is CodeIndexer legacyIndexer)
{
indexerParentClass.RemoveChildElement(legacyIndexer);
indexerParentClass.AddMethod(CodeMethod.FromIndexer(legacyIndexer, methodNameCallback, parameterNameCallback, parameterNullable));
foundLegacyIndexer = true;
}
indexerParentClass.AddMethod(CodeMethod.FromIndexer(currentIndexer, methodNameCallback, parameterNameCallback, parameterNullable, foundLegacyIndexer));
}
}
else if (!currentIndexer.IsLegacyIndexer)
indexerParentClass.AddMethod(CodeMethod.FromIndexer(currentIndexer, methodNameCallback, parameterNameCallback, parameterNullable));
}
CrawlTree(currentElement, c => ReplaceIndexersByMethodsWithParameter(c, parameterNullable, methodNameCallback, parameterNameCallback, language));
}
internal void DisableActionOf(CodeElement current, params CodeParameterKind[] kinds)
{
if (current is CodeMethod currentMethod)
foreach (var parameter in currentMethod.Parameters.Where(x => x.Type.ActionOf && x.IsOfKind(kinds)))
parameter.Type.ActionOf = false;
CrawlTree(current, x => DisableActionOf(x, kinds));
}
internal void AddInnerClasses(CodeElement current, bool prefixClassNameWithParentName, string queryParametersBaseClassName = "", bool addToParentNamespace = false, Func<string, string, string>? nameFactory = default)
{
if (current is CodeClass currentClass && currentClass.IsOfKind(CodeClassKind.RequestBuilder))
{
var parentNamespace = currentClass.GetImmediateParentOfType<CodeNamespace>();
var innerClasses = currentClass
.Methods
.SelectMany(static x => x.Parameters)
.Where(static x => x.Type.ActionOf && x.IsOfKind(CodeParameterKind.RequestConfiguration))
.SelectMany(static x => x.Type.AllTypes)
.Select(static x => x.TypeDefinition)
.OfType<CodeClass>()
.Distinct();
// ensure we do not miss out the types present in request configuration objects i.e. the query parameters
var nestedQueryParameters = innerClasses
.SelectMany(static x => x.Properties)
.Where(static x => x.IsOfKind(CodePropertyKind.QueryParameters))
.SelectMany(static x => x.Type.AllTypes)
.Select(static x => x.TypeDefinition)
.OfType<CodeClass>()
.Distinct();
var nestedClasses = new List<CodeClass>();
nestedClasses.AddRange(innerClasses);
nestedClasses.AddRange(nestedQueryParameters);
foreach (var nestedClass in nestedClasses)
{
if (nestedClass.Parent is not CodeClass parentClass) continue;
if (nameFactory != default)
parentClass.RenameChildElement(nestedClass.Name, nameFactory(currentClass.Name, nestedClass.Name));
else if (prefixClassNameWithParentName && !nestedClass.Name.StartsWith(currentClass.Name, StringComparison.OrdinalIgnoreCase))
parentClass.RenameChildElement(nestedClass.Name, $"{currentClass.Name}{nestedClass.Name}");
if (addToParentNamespace && parentNamespace.FindChildByName<CodeClass>(nestedClass.Name, false) == null)
{ // the query parameters class is already a child of the request executor method parent class
parentNamespace.AddClass(nestedClass);
currentClass.RemoveChildElementByName(nestedClass.Name);
}
else if (!addToParentNamespace && currentClass.FindChildByName<CodeClass>(nestedClass.Name, false) == null) //failsafe
currentClass.AddInnerClass(nestedClass);
if (!string.IsNullOrEmpty(queryParametersBaseClassName))
nestedClass.StartBlock.Inherits = new CodeType { Name = queryParametersBaseClassName, IsExternal = true };
}
}
CrawlTree(current, x => AddInnerClasses(x, prefixClassNameWithParentName, queryParametersBaseClassName, addToParentNamespace, nameFactory));
}
private static readonly CodeUsingComparer usingComparerWithDeclarations = new(true);
private static readonly CodeUsingComparer usingComparerWithoutDeclarations = new(false);
#pragma warning disable CA1051 // Do not declare visible instance fields
protected readonly GenerationConfiguration _configuration;
#pragma warning restore CA1051 // Do not declare visible instance fields
protected static void AddPropertiesAndMethodTypesImports(CodeElement current, bool includeParentNamespaces, bool includeCurrentNamespace, bool compareOnDeclaration, Func<IEnumerable<CodeTypeBase>, IEnumerable<CodeTypeBase>>? codeTypeFilter = default)
{
if (current is CodeClass currentClass &&
currentClass.StartBlock is ClassDeclaration currentClassDeclaration &&
currentClass.GetImmediateParentOfType<CodeNamespace>() is CodeNamespace currentClassNamespace)
{
var currentClassChildren = currentClass.GetChildElements(true);
var inheritTypes = currentClassDeclaration.Inherits?.AllTypes ?? Enumerable.Empty<CodeType>();
var propertiesTypes = currentClass
.Properties
.Where(static x => !x.ExistsInBaseType)
.Select(static x => x.Type)
.Distinct();
var methods = currentClass.Methods;
var methodsReturnTypes = methods
.Select(static x => x.ReturnType)
.Distinct();
var methodsParametersTypes = methods
.SelectMany(static x => x.Parameters)
.Where(static x => x.IsOfKind(CodeParameterKind.Custom, CodeParameterKind.RequestBody, CodeParameterKind.RequestConfiguration, CodeParameterKind.QueryParameter))
.Select(static x => x.Type)
.Distinct();
var indexerTypes = currentClassChildren
.OfType<CodeIndexer>()
.Select(static x => x.ReturnType)
.Distinct();
var errorTypes = currentClassChildren
.OfType<CodeMethod>()
.Where(static x => x.IsOfKind(CodeMethodKind.RequestExecutor))
.SelectMany(static x => x.ErrorMappings)
.Select(static x => x.Value)
.Distinct();
var typesCollection = propertiesTypes
.Union(methodsParametersTypes)
.Union(methodsReturnTypes)
.Union(indexerTypes)
.Union(inheritTypes)
.Union(errorTypes)
.Where(static x => x != null);
if (codeTypeFilter != default)
{
typesCollection = codeTypeFilter.Invoke(typesCollection);
}
var usingsToAdd = typesCollection
.SelectMany(static x => x.AllTypes.Select(static y => (type: y, ns: y.TypeDefinition?.GetImmediateParentOfType<CodeNamespace>())))
.Where(x => x.ns != null && (includeCurrentNamespace || x.ns != currentClassNamespace))
.Where(x => includeParentNamespaces || !currentClassNamespace.IsChildOf(x.ns!))
.Select(static x => new CodeUsing { Name = x.ns!.Name, Declaration = x.type })
.Where(x => x.Declaration?.TypeDefinition != current)
.Distinct(compareOnDeclaration ? usingComparerWithDeclarations : usingComparerWithoutDeclarations)
.ToArray();
if (usingsToAdd.Length != 0)
(currentClass.Parent is CodeClass parentClass ? parentClass : currentClass).AddUsing(usingsToAdd); //lots of languages do not support imports on nested classes
}
CrawlTree(current, x => AddPropertiesAndMethodTypesImports(x, includeParentNamespaces, includeCurrentNamespace, compareOnDeclaration, codeTypeFilter));
}
protected static void CrawlTree(CodeElement currentElement, Action<CodeElement> function, bool innerOnly = true)
{
ArgumentNullException.ThrowIfNull(currentElement);
ArgumentNullException.ThrowIfNull(function);
foreach (var childElement in currentElement.GetChildElements(innerOnly))
function.Invoke(childElement);
}
protected static void CorrectCoreType(CodeElement currentElement, Action<CodeMethod>? correctMethodType, Action<CodeProperty>? correctPropertyType, Action<ProprietableBlockDeclaration>? correctImplements = default)
{
switch (currentElement)
{
case CodeProperty property:
correctPropertyType?.Invoke(property);
break;
case CodeMethod method:
correctMethodType?.Invoke(method);
break;
case ProprietableBlockDeclaration block:
correctImplements?.Invoke(block);
break;
}
CrawlTree(currentElement, x => CorrectCoreType(x, correctMethodType, correctPropertyType, correctImplements), false);
}
protected static void MakeModelPropertiesNullable(CodeElement currentElement)
{
if (currentElement is CodeClass currentClass &&
currentClass.IsOfKind(CodeClassKind.Model))
currentClass.Properties
.Where(static x => x.IsOfKind(CodePropertyKind.Custom))
.ToList()
.ForEach(static x => x.Type.IsNullable = true);
CrawlTree(currentElement, MakeModelPropertiesNullable);
}
protected static void RemoveMethodByKind(CodeElement currentElement, CodeMethodKind kind, params CodeMethodKind[] additionalKinds)
{
RemoveMethodByKindImpl(currentElement, new List<CodeMethodKind>(additionalKinds) { kind }.ToArray());
}
private static void RemoveMethodByKindImpl(CodeElement currentElement, CodeMethodKind[] kinds)
{
if (currentElement is CodeMethod codeMethod &&
currentElement.Parent is CodeClass parentClass &&
codeMethod.IsOfKind(kinds))
{
parentClass.RemoveMethodByKinds(codeMethod.Kind);
}
CrawlTree(currentElement, x => RemoveMethodByKindImpl(x, kinds));
}
protected static void RemoveCancellationParameter(CodeElement currentElement)
{
if (currentElement is CodeMethod currentMethod &&
currentMethod.IsOfKind(CodeMethodKind.RequestExecutor))
{
currentMethod.RemoveParametersByKind(CodeParameterKind.Cancellation);
}
CrawlTree(currentElement, RemoveCancellationParameter);
}
protected static void AddParsableImplementsForModelClasses(CodeElement currentElement, string className)
{
ArgumentException.ThrowIfNullOrEmpty(className);
if (currentElement is CodeClass currentClass &&
currentClass.IsOfKind(CodeClassKind.Model))
{
currentClass.StartBlock.AddImplements(new CodeType
{
IsExternal = true,
Name = className
});
}
CrawlTree(currentElement, c => AddParsableImplementsForModelClasses(c, className));
}
protected static void CorrectCoreTypes(CodeClass? parentClass, Dictionary<string, (string, CodeUsing?)> coreTypesReplacements, params CodeTypeBase[] types)
{
ArgumentNullException.ThrowIfNull(coreTypesReplacements);
if (parentClass == null)
return;
foreach (var type in types.Where(x => x != null && !string.IsNullOrEmpty(x.Name) && coreTypesReplacements.ContainsKey(x.Name)))
{
var replacement = coreTypesReplacements[type.Name];
if (!string.IsNullOrEmpty(replacement.Item1))
type.Name = replacement.Item1;
if (replacement.Item2 != null)
parentClass.AddUsing((CodeUsing)replacement.Item2.Clone());
}
}
protected static void InlineParentClasses(CodeElement currentElement, CodeElement parent)
{
if (currentElement is CodeClass currentClass &&
parent is CodeType parentType &&
parentType.TypeDefinition is CodeClass parentClass)
{
foreach (var currentParent in parentClass.GetInheritanceTree())
{
foreach (var p in currentParent
.Properties
.Where(pp =>
!currentClass.ContainsMember(pp.Name) &&
!currentClass.Properties.Any(cp => cp.Name.Equals(pp.Name, StringComparison.OrdinalIgnoreCase))))
{
var newP = (CodeProperty)p.Clone();
newP.Parent = currentClass;
currentClass.AddProperty(newP);
if (newP.Setter != null)
{
newP.Setter.AccessedProperty = newP;
currentClass.AddMethod(newP.Setter);
}
if (newP.Getter != null)
{
newP.Getter.AccessedProperty = newP;
currentClass.AddMethod(newP.Getter);
}
}
foreach (var m in currentParent
.Methods
.Where(pm =>
!currentClass.ContainsMember(pm.Name) &&
!currentClass.Methods.Any(cm => cm.Name.Equals(pm.Name, StringComparison.OrdinalIgnoreCase))))
{
var newM = (CodeMethod)m.Clone();
newM.Parent = currentClass;
currentClass.AddMethod(newM);
}
foreach (var u in currentParent
.Usings
.Where(pu => !currentClass.Usings.Any(cu => cu.Name.Equals(pu.Name, StringComparison.OrdinalIgnoreCase))))
{
var newU = (CodeUsing)u.Clone();
newU.Parent = currentClass;
currentClass.AddUsing(newU);
}
foreach (var implement in currentParent
.StartBlock
.Implements
.Where(pi => !currentClass.Usings.Any(ci => ci.Name.Equals(pi.Name, StringComparison.OrdinalIgnoreCase))))
{
currentClass.StartBlock.AddImplements((CodeType)implement.Clone());
}
}
}
}
protected static void AddParentClassToErrorClasses(CodeElement currentElement, string parentClassName, string parentClassNamespace, bool addNamespaceToInheritDeclaration = false, bool isInterface = false, bool isErasable = false)
{
if (currentElement is CodeClass currentClass &&
currentClass.IsErrorDefinition &&
currentClass.StartBlock is ClassDeclaration declaration)
{
if (isInterface)
{
declaration.AddImplements(new CodeType
{
Name = parentClassName,
IsExternal = true,
});
}
else
{
if (declaration.Inherits is CodeElement parentElement)
{
// Need to remove inheritance before fixing up the child elements
declaration.Inherits = null;
InlineParentClasses(currentClass, parentElement);
}
declaration.Inherits = new CodeType
{
Name = parentClassName,
IsExternal = true,
};
if (addNamespaceToInheritDeclaration)
{
declaration.Inherits.TypeDefinition = new CodeType
{
Name = parentClassNamespace,
IsExternal = true,
};
}
}
declaration.AddUsings(new CodeUsing
{
Name = parentClassName,
Declaration = new CodeType
{
Name = parentClassNamespace,
IsExternal = true,
},
IsErasable = isErasable
});
}
CrawlTree(currentElement, x => AddParentClassToErrorClasses(x, parentClassName, parentClassNamespace, addNamespaceToInheritDeclaration, isInterface, isErasable));
}
protected static void AddDiscriminatorMappingsUsingsToParentClasses(CodeElement currentElement, string parseNodeInterfaceName, bool addFactoryMethodImport = false, bool addUsings = true, bool includeParentNamespace = false)
{
if (currentElement is CodeMethod currentMethod &&
currentMethod.Parent is CodeClass parentClass &&
parentClass.StartBlock is ClassDeclaration declaration)
{
if (currentMethod.IsOfKind(CodeMethodKind.Factory) &&
(parentClass.DiscriminatorInformation?.HasBasicDiscriminatorInformation ?? false) &&
parentClass.GetImmediateParentOfType<CodeNamespace>() is CodeNamespace parentClassNamespace)
{
if (addUsings && includeParentNamespace)
declaration.AddUsings(parentClass.DiscriminatorInformation.DiscriminatorMappings
.Select(static x => x.Value)
.OfType<CodeType>()
.Where(static x => x.TypeDefinition != null)
.Select(x => new CodeUsing
{
Name = x.TypeDefinition!.GetImmediateParentOfType<CodeNamespace>().Name,
Declaration = new CodeType
{
Name = x.TypeDefinition.Name,
TypeDefinition = x.TypeDefinition,
},
}).ToArray());