-
Notifications
You must be signed in to change notification settings - Fork 866
Expand file tree
/
Copy pathAtsPythonCodeGenerator.cs
More file actions
2442 lines (2175 loc) · 99.3 KB
/
AtsPythonCodeGenerator.cs
File metadata and controls
2442 lines (2175 loc) · 99.3 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
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Globalization;
using System.Reflection;
using Aspire.TypeSystem;
namespace Aspire.Hosting.CodeGeneration.Python;
/// <summary>
/// Represents a builder class to be generated with its capabilities.
/// Internal type replacing BuilderModel - used only within the generator.
/// </summary>
internal sealed class BuilderModel
{
public required string TypeId { get; init; }
public required string BuilderClassName { get; init; }
public required List<AtsCapabilityInfo> Capabilities { get; init; }
public bool IsInterface { get; init; }
public AtsTypeRef? TargetType { get; init; }
}
/// <summary>
/// Generates a Python SDK using the ATS (Aspire Type System) capability-based API.
/// Produces typed wrapper classes with fluent methods that use invoke_capability().
/// </summary>
/// <remarks>
/// <para>
/// <b>ATS to Python Type Mapping</b>
/// </para>
/// <para>
/// The generator maps ATS types to Python types according to the following rules:
/// </para>
/// <para>
/// <b>Primitive Types:</b>
/// <list type="table">
/// <listheader>
/// <term>ATS Type</term>
/// <description>Python Type</description>
/// </listheader>
/// <item><term><c>string</c></term><description><c>str</c></description></item>
/// <item><term><c>number</c></term><description><c>float</c></description></item>
/// <item><term><c>boolean</c></term><description><c>bool</c></description></item>
/// <item><term><c>any</c></term><description><c>Any</c></description></item>
/// </list>
/// </para>
/// <para>
/// <b>Handle Types:</b>
/// Type IDs use the format <c>{AssemblyName}/{TypeName}</c>.
/// Handle types are wrapped in Python classes that provide typed access to capabilities.
/// </para>
/// <para>
/// <b>Method Naming:</b>
/// <list type="bullet">
/// <item><description>Derived from capability ID using snake_case conversion</description></item>
/// <item><description><c>addRedis</c> → <c>add_redis</c></description></item>
/// <item><description><c>withEnvironment</c> → <c>with_environment</c></description></item>
/// </list>
/// </para>
/// </remarks>
internal sealed class AtsPythonCodeGenerator : ICodeGenerator
{
private static readonly HashSet<string> s_pythonKeywords = new(StringComparer.Ordinal)
{
"False",
"None",
"True",
"and",
"as",
"assert",
"async",
"await",
"break",
"class",
"continue",
"def",
"del",
"elif",
"else",
"except",
"finally",
"for",
"from",
"global",
"if",
"import",
"in",
"is",
"lambda",
"match",
"nonlocal",
"not",
"or",
"pass",
"raise",
"return",
"try",
"while",
"with",
"yield"
};
private sealed record OptionVariation(
string OptionType,
List<AtsParameterInfo> RequiredParameters,
List<AtsParameterInfo> OptionalParameters,
string? Experimental);
/// <summary>
/// Tracks the alternate capability ID for merged capabilities.
/// Key: the merged capability ID (the "short" one without the extra param).
/// Value: (alternateCapabilityId, discriminatingParamName) - the capability to invoke when the extra param is provided.
/// </summary>
private sealed record MergedCapabilityDispatch(string AlternateCapabilityId, string DiscriminatingParamName);
private readonly Dictionary<string, MergedCapabilityDispatch> _mergedCapabilityDispatches = new(StringComparer.Ordinal);
private PythonModuleBuilder _moduleBuilder = null!;
// Mapping of typeId -> wrapper class name for all generated wrapper types
// Used to resolve parameter types to wrapper classes instead of handle types
private readonly Dictionary<string, string> _wrapperClassNames = new(StringComparer.Ordinal);
// Mapping of enum type IDs to Python enum names
private readonly Dictionary<string, string> _enumTypeNames = new(StringComparer.Ordinal);
// List of type IDs to ignore when generating handle type aliases
private readonly List<string> _ignoreTypes = new()
{
AtsConstants.ReferenceExpressionTypeId,
"System.Private.CoreLib/System.IAsyncDisposable",
"System.Private.CoreLib/System.IDisposable",
"Microsoft.Extensions.Hosting.Abstractions/Microsoft.Extensions.Hosting.IHost"
};
/// <summary>
/// Checks if an AtsTypeRef represents a handle type.
/// </summary>
private static bool IsHandleType(AtsTypeRef? typeRef) =>
typeRef != null && typeRef.Category == AtsTypeCategory.Handle;
/// <summary>
/// Checks if the capability's target type is already covered by the builder's base class hierarchy.
/// Returns true if the target type is a base class of the builder's type, or an interface
/// that's implemented by any class in the builder's base class hierarchy.
/// </summary>
private static bool IsTargetTypeCoveredByBaseHierarchy(AtsTypeRef? capabilityTargetType, AtsTypeRef? builderTargetType)
{
if (capabilityTargetType == null || builderTargetType == null)
{
return false;
}
// If the capability targets the builder's own type, it's not covered by base
if (capabilityTargetType.TypeId == builderTargetType.TypeId)
{
return false;
}
// Check if the capability's target type is in the base class hierarchy
var currentBase = builderTargetType.BaseType;
while (currentBase != null)
{
// Check if capability targets this base class
if (capabilityTargetType.TypeId == currentBase.TypeId)
{
return true;
}
// Check if capability targets an interface implemented by this base class
if (currentBase.ImplementedInterfaces != null)
{
if (currentBase.ImplementedInterfaces.Any(i => i.TypeId == capabilityTargetType.TypeId))
{
return true;
}
}
currentBase = currentBase.BaseType;
}
return false;
}
/// <summary>
/// Maps an AtsTypeRef to a Python type using category-based dispatch.
/// This is the preferred method - uses type metadata rather than string parsing.
/// </summary>
private string MapTypeRefToPython(AtsTypeRef? typeRef)
{
if (typeRef == null)
{
return "typing.Any";
}
// Check for wrapper class first (handles custom types like ReferenceExpression)
if (_wrapperClassNames.TryGetValue(typeRef.TypeId, out var wrapperClassName))
{
return wrapperClassName;
}
return typeRef.Category switch
{
AtsTypeCategory.Primitive => MapPrimitiveType(typeRef.TypeId),
AtsTypeCategory.Enum => MapEnumType(typeRef.TypeId),
AtsTypeCategory.Handle => GetWrapperOrHandleName(typeRef.TypeId),
AtsTypeCategory.Dto => GetDtoClassName(typeRef.TypeId),
AtsTypeCategory.Callback => "typing.Callable", // Callbacks handled separately with full signature
AtsTypeCategory.Array => $"typing.Iterable[{MapTypeRefToPython(typeRef.ElementType)}]",
AtsTypeCategory.List => $"AspireList[{MapTypeRefToPython(typeRef.ElementType)}]",
AtsTypeCategory.Dict => typeRef.IsReadOnly
? $"typing.Mapping[{MapTypeRefToPython(typeRef.KeyType)}, {MapTypeRefToPython(typeRef.ValueType)}]"
: $"AspireDict[{MapTypeRefToPython(typeRef.KeyType)}, {MapTypeRefToPython(typeRef.ValueType)}]",
AtsTypeCategory.Union => MapUnionTypeToPython(typeRef),
AtsTypeCategory.Unknown => "typing.Any", // Unknown types use 'Any' since they're not in the ATS universe
_ => "typing.Any" // Fallback for any unhandled categories
};
}
/// <summary>
/// Maps primitive type IDs to Python types.
/// </summary>
private static string MapPrimitiveType(string typeId) => typeId switch
{
AtsConstants.String or AtsConstants.Char => "str",
AtsConstants.Number => "int",
AtsConstants.Boolean => "bool",
AtsConstants.Void => "None",
AtsConstants.Any => "typing.Any",
AtsConstants.DateTime => "datetime.datetime",
AtsConstants.DateTimeOffset => "datetime.datetime",
AtsConstants.DateOnly => "datetime.date",
AtsConstants.TimeOnly => "datetime.time",
AtsConstants.TimeSpan => "float",
AtsConstants.Guid or AtsConstants.Uri => "str",
AtsConstants.CancellationToken => "CancellationToken",
_ => typeId
};
private static string GetParamHandler(AtsParameterInfo param, string paramName)
{
if (param.IsCallback)
{
return $"self._client.register_callback({paramName})";
}
if (param.Type?.TypeId == AtsConstants.CancellationToken)
{
return $"self._client.register_cancellation_token({paramName})";
}
return paramName;
}
private static string GetConstructorParamHandler(AtsParameterInfo param, string paramName)
{
if (param.IsCallback)
{
return $"client.register_callback({paramName})";
}
if (param.Type?.TypeId == AtsConstants.CancellationToken)
{
return $"client.register_cancellation_token({paramName})";
}
return paramName;
}
/// <summary>
/// Merges capabilities that share the same <see cref="AtsCapabilityInfo.SourceLocation"/> and differ
/// by exactly one required parameter. The merged capability uses the shortest method name and makes
/// the differing parameter optional.
/// </summary>
private List<AtsCapabilityInfo> MergeCapabilitiesBySourceLocation(List<AtsCapabilityInfo> capabilities)
{
var result = new List<AtsCapabilityInfo>();
var groups = capabilities.GroupBy(c => c.SourceLocation ?? string.Empty);
foreach (var group in groups)
{
if (string.IsNullOrEmpty(group.Key) || group.Count() <= 1)
{
result.AddRange(group);
continue;
}
var items = group.ToList();
// Find parameter names common to all capabilities in this group
var commonParamNames = new HashSet<string>(
items[0].Parameters.Select(p => p.Name), StringComparer.Ordinal);
foreach (var item in items.Skip(1))
{
commonParamNames.IntersectWith(item.Parameters.Select(p => p.Name));
}
// Find the union of all parameter names
var allParamNames = items
.SelectMany(c => c.Parameters.Select(p => p.Name))
.ToHashSet(StringComparer.Ordinal);
var extraParamNames = allParamNames.Except(commonParamNames).ToHashSet(StringComparer.Ordinal);
// Only merge when exactly one parameter differs
if (extraParamNames.Count != 1)
{
result.AddRange(items);
continue;
}
var extraParamName = extraParamNames.Single();
// Get the extra parameter info from whichever capability has it
var capWithExtra = items.First(c => c.Parameters.Any(p => string.Equals(p.Name, extraParamName, StringComparison.Ordinal)));
var extraParam = capWithExtra.Parameters.First(p => string.Equals(p.Name, extraParamName, StringComparison.Ordinal));
// Only merge if the extra param is required (not already optional)
if (extraParam.IsOptional || extraParam.IsNullable)
{
result.AddRange(items);
continue;
}
// Use the capability with the shortest MethodName as the base
var shortest = items.OrderBy(c => c.MethodName.Length).ThenBy(c => c.MethodName, StringComparer.Ordinal).First();
// Build merged params from the capability with the most parameters
var fullCap = items.OrderByDescending(c => c.Parameters.Count).First();
var mergedParams = new List<AtsParameterInfo>();
foreach (var p in fullCap.Parameters)
{
if (string.Equals(p.Name, extraParamName, StringComparison.Ordinal))
{
mergedParams.Add(new AtsParameterInfo
{
Name = p.Name,
Type = p.Type,
IsOptional = true,
IsNullable = true,
IsCallback = p.IsCallback,
CallbackParameters = p.CallbackParameters,
CallbackReturnType = p.CallbackReturnType,
DefaultValue = p.DefaultValue
});
}
else
{
mergedParams.Add(p);
}
}
// Determine which capability ID to use when the extra param IS vs IS NOT provided.
// The "short" capability (without the extra param) is the default.
// The "long" capability (with the extra param) is the alternate.
var capWithoutExtra = items.FirstOrDefault(c => !c.Parameters.Any(p => string.Equals(p.Name, extraParamName, StringComparison.Ordinal)));
var alternateCapabilityId = capWithExtra.CapabilityId;
var baseCapabilityId = capWithoutExtra?.CapabilityId ?? shortest.CapabilityId;
var merged = new AtsCapabilityInfo
{
CapabilityId = baseCapabilityId,
MethodName = shortest.MethodName,
OwningTypeName = shortest.OwningTypeName,
Description = shortest.Description ?? items.FirstOrDefault(c => c.Description is not null)?.Description,
Parameters = mergedParams,
ReturnType = shortest.ReturnType,
TargetTypeId = shortest.TargetTypeId,
TargetType = shortest.TargetType,
TargetParameterName = shortest.TargetParameterName,
ReturnsBuilder = shortest.ReturnsBuilder,
CapabilityKind = shortest.CapabilityKind,
SourceLocation = shortest.SourceLocation,
RunSyncOnBackgroundThread = shortest.RunSyncOnBackgroundThread,
ExpandedTargetTypes = shortest.ExpandedTargetTypes
};
// Track the alternate dispatch so GenerateBuilderMethod can emit conditional logic
if (!string.Equals(baseCapabilityId, alternateCapabilityId, StringComparison.Ordinal))
{
_mergedCapabilityDispatches[baseCapabilityId] = new MergedCapabilityDispatch(alternateCapabilityId, extraParamName);
}
result.Add(merged);
}
return result;
}
/// <summary>
/// Filters capability parameters for Python code generation.
/// Removes the target parameter (e.g., "builder", "context") if specified,
/// and removes cancellationToken when a separate timeout parameter already exists,
/// since cancellationToken maps to "timeout" in Python and would cause a naming conflict.
/// </summary>
private static List<AtsParameterInfo> FilterMethodParameters(IReadOnlyList<AtsParameterInfo> parameters, string? targetParameterName = null)
{
var filtered = targetParameterName is not null
? parameters.Where(p => p.Name != targetParameterName)
: parameters.AsEnumerable();
if (parameters.Any(p => string.Equals(p.Name, "timeout", StringComparison.Ordinal)))
{
filtered = filtered.Where(p => p.Type?.TypeId != AtsConstants.CancellationToken);
}
return filtered.ToList();
}
/// <summary>
/// Gets the Python parameter name for a capability parameter.
/// Converts camelCase to snake_case, and renames cancellationToken to timeout.
/// </summary>
private static string GetParamName(AtsParameterInfo param)
{
if (param.Type?.TypeId == AtsConstants.CancellationToken)
{
return "timeout";
}
return ToSnakeCase(param.Name);
}
/// <summary>
/// Gets the Python representation of a parameter's default value.
/// Returns "None" if the default value is null or not set.
/// </summary>
private static string GetPythonDefaultValue(AtsParameterInfo param)
{
var defaultValue = param.DefaultValue;
if (defaultValue is null)
{
return "None";
}
return defaultValue switch
{
bool b => b ? "True" : "False",
string s => $"\"{s.Replace("\\", "\\\\").Replace("\"", "\\\"")}\"",
char c => $"\"{c}\"",
int i => i.ToString(CultureInfo.InvariantCulture),
long l => l.ToString(CultureInfo.InvariantCulture),
float f => float.IsPositiveInfinity(f) ? "float('inf')" : float.IsNegativeInfinity(f) ? "float('-inf')" : f.ToString(CultureInfo.InvariantCulture),
double d => double.IsPositiveInfinity(d) ? "float('inf')" : double.IsNegativeInfinity(d) ? "float('-inf')" : d.ToString(CultureInfo.InvariantCulture),
Enum e => $"\"{e}\"",
_ => "None"
};
}
/// <summary>
/// Gets the Python type annotation suffix and default value for an optional parameter.
/// Uses the actual default value when available instead of always defaulting to None.
/// </summary>
private string GetOptionalParamSuffix(AtsParameterInfo param)
{
var pythonDefault = GetPythonDefaultValue(param);
if (pythonDefault == "None")
{
var paramType = MapParameterToPython(param);
return $"{paramType} | None = None";
}
var type = MapParameterToPython(param);
// When we have a real default, the type doesn't need "| None" unless the param is also nullable
if (param.IsNullable)
{
return $"{type} | None = {pythonDefault}";
}
return $"{type} = {pythonDefault}";
}
/// <summary>
/// Maps an enum type ID to the generated Python enum name.
/// Throws if the enum type wasn't collected during scanning.
/// </summary>
private string MapEnumType(string typeId)
{
if (!_enumTypeNames.TryGetValue(typeId, out var enumName))
{
throw new InvalidOperationException(
$"Enum type '{typeId}' was not found in the scanned enum types. " +
$"This indicates the enum type was not discovered during assembly scanning.");
}
return enumName;
}
/// <summary>
/// Maps a union type to Python union syntax (T1 | T2 | ...).
/// </summary>
private string MapUnionTypeToPython(AtsTypeRef typeRef)
{
if (typeRef.UnionTypes == null || typeRef.UnionTypes.Count == 0)
{
return "typing.Any";
}
var memberTypes = typeRef.UnionTypes
.Select(MapTypeRefToPython)
.Distinct();
return string.Join(" | ", memberTypes);
}
/// <summary>
/// Gets the wrapper class name or handle type name for a handle type ID.
/// Prefers wrapper class if one exists, otherwise generates a handle type name.
/// </summary>
private string GetWrapperOrHandleName(string typeId)
{
if (_wrapperClassNames.TryGetValue(typeId, out var wrapperClassName))
{
return wrapperClassName;
}
return GetHandleTypeName(typeId);
}
/// <summary>
/// Gets a Python class name for a DTO type.
/// </summary>
private static string GetDtoClassName(string typeId)
{
// Extract simple type name and use as class name
var simpleTypeName = ExtractSimpleTypeName(typeId);
return simpleTypeName;
}
/// <summary>
/// Maps a parameter to its Python type, handling callbacks specially.
/// For interface handle types, uses ResourceBuilderBase as the parameter type.
/// </summary>
private string MapParameterToPython(AtsParameterInfo param)
{
if (param.IsCallback)
{
return GenerateCallbackTypeSignature(param.CallbackParameters, param.CallbackReturnType);
}
if (param.Type?.TypeId == AtsConstants.CancellationToken)
{
return "int";
}
var baseType = MapTypeRefToPython(param.Type);
return baseType;
}
// /// <summary>
// /// Checks if a type reference is an interface handle type.
// /// Interface handles need base class types to accept wrapper classes.
// /// </summary>
// private static bool IsInterfaceHandleType(AtsTypeRef? typeRef)
// {
// if (typeRef == null)
// {
// return false;
// }
// return typeRef.Category == AtsTypeCategory.Handle && typeRef.IsInterface;
// }
/// <summary>
/// Gets the TypeId from a capability's return type.
/// </summary>
private static string? GetReturnTypeId(AtsCapabilityInfo capability) => capability.ReturnType?.TypeId;
/// <inheritdoc />
public string Language => "Python";
/// <inheritdoc />
public Dictionary<string, string> GenerateDistributedApplication(AtsContext context)
{
var files = new Dictionary<string, string>();
// Generate the capability-based aspire.py SDK
files["aspire_app.py"] = GenerateAspireSdk(context);
files["pyproject.toml"] = GetEmbeddedResource("pyproject.toml");
return files;
}
private static string GetEmbeddedResource(string name)
{
var assembly = Assembly.GetExecutingAssembly();
var resourceName = $"Aspire.Hosting.CodeGeneration.Python.Resources.{name}";
using var stream = assembly.GetManifestResourceStream(resourceName)
?? throw new InvalidOperationException($"Embedded resource '{name}' not found.");
using var reader = new StreamReader(stream);
return reader.ReadToEnd();
}
/// <summary>
/// Gets a valid Python method name from a capability method name.
/// Converts camelCase to snake_case.
/// Handles dotted names like "EnvironmentContext.resource" by extracting just the final part.
/// </summary>
private static string GetPythonMethodName(string methodName)
{
// Extract last component if dotted (e.g., "Type.method" -> "method")
var lastDot = methodName.LastIndexOf('.');
if (lastDot >= 0)
{
methodName = methodName[(lastDot + 1)..];
}
// Convert camelCase to snake_case
var snakeName = ToSnakeCase(methodName);
if (snakeName.EndsWith("_async"))
{
snakeName = snakeName[..^6];
}
return snakeName;
}
private static string GetMethodAsOptionName(string methodName)
{
if (methodName.StartsWith("with_"))
{
return methodName[5..];
}
return methodName;
}
private static string GetMethodParametersName(string methodName)
{
methodName = char.ToUpper(methodName[0]) + methodName.Substring(1);
if (methodName.StartsWith("With"))
{
methodName = methodName[4..];
}
return methodName + "Parameters";
}
/// <summary>
/// Generates the aspire.py SDK file with capability-based API.
/// </summary>
private string GenerateAspireSdk(AtsContext context)
{
_moduleBuilder = new PythonModuleBuilder();
var capabilities = context.Capabilities;
var dtoTypes = context.DtoTypes;
var enumTypes = context.EnumTypes;
// Get builder models (flattened - each builder has all its applicable capabilities)
var allBuilders = CreateBuilderModels(capabilities);
var entryPoints = GetEntryPointCapabilities(capabilities);
// All builders (no special filtering)
var builders = allBuilders;
// Collect all unique type IDs for handle type aliases
// Exclude DTO types - they have their own interfaces, not handle aliases
var dtoTypeIds = new HashSet<string>(dtoTypes.Select(d => d.TypeId));
var typeIds = new HashSet<string>();
foreach (var cap in capabilities)
{
if (!string.IsNullOrEmpty(cap.TargetTypeId) && !dtoTypeIds.Contains(cap.TargetTypeId))
{
typeIds.Add(cap.TargetTypeId);
}
if (IsHandleType(cap.ReturnType) && !dtoTypeIds.Contains(cap.ReturnType!.TypeId))
{
typeIds.Add(GetReturnTypeId(cap)!);
}
// Add parameter type IDs (for types like IResourceBuilder<IResource>)
foreach (var param in cap.Parameters)
{
if (IsHandleType(param.Type) && !dtoTypeIds.Contains(param.Type!.TypeId))
{
typeIds.Add(param.Type!.TypeId);
}
// Also collect callback parameter types
if (param.IsCallback && param.CallbackParameters != null)
{
foreach (var cbParam in param.CallbackParameters)
{
if (IsHandleType(cbParam.Type) && !dtoTypeIds.Contains(cbParam.Type.TypeId))
{
typeIds.Add(cbParam.Type.TypeId);
}
}
}
}
}
// Collect enum type names
foreach (var enumType in enumTypes)
{
if (!_enumTypeNames.ContainsKey(enumType.TypeId))
{
_enumTypeNames[enumType.TypeId] = ExtractSimpleTypeName(enumType.TypeId);
}
}
// Separate builders into categories:
// 1. Resource builders: IResource*, ContainerResource, etc.
// 2. Type classes: everything else (context types, wrapper types)
var resources = builders.Where(b => b.TargetType?.IsResourceBuilder == true).ToList();
var typeClasses = builders.Where(b => b.TargetType?.IsResourceBuilder != true).ToList();
var interfaceClasses = resources.Where(b => b.IsInterface).ToList();
// Build wrapper class name mapping for type resolution BEFORE generating code
// This allows parameter types to use wrapper class names instead of handle types
_wrapperClassNames.Clear();
foreach (var resource in resources)
{
_wrapperClassNames[resource.TypeId] = resource.BuilderClassName;
}
// Add ReferenceExpression (defined in base.py, not generated)
//_wrapperClassNames[AtsConstants.ReferenceExpressionTypeId] = "ReferenceExpression";
// Generate enum types
GenerateEnumTypes(enumTypes);
// Generate DTO classes
GenerateDtoClasses(dtoTypes);
// Generate type classes (context types and wrapper types)
foreach (var typeClass in typeClasses.Where(t => !_ignoreTypes.Contains(t.TypeId)))
{
GenerateTypeClass(typeClass);
}
// Generate interface ABC classes
foreach (var interfaceClass in interfaceClasses)
{
GenerateInterfaceClass(interfaceClass);
}
// Generate resource builder classes
foreach (var resource in resources.Where(b => !b.IsInterface))
{
GenerateBuilderClass(resource);
}
// Generate entry point functions
GenerateEntryPointFunctions(_moduleBuilder.EntryPoints, entryPoints);
return _moduleBuilder.Write();
}
/// <summary>
/// Generates Python enums from discovered enum types.
/// </summary>
private void GenerateEnumTypes(IReadOnlyList<AtsEnumTypeInfo> enumTypes)
{
var sb = _moduleBuilder.Enums;
if (enumTypes.Count == 0)
{
return;
}
foreach (var enumType in enumTypes.OrderBy(e => e.Name))
{
var enumName = _enumTypeNames[enumType.TypeId];
sb.AppendLine(CultureInfo.InvariantCulture, $"{enumName} = typing.Literal[{string.Join(", ", enumType.Values.Select(v => $"\"{v}\""))}]");
sb.AppendLine();
}
}
/// <summary>
/// Generates Python classes for DTO types marked with [AspireDto].
/// </summary>
private void GenerateDtoClasses(IReadOnlyList<AtsDtoTypeInfo> dtoTypes)
{
var sb = _moduleBuilder.DtoClasses;
if (dtoTypes.Count == 0)
{
return;
}
foreach (var dtoType in dtoTypes.OrderBy(d => d.Name))
{
var className = GetDtoClassName(dtoType.TypeId);
// All DTO properties are optional in Python to allow partial objects
sb.AppendLine(CultureInfo.InvariantCulture, $"class {className}(typing.TypedDict, total=False):");
foreach (var prop in dtoType.Properties)
{
var propType = MapTypeRefToPython(prop.Type);
sb.AppendLine(CultureInfo.InvariantCulture, $" {prop.Name}: {propType}");
}
sb.AppendLine();
}
}
/// <summary>
/// Converts a camelCase name to snake_case.
/// </summary>
private static string ToSnakeCase(string name)
{
if (string.IsNullOrEmpty(name))
{
return name;
}
var result = new System.Text.StringBuilder();
result.Append(char.ToLowerInvariant(name[0]));
for (int i = 1; i < name.Length; i++)
{
var c = name[i];
if (char.IsUpper(c))
{
result.Append('_');
result.Append(char.ToLowerInvariant(c));
}
else
{
result.Append(c);
}
}
var resultStr = result.ToString();
resultStr = resultStr.Replace("environment", "env");
resultStr = resultStr.Replace("configuration", "config");
resultStr = resultStr.Replace("application", "app");
resultStr = resultStr.Replace("variable", "var");
resultStr = resultStr.Replace("directory", "dir");
return SanitizePythonIdentifier(resultStr);
}
/// <summary>
/// Generates a type class (context type or wrapper type).
/// Uses property-like pattern for exposed properties.
/// </summary>
private void GenerateTypeClass(BuilderModel model)
{
var className = DeriveClassName(model.TypeId);
var sb = new System.Text.StringBuilder();
_moduleBuilder.TypeClasses[className] = sb;
// Separate capabilities by type using CapabilityKind enum
var getters = model.Capabilities.Where(c => c.CapabilityKind == AtsCapabilityKind.PropertyGetter).ToList();
var setters = model.Capabilities.Where(c => c.CapabilityKind == AtsCapabilityKind.PropertySetter).ToList();
var contextMethods = model.Capabilities.Where(c => c.CapabilityKind == AtsCapabilityKind.InstanceMethod).ToList();
var otherMethods = model.Capabilities.Where(c => c.CapabilityKind == AtsCapabilityKind.Method).ToList();
// Combine methods
var allMethods = contextMethods.Concat(otherMethods).ToList();
if (className == "AbstractDistributedApplicationBuilder")
{
sb.Append(PythonModuleBuilder.DistributedApplicationBuilder);
sb.AppendLine();
}
else
{
if (model.IsInterface && model.Capabilities.Count == 0)
{
sb.AppendLine(CultureInfo.InvariantCulture, $"class {className}(abc.ABC):");
sb.AppendLine(CultureInfo.InvariantCulture, $" \"\"\"Abstract base class for {className}.\"\"\"");
}
else
{
_moduleBuilder.HandleRegistrations[model.TypeId] = className;
sb.AppendLine(CultureInfo.InvariantCulture, $"class {className}:");
sb.AppendLine(CultureInfo.InvariantCulture, $" \"\"\"Type class for {className}.\"\"\"");
sb.AppendLine();
sb.AppendLine(" def __init__(self, handle: Handle, client: AspireClient) -> None:");
sb.AppendLine(" self._handle = handle");
sb.AppendLine(" self._client = client");
sb.AppendLine();
sb.AppendLine(" def __repr__(self) -> str:");
sb.AppendLine(CultureInfo.InvariantCulture, $" return f\"{className}(handle={{self._handle.handle_id}})\"");
sb.AppendLine();
sb.AppendLine(" @_uncached_property");
sb.AppendLine(" def handle(self) -> Handle:");
sb.AppendLine(" \"\"\"The underlying object reference handle.\"\"\"");
sb.AppendLine(" return self._handle");
sb.AppendLine();
}
}
// Group getters and setters by property name to create properties
var properties = GroupPropertiesByName(getters, setters);
// Generate properties
foreach (var prop in properties)
{
GeneratePropertyMethods(sb, prop.PropertyName, prop.Getter, prop.Setter);
}
// Generate methods
foreach (var method in allMethods)
{
GenerateTypeClassMethod(sb, method);
}
}
/// <summary>
/// Groups getters and setters by property name.
/// </summary>
private static List<(string PropertyName, AtsCapabilityInfo? Getter, AtsCapabilityInfo? Setter)> GroupPropertiesByName(
List<AtsCapabilityInfo> getters, List<AtsCapabilityInfo> setters)
{
var result = new List<(string PropertyName, AtsCapabilityInfo? Getter, AtsCapabilityInfo? Setter)>();
var processedNames = new HashSet<string>();
// Process getters
foreach (var getter in getters)
{
var propName = ExtractPropertyName(getter.MethodName);
if (processedNames.Contains(propName))
{
continue;
}
processedNames.Add(propName);
// Find matching setter (setPropertyName for propertyName)
var setterName = "set" + char.ToUpperInvariant(propName[0]) + propName[1..];
var setter = setters.FirstOrDefault(s => ExtractPropertyName(s.MethodName).Equals(setterName, StringComparison.OrdinalIgnoreCase));
result.Add((propName, getter, setter));
}
// Process any setters without matching getters
foreach (var setter in setters)
{
var setterMethodName = ExtractPropertyName(setter.MethodName);
// setPropertyName -> propertyName
if (setterMethodName.StartsWith("set", StringComparison.OrdinalIgnoreCase) && setterMethodName.Length > 3)
{
var propName = char.ToLowerInvariant(setterMethodName[3]) + setterMethodName[4..];
if (!processedNames.Contains(propName))
{
processedNames.Add(propName);
result.Add((propName, null, setter));
}
}
}
return result;
}
/// <summary>
/// Extracts the property name from a method name like "ClassName.propertyName" or "setPropertyName".
/// </summary>
private static string ExtractPropertyName(string methodName)
{
// Handle "ClassName.propertyName" format
if (methodName.Contains('.'))
{
return methodName[(methodName.LastIndexOf('.') + 1)..];
}
return methodName;
}
/// <summary>
/// Generates getter and setter methods for a property.
/// </summary>
private void GeneratePropertyMethods(System.Text.StringBuilder sb, string propertyName, AtsCapabilityInfo? getter, AtsCapabilityInfo? setter, bool isInterface = false)
{
var snakeName = ToSnakeCase(propertyName);
// Generate getter
if (getter != null)
{
if (propertyName == "cancellationToken")
{
// TODO: Replace this with handling for a CancelCallback exception.
// or maybe a cancel() method.
sb.AppendLine(CultureInfo.InvariantCulture, $" def cancel(self) -> None:");
sb.AppendLine(CultureInfo.InvariantCulture, $" \"\"\"Cancel the operation.\"\"\"");
if (isInterface)
{
return;
}
sb.AppendLine(CultureInfo.InvariantCulture, $" token: CancellationToken = self._client.invoke_capability(");
sb.AppendLine(CultureInfo.InvariantCulture, $" '{getter.CapabilityId}',");
sb.AppendLine(CultureInfo.InvariantCulture, $" {{'context': self._handle}}");
sb.AppendLine(CultureInfo.InvariantCulture, $" )");
sb.AppendLine(CultureInfo.InvariantCulture, $" token.cancel()");
sb.AppendLine();
return;
}
var returnType = MapTypeRefToPython(getter.ReturnType);
var propertyType = setter != null ? "@_uncached_property" : "@_cached_property";
if (!string.IsNullOrEmpty(getter.Description))
{
sb.AppendLine(CultureInfo.InvariantCulture, $" {propertyType}");
sb.AppendLine(CultureInfo.InvariantCulture, $" def {snakeName}(self) -> {returnType}:");
sb.AppendLine(CultureInfo.InvariantCulture, $" \"\"\"{getter.Description}\"\"\"");
}
else
{
sb.AppendLine(CultureInfo.InvariantCulture, $" {propertyType}");
sb.AppendLine(CultureInfo.InvariantCulture, $" def {snakeName}(self) -> {returnType}:");
sb.AppendLine(CultureInfo.InvariantCulture, $" \"\"\"{propertyName}\"\"\"");
}
if (!isInterface)
{
sb.AppendLine(CultureInfo.InvariantCulture, $" result = self._client.invoke_capability(");
sb.AppendLine(CultureInfo.InvariantCulture, $" '{getter.CapabilityId}',");
sb.AppendLine(CultureInfo.InvariantCulture, $" {{'context': self._handle}}");
sb.AppendLine(CultureInfo.InvariantCulture, $" )");
sb.AppendLine(CultureInfo.InvariantCulture, $" return typing.cast({returnType}, result)");
}
sb.AppendLine();
}
// Generate setter
if (setter != null)
{
var valueParam = setter.Parameters.FirstOrDefault(p => p.Name == "value");
if (valueParam != null)