-
Notifications
You must be signed in to change notification settings - Fork 726
/
TemplateWriter.cs
1503 lines (1298 loc) · 72.6 KB
/
TemplateWriter.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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using Azure.Deployments.Core.Definitions.Schema;
using Azure.Deployments.Core.Helpers;
using Bicep.Core.Extensions;
using Bicep.Core.Intermediate;
using Bicep.Core.Resources;
using Bicep.Core.Semantics;
using Bicep.Core.Semantics.Metadata;
using Bicep.Core.Semantics.Namespaces;
using Bicep.Core.Syntax;
using Bicep.Core.TypeSystem;
using Bicep.Core.TypeSystem.Providers.Az;
using Bicep.Core.TypeSystem.Types;
using Microsoft.WindowsAzure.ResourceStack.Common.Json;
using Newtonsoft.Json.Linq;
namespace Bicep.Core.Emit
{
// TODO: Are there discrepancies between parameter, variable, and output names between bicep and ARM?
public class TemplateWriter : ITemplateWriter
{
public const string GeneratorMetadataPath = "metadata._generator";
public const string NestedDeploymentResourceType = AzResourceTypeProvider.ResourceTypeDeployments;
public const string TemplateHashPropertyName = "templateHash";
public const string LanguageVersionPropertyName = "languageVersion";
// IMPORTANT: Do not update this API version until the new one is confirmed to be deployed and available in ALL the clouds.
public const string NestedDeploymentResourceApiVersion = "2022-09-01";
private const string TypePropertyName = "type";
private const string InternalTypeRefStart = "#";
private const string TypeDefinitionsProperty = "definitions";
private static ISemanticModel GetModuleSemanticModel(ModuleSymbol moduleSymbol)
{
if (!moduleSymbol.TryGetSemanticModel().IsSuccess(out var moduleSemanticModel))
{
// this should have already been checked during type assignment
throw new InvalidOperationException($"Unable to find referenced compilation for module {moduleSymbol.Name}");
}
return moduleSemanticModel;
}
private static string GetSchema(ResourceScope targetScope)
{
if (targetScope.HasFlag(ResourceScope.Tenant))
{
return "https://schema.management.azure.com/schemas/2019-08-01/tenantDeploymentTemplate.json#";
}
if (targetScope.HasFlag(ResourceScope.ManagementGroup))
{
return "https://schema.management.azure.com/schemas/2019-08-01/managementGroupDeploymentTemplate.json#";
}
if (targetScope.HasFlag(ResourceScope.Subscription))
{
return "https://schema.management.azure.com/schemas/2018-05-01/subscriptionDeploymentTemplate.json#";
}
return "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#";
}
private EmitterContext Context => ExpressionBuilder.Context;
private ExpressionBuilder ExpressionBuilder { get; }
private ImmutableDictionary<string, DeclaredTypeExpression> declaredTypesByName;
public TemplateWriter(SemanticModel semanticModel)
{
ExpressionBuilder = new ExpressionBuilder(new EmitterContext(semanticModel));
declaredTypesByName = ImmutableDictionary<string, DeclaredTypeExpression>.Empty;
}
public void Write(SourceAwareJsonTextWriter writer)
{
// Template is used for calcualting template hash, template jtoken is used for writing to file.
var (template, templateJToken) = GenerateTemplateWithoutHash(writer.TrackingJsonWriter);
var templateHash = TemplateHelpers.ComputeTemplateHash(template.ToJToken());
if (templateJToken.SelectToken(GeneratorMetadataPath) is not JObject generatorObject)
{
throw new InvalidOperationException($"generated template doesn't contain a generator object at the path {GeneratorMetadataPath}");
}
generatorObject.Add("templateHash", templateHash);
templateJToken.WriteTo(writer);
writer.ProcessSourceMap(templateJToken);
}
public (Template, JToken) GetTemplate(SourceAwareJsonTextWriter writer)
{
return GenerateTemplateWithoutHash(writer.TrackingJsonWriter);
}
private (Template, JToken) GenerateTemplateWithoutHash(PositionTrackingJsonTextWriter jsonWriter)
{
var emitter = new ExpressionEmitter(jsonWriter, this.Context);
var program = (ProgramExpression)ExpressionBuilder.Convert(Context.SemanticModel.Root.Syntax);
var programTypes = program.Types.Concat(Context.ImportClosureInfo.ImportedTypesInClosure);
declaredTypesByName = programTypes.ToImmutableDictionary(t => t.Name);
jsonWriter.WriteStartObject();
emitter.EmitProperty("$schema", GetSchema(Context.SemanticModel.TargetScope));
if (Context.Settings.UseExperimentalTemplateLanguageVersion)
{
emitter.EmitProperty(LanguageVersionPropertyName, "2.1-experimental");
}
else if (Context.Settings.EnableSymbolicNames)
{
emitter.EmitProperty(LanguageVersionPropertyName, "2.0");
}
emitter.EmitProperty("contentVersion", "1.0.0.0");
this.EmitMetadata(emitter, program.Metadata);
this.EmitTypeDefinitionsIfPresent(emitter, programTypes);
this.EmitUserDefinedFunctions(emitter, program.Functions.Concat(Context.ImportClosureInfo.ImportedFunctionsInClosure));
this.EmitParametersIfPresent(emitter, program.Parameters);
this.EmitVariablesIfPresent(emitter, program.Variables.Concat(Context.ImportClosureInfo.ImportedVariablesInClosure));
this.EmitProviders(emitter, program.Providers);
this.EmitResources(jsonWriter, emitter, program.Resources, program.Modules);
this.EmitOutputsIfPresent(emitter, program.Outputs);
this.EmitAssertsIfPresent(emitter, program.Asserts);
jsonWriter.WriteEndObject();
var content = jsonWriter.ToString();
return (Template.FromJson<Template>(content), content.FromJson<JToken>());
}
private void EmitTypeDefinitionsIfPresent(ExpressionEmitter emitter, IEnumerable<DeclaredTypeExpression> types)
{
if (!types.Any())
{
return;
}
emitter.EmitObjectProperty(TypeDefinitionsProperty, () =>
{
foreach (var type in types)
{
EmitTypeDeclaration(emitter, type);
}
});
}
private void EmitUserDefinedFunctions(ExpressionEmitter emitter, IEnumerable<DeclaredFunctionExpression> functions)
{
if (!functions.Any())
{
return;
}
emitter.EmitArrayProperty("functions", () =>
{
foreach (var ns in functions.GroupBy(f => f.Namespace))
{
emitter.EmitObject(() =>
{
emitter.EmitProperty("namespace", ns.Key);
emitter.EmitObjectProperty("members", () =>
{
foreach (var function in ns)
{
EmitUserDefinedFunction(emitter, function);
}
});
});
}
});
}
private void EmitParametersIfPresent(ExpressionEmitter emitter, ImmutableArray<DeclaredParameterExpression> parameters)
{
if (!parameters.Any())
{
return;
}
emitter.EmitObjectProperty("parameters", () =>
{
foreach (var parameter in parameters)
{
EmitParameter(emitter, parameter);
}
});
}
private static ObjectExpression ApplyTypeModifiers(TypeDeclaringExpression expression, ObjectExpression input)
{
var result = input;
if (expression.Secure is { } secure)
{
result = result.Properties.Where(p => p.Key is StringLiteralExpression { Value: string name } && name == "type").Single().Value switch
{
StringLiteralExpression { Value: string typeName } when typeName == LanguageConstants.TypeNameString
=> result.MergeProperty("type", ExpressionFactory.CreateStringLiteral("securestring", secure.SourceSyntax)),
StringLiteralExpression { Value: string typeName } when typeName == LanguageConstants.ObjectType
=> result.MergeProperty("type", ExpressionFactory.CreateStringLiteral("secureObject", secure.SourceSyntax)),
_ => result,
};
}
if (expression.Sealed is { } @sealed)
{
result = result.MergeProperty("additionalProperties", ExpressionFactory.CreateBooleanLiteral(false, @sealed.SourceSyntax));
}
if (expression is DeclaredTypeExpression declaredTypeExpression && declaredTypeExpression.Exported is { } exported)
{
result = ApplyMetadataProperty(result, LanguageConstants.MetadataExportedPropertyName, ExpressionFactory.CreateBooleanLiteral(true, exported.SourceSyntax));
}
foreach (var (modifier, propertyName) in new[]
{
(expression.Metadata, LanguageConstants.ParameterMetadataPropertyName),
(expression.MinLength, LanguageConstants.ParameterMinLengthPropertyName),
(expression.MaxLength, LanguageConstants.ParameterMaxLengthPropertyName),
(expression.MinValue, LanguageConstants.ParameterMinValuePropertyName),
(expression.MaxValue, LanguageConstants.ParameterMaxValuePropertyName),
})
{
if (modifier is not null)
{
result = result.MergeProperty(propertyName, modifier);
}
}
return ApplyDescription(expression, result);
}
private static ObjectExpression ApplyDescription(DescribableExpression expression, ObjectExpression input)
=> ApplyMetadataProperty(input, LanguageConstants.MetadataDescriptionPropertyName, expression.Description);
private static ObjectExpression ApplyMetadataProperty(ObjectExpression input, string propertyName, Expression? propertyValue) => propertyValue is not null
? input.MergeProperty(LanguageConstants.ParameterMetadataPropertyName, ExpressionFactory.CreateObject(
ExpressionFactory.CreateObjectProperty(propertyName, propertyValue, propertyValue.SourceSyntax).AsEnumerable(),
propertyValue.SourceSyntax))
: input;
private void EmitParameter(ExpressionEmitter emitter, DeclaredParameterExpression parameter)
{
emitter.EmitObjectProperty(parameter.Name, () =>
{
var parameterObject = TypePropertiesForTypeExpression(parameter.Type);
if (parameter.DefaultValue is not null)
{
parameterObject = parameterObject.MergeProperty("defaultValue", parameter.DefaultValue);
}
if (parameter.AllowedValues is not null)
{
parameterObject = parameterObject.MergeProperty("allowedValues", parameter.AllowedValues);
}
EmitProperties(emitter, ApplyTypeModifiers(parameter, parameterObject));
}, parameter.SourceSyntax);
}
private void EmitUserDefinedFunction(ExpressionEmitter emitter, DeclaredFunctionExpression function)
{
if (function.Lambda is not LambdaExpression lambda)
{
throw new ArgumentException("Invalid function expression lambda encountered.");
}
emitter.EmitObjectProperty(function.Name, () =>
{
emitter.EmitArrayProperty("parameters", () =>
{
for (var i = 0; i < lambda.Parameters.Length; i++)
{
var parameterObject = TypePropertiesForTypeExpression(lambda.ParameterTypes[i]!);
parameterObject = parameterObject.MergeProperty("name", new StringLiteralExpression(null, lambda.Parameters[i]));
emitter.EmitObject(() =>
{
EmitProperties(emitter, parameterObject);
});
}
});
emitter.EmitObjectProperty("output", () =>
{
var outputObject = TypePropertiesForTypeExpression(lambda.OutputType!);
outputObject = outputObject.MergeProperty("value", lambda.Body);
EmitProperties(emitter, outputObject);
});
var originMetadataLookupKey = function.Namespace == EmitConstants.UserDefinedFunctionsNamespace
? function.Name
: $"{function.Namespace}.{function.Name}";
if (function.Description is not null || function.Exported is not null || Context.ImportClosureInfo.ImportedSymbolOriginMetadata.ContainsKey(originMetadataLookupKey))
{
emitter.EmitObjectProperty(LanguageConstants.ParameterMetadataPropertyName, () =>
{
if (function.Description is not null)
{
emitter.EmitProperty(LanguageConstants.MetadataDescriptionPropertyName, function.Description);
}
if (function.Exported is not null)
{
emitter.EmitProperty(LanguageConstants.MetadataExportedPropertyName, ExpressionFactory.CreateBooleanLiteral(true, function.Exported.SourceSyntax));
}
if (Context.ImportClosureInfo.ImportedSymbolOriginMetadata.TryGetValue(originMetadataLookupKey, out var originMetadata))
{
emitter.EmitObjectProperty(LanguageConstants.MetadataImportedFromPropertyName, () =>
{
emitter.EmitProperty(LanguageConstants.ImportMetadataSourceTemplatePropertyName, originMetadata.SourceTemplateIdentifier);
if (!function.Name.Equals(originMetadata.OriginalName))
{
emitter.EmitProperty(LanguageConstants.ImportMetadataOriginalIdentifierPropertyName, originMetadata.OriginalName);
}
});
}
});
}
}, function.SourceSyntax);
}
private void EmitProperties(ExpressionEmitter emitter, ObjectExpression objectExpression)
{
foreach (var property in objectExpression.Properties)
{
if (property.TryGetKeyText() is string propertyName)
{
emitter.EmitProperty(propertyName, property.Value);
}
}
}
private void EmitTypeDeclaration(ExpressionEmitter emitter, DeclaredTypeExpression declaredType)
{
emitter.EmitObjectProperty(declaredType.Name,
() =>
{
var declaredTypeObject = ApplyTypeModifiers(declaredType, TypePropertiesForTypeExpression(declaredType.Value));
if (Context.ImportClosureInfo.ImportedSymbolOriginMetadata.TryGetValue(declaredType.Name, out var originMetadata))
{
var importedFromProperties = ExpressionFactory.CreateObjectProperty(LanguageConstants.ImportMetadataSourceTemplatePropertyName,
ExpressionFactory.CreateStringLiteral(originMetadata.SourceTemplateIdentifier)).AsEnumerable();
if (!declaredType.Name.EndsWith(originMetadata.OriginalName))
{
importedFromProperties = importedFromProperties.Append(ExpressionFactory.CreateObjectProperty(LanguageConstants.ImportMetadataOriginalIdentifierPropertyName,
ExpressionFactory.CreateStringLiteral(originMetadata.OriginalName)));
}
declaredTypeObject = ApplyMetadataProperty(declaredTypeObject, LanguageConstants.MetadataImportedFromPropertyName, ExpressionFactory.CreateObject(importedFromProperties));
}
EmitProperties(emitter, declaredTypeObject);
},
declaredType.SourceSyntax);
}
private ObjectExpression TypePropertiesForTypeExpression(TypeExpression typeExpression) => typeExpression switch
{
// ARM primitive types
AmbientTypeReferenceExpression ambientTypeReference
=> ExpressionFactory.CreateObject(TypeProperty(ambientTypeReference.Name, ambientTypeReference.SourceSyntax).AsEnumerable(),
ambientTypeReference.SourceSyntax),
FullyQualifiedAmbientTypeReferenceExpression fullyQualifiedAmbientTypeReference
=> TypePropertiesForQualifiedReference(fullyQualifiedAmbientTypeReference),
// references
TypeAliasReferenceExpression or
SynthesizedTypeAliasReferenceExpression or
ImportedTypeReferenceExpression or
WildcardImportTypePropertyReferenceExpression or
ResourceDerivedTypeExpression or
ITypeReferenceAccessExpression => GetTypePropertiesForReferenceExpression(typeExpression),
// literals
StringLiteralTypeExpression @string => ExpressionFactory.CreateObject(
new[]
{
TypeProperty(LanguageConstants.TypeNameString, @string.SourceSyntax),
AllowedValuesProperty(SingleElementArray(ExpressionFactory.CreateStringLiteral(@string.Value, @string.SourceSyntax)),
@string.SourceSyntax),
},
@string.SourceSyntax),
IntegerLiteralTypeExpression @int => ExpressionFactory.CreateObject(
new[]
{
TypeProperty(LanguageConstants.TypeNameInt, @int.SourceSyntax),
AllowedValuesProperty(SingleElementArray(ExpressionFactory.CreateIntegerLiteral(@int.Value, @int.SourceSyntax)),
@int.SourceSyntax),
},
@int.SourceSyntax),
BooleanLiteralTypeExpression @bool => ExpressionFactory.CreateObject(
new[]
{
TypeProperty(LanguageConstants.TypeNameBool, @bool.SourceSyntax),
AllowedValuesProperty(SingleElementArray(ExpressionFactory.CreateBooleanLiteral(@bool.Value, @bool.SourceSyntax)),
@bool.SourceSyntax),
},
@bool.SourceSyntax),
UnionTypeExpression unionType => GetTypePropertiesForUnionTypeExpression(unionType),
// resource types
ResourceTypeExpression resourceType => GetTypePropertiesForResourceType(resourceType),
// aggregate types
ArrayTypeExpression arrayType => GetTypePropertiesForArrayType(arrayType),
ObjectTypeExpression objectType => GetTypePropertiesForObjectType(objectType),
TupleTypeExpression tupleType => GetTypePropertiesForTupleType(tupleType),
NullableTypeExpression nullableType => TypePropertiesForTypeExpression(nullableType.BaseExpression)
.MergeProperty("nullable", ExpressionFactory.CreateBooleanLiteral(true, nullableType.SourceSyntax)),
NonNullableTypeExpression nonNullableType => TypePropertiesForTypeExpression(nonNullableType.BaseExpression)
.MergeProperty("nullable", ExpressionFactory.CreateBooleanLiteral(false, nonNullableType.SourceSyntax)),
DiscriminatedObjectTypeExpression discriminatedObject => GetTypePropertiesForDiscriminatedObjectExpression(discriminatedObject),
// this should have been caught by the parser
_ => throw new ArgumentException("Invalid type expression encountered."),
};
private ObjectExpression GetTypePropertiesForReferenceExpression(TypeExpression typeExpression)
=> ResolveTypeReferenceExpression(typeExpression)
.GetTypePropertiesForResolvedReferenceExpression(typeExpression.SourceSyntax);
private interface ITypeReferenceExpressionResolution
{
ImmutableArray<string> PointerSegments { get; }
ObjectExpression GetTypePropertiesForResolvedReferenceExpression(SyntaxBase? sourceSyntax);
ImmutableArray<string> SegmentsForProperty(string propertyName)
=> PointerSegments.AddRange("properties", propertyName);
ImmutableArray<string> SegmentsForAdditionalProperties()
=> PointerSegments.Add("additionalProperties");
ImmutableArray<string> SegmentsForIndex(long index)
=> PointerSegments.AddRange("prefixItems", index.ToString(CultureInfo.InvariantCulture));
ImmutableArray<string> SegmentsForItems()
=> PointerSegments.Add("items");
ImmutableArray<string> SegmentsForVariant(string discriminatorValue)
=> PointerSegments.AddRange("discriminator", "mapping", discriminatorValue);
}
private record ResourceDerivedTypeResolution(ResourceTypeReference RootResourceTypeReference, ImmutableArray<string> PointerSegments, TypeSymbol DerivedType) : ITypeReferenceExpressionResolution
{
internal ResourceDerivedTypeResolution(ResourceDerivedTypeExpression expression)
: this(expression.RootResourceType.TypeReference, ImmutableArray<string>.Empty, expression.RootResourceType.Body.Type) { }
public ObjectExpression GetTypePropertiesForResolvedReferenceExpression(SyntaxBase? sourceSyntax)
=> ExpressionFactory.CreateObject(new[]
{
TypeProperty(GetNonLiteralTypeName(DerivedType), sourceSyntax),
ExpressionFactory.CreateObjectProperty(LanguageConstants.ParameterMetadataPropertyName,
ExpressionFactory.CreateObject(
ExpressionFactory.CreateObjectProperty(LanguageConstants.MetadataResourceDerivedTypePropertyName,
ExpressionFactory.CreateStringLiteral(
PointerSegments.IsEmpty
? RootResourceTypeReference.FormatName()
: $"{RootResourceTypeReference.FormatName()}#{string.Join('/', PointerSegments.Select(StringExtensions.Rfc6901Encode))}",
sourceSyntax),
sourceSyntax).AsEnumerable(),
sourceSyntax),
sourceSyntax),
});
}
private record ResolvedInternalReference(ImmutableArray<string> PointerSegments, TypeExpression Declaration) : ITypeReferenceExpressionResolution
{
public ObjectExpression GetTypePropertiesForResolvedReferenceExpression(SyntaxBase? sourceSyntax)
=> ExpressionFactory.CreateObject(
ExpressionFactory.CreateObjectProperty("$ref",
ExpressionFactory.CreateStringLiteral(
string.Join('/', InternalTypeRefStart.AsEnumerable().Concat(PointerSegments.Select(StringExtensions.Rfc6901Encode))),
sourceSyntax),
sourceSyntax).AsEnumerable(),
sourceSyntax);
}
private ResolvedInternalReference ForNamedRoot(string rootName)
=> new(ImmutableArray.Create(TypeDefinitionsProperty, rootName), declaredTypesByName[rootName].Value);
private ITypeReferenceExpressionResolution ResolveTypeReferenceExpression(TypeExpression expression)
{
Stack<ITypeReferenceAccessExpression> typeReferencesStack = new();
TypeExpression root = expression;
while (root is ITypeReferenceAccessExpression accessExpression)
{
typeReferencesStack.Push(accessExpression);
root = accessExpression.BaseExpression;
}
ITypeReferenceExpressionResolution currentResolution = root switch
{
TypeAliasReferenceExpression typeAliasReference => ForNamedRoot(typeAliasReference.Symbol.Name),
SynthesizedTypeAliasReferenceExpression typeAliasReference => ForNamedRoot(typeAliasReference.Name),
ImportedTypeReferenceExpression importedTypeReference => ForNamedRoot(
Context.ImportClosureInfo.ImportedSymbolNames[importedTypeReference.Symbol]),
WildcardImportTypePropertyReferenceExpression importedTypeReference => ForNamedRoot(
Context.ImportClosureInfo.WildcardImportPropertyNames[new(importedTypeReference.ImportSymbol, importedTypeReference.PropertyName)]),
ResourceDerivedTypeExpression resourceDerived => new ResourceDerivedTypeResolution(resourceDerived),
_ => throw new ArgumentException($"Cannot resolve type reference access expression with a root of type '{root.GetType().Name}'."),
};
while (typeReferencesStack.TryPop(out var currentAccessExpression))
{
currentResolution = currentAccessExpression switch
{
TypeReferencePropertyAccessExpression propertyAccess
=> ResolveTypeReferenceExpressionProperty(currentResolution, propertyAccess),
TypeReferenceAdditionalPropertiesAccessExpression additionalPropertiesAccess
=> ResolveTypeReferenceExpressionAdditionalProperties(currentResolution, additionalPropertiesAccess),
TypeReferenceIndexAccessExpression indexAccess
=> ResolveTypeReferenceExpressionIndex(currentResolution, indexAccess),
TypeReferenceItemsAccessExpression itemsAccess
=> ResolveTypeReferenceExpressionItems(currentResolution, itemsAccess),
_ => throw new UnreachableException(
$"This switch expression should be exhaustive, but received an unexpected reference access expression of type {currentAccessExpression.GetType().Name}."),
};
}
return currentResolution;
}
private ITypeReferenceExpressionResolution ResolveTypeReferenceExpressionProperty(
ITypeReferenceExpressionResolution containerResolution,
TypeReferencePropertyAccessExpression propertyAccess)
{
var (resolution, declaration) = TraceToObjectDeclaration(containerResolution);
if (declaration is not null)
{
return new ResolvedInternalReference(
resolution.SegmentsForProperty(propertyAccess.PropertyName),
declaration.PropertyExpressions
.Single(p => StringComparer.OrdinalIgnoreCase.Equals(p.PropertyName, propertyAccess.PropertyName))
.Value);
}
if (resolution is ResourceDerivedTypeResolution resourceDerived)
{
return new ResourceDerivedTypeResolution(
resourceDerived.RootResourceTypeReference,
resolution.SegmentsForProperty(propertyAccess.PropertyName),
propertyAccess.ExpressedType);
}
throw new ArgumentException($"Unable to handle resolution of type {resolution.GetType().Name}.");
}
private ITypeReferenceExpressionResolution ResolveTypeReferenceExpressionAdditionalProperties(
ITypeReferenceExpressionResolution containerResolution,
TypeReferenceAdditionalPropertiesAccessExpression additionalPropertiesAccess)
{
var (resolution, declaration) = TraceToObjectDeclaration(containerResolution);
if (declaration is not null)
{
if (declaration.AdditionalPropertiesExpression is null)
{
throw new ArgumentException("This should have been caught by the type checker.");
}
return new ResolvedInternalReference(
resolution.SegmentsForAdditionalProperties(),
declaration.AdditionalPropertiesExpression.Value);
}
if (resolution is ResourceDerivedTypeResolution resourceDerived)
{
return new ResourceDerivedTypeResolution(
resourceDerived.RootResourceTypeReference,
resolution.SegmentsForAdditionalProperties(),
additionalPropertiesAccess.ExpressedType);
}
throw new ArgumentException($"Unable to handle resolution of type {resolution.GetType().Name}.");
}
private (ITypeReferenceExpressionResolution resolution, ObjectTypeExpression? declaration) TraceToObjectDeclaration(ITypeReferenceExpressionResolution original)
{
var currentResolution = original;
while (currentResolution is ResolvedInternalReference @ref)
{
if (@ref.Declaration is ObjectTypeExpression @object)
{
return (currentResolution, @object);
}
currentResolution = ResolveTypeReferenceExpression(@ref.Declaration);
}
return (currentResolution, null);
}
private ITypeReferenceExpressionResolution ResolveTypeReferenceExpressionIndex(
ITypeReferenceExpressionResolution containerResolution,
TypeReferenceIndexAccessExpression indexAccess)
{
var currentResolution = containerResolution;
while (currentResolution is ResolvedInternalReference @ref)
{
if (@ref.Declaration is TupleTypeExpression tuple)
{
return new ResolvedInternalReference(
currentResolution.SegmentsForIndex(indexAccess.Index),
tuple.ItemExpressions[(int)indexAccess.Index].Value);
}
currentResolution = ResolveTypeReferenceExpression(@ref.Declaration);
}
if (currentResolution is ResourceDerivedTypeResolution resourceDerived)
{
return new ResourceDerivedTypeResolution(
resourceDerived.RootResourceTypeReference,
currentResolution.SegmentsForIndex(indexAccess.Index),
indexAccess.ExpressedType);
}
throw new ArgumentException($"Unable to handle resolution of type {currentResolution.GetType().Name}.");
}
private ITypeReferenceExpressionResolution ResolveTypeReferenceExpressionItems(
ITypeReferenceExpressionResolution containerResolution,
TypeReferenceItemsAccessExpression itemsAccess)
{
var currentResolution = containerResolution;
while (currentResolution is ResolvedInternalReference @ref)
{
if (@ref.Declaration is ArrayTypeExpression @array)
{
return new ResolvedInternalReference(
currentResolution.SegmentsForItems(),
@array.BaseExpression);
}
currentResolution = ResolveTypeReferenceExpression(@ref.Declaration);
}
if (currentResolution is ResourceDerivedTypeResolution resourceDerived)
{
return new ResourceDerivedTypeResolution(
resourceDerived.RootResourceTypeReference,
currentResolution.SegmentsForItems(),
itemsAccess.ExpressedType);
}
throw new ArgumentException($"Unable to handle resolution of type {currentResolution.GetType().Name}.");
}
private static ObjectExpression TypePropertiesForQualifiedReference(FullyQualifiedAmbientTypeReferenceExpression qualifiedAmbientType)
{
if (qualifiedAmbientType.ProviderName != SystemNamespaceType.BuiltInName)
{
throw new ArgumentException("Property access base expression did not resolve to the 'sys' namespace.");
}
return ExpressionFactory.CreateObject(TypeProperty(qualifiedAmbientType.Name, qualifiedAmbientType.SourceSyntax).AsEnumerable(),
qualifiedAmbientType.SourceSyntax);
}
private static ObjectPropertyExpression TypeProperty(string typeName, SyntaxBase? sourceSyntax)
=> Property(TypePropertyName, new StringLiteralExpression(sourceSyntax, typeName), sourceSyntax);
private static ObjectPropertyExpression AllowedValuesProperty(ArrayExpression allowedValues, SyntaxBase? sourceSyntax)
=> Property("allowedValues", allowedValues, sourceSyntax);
private static ObjectPropertyExpression Property(string name, Expression value, SyntaxBase? sourceSyntax)
=> ExpressionFactory.CreateObjectProperty(name, value, sourceSyntax);
private static ObjectExpression GetTypePropertiesForResourceType(ResourceTypeExpression expression)
{
var typeString = expression.ExpressedResourceType.TypeReference.FormatName();
return ExpressionFactory.CreateObject(new[]
{
TypeProperty(LanguageConstants.TypeNameString, expression.SourceSyntax),
ExpressionFactory.CreateObjectProperty(LanguageConstants.ParameterMetadataPropertyName,
ExpressionFactory.CreateObject(
ExpressionFactory.CreateObjectProperty(LanguageConstants.MetadataResourceTypePropertyName,
ExpressionFactory.CreateStringLiteral(typeString, expression.SourceSyntax),
expression.SourceSyntax).AsEnumerable(),
expression.SourceSyntax),
expression.SourceSyntax),
});
}
private ObjectExpression GetTypePropertiesForArrayType(ArrayTypeExpression expression)
{
var properties = new List<ObjectPropertyExpression> { TypeProperty(LanguageConstants.ArrayType, expression.SourceSyntax) };
if (TryGetAllowedValues(expression.BaseExpression) is { } allowedValues)
{
properties.Add(AllowedValuesProperty(allowedValues, expression.BaseExpression.SourceSyntax));
}
else
{
properties.Add(ExpressionFactory.CreateObjectProperty("items", TypePropertiesForTypeExpression(expression.BaseExpression)));
}
return ExpressionFactory.CreateObject(properties, expression.SourceSyntax);
}
private static ArrayExpression? TryGetAllowedValues(TypeExpression expression) => expression switch
{
StringLiteralTypeExpression @string => SingleElementArray(ExpressionFactory.CreateStringLiteral(@string.Value, @string.SourceSyntax)),
IntegerLiteralTypeExpression @int => SingleElementArray(ExpressionFactory.CreateIntegerLiteral(@int.Value, @int.SourceSyntax)),
BooleanLiteralTypeExpression @bool => SingleElementArray(ExpressionFactory.CreateBooleanLiteral(@bool.Value, @bool.SourceSyntax)),
NullLiteralTypeExpression @null => SingleElementArray(new NullLiteralExpression(@null.SourceSyntax)),
ObjectTypeExpression @object when TypeHelper.IsLiteralType(@object.ExpressedType) => SingleElementArray(ToLiteralValue(@object.ExpressedType)),
TupleTypeExpression tuple when TypeHelper.IsLiteralType(tuple.ExpressedType) => SingleElementArray(ToLiteralValue(tuple.ExpressedType)),
UnionTypeExpression union => GetAllowedValuesForUnionType(union.ExpressedUnionType, union.SourceSyntax),
_ => null,
};
private static ArrayExpression SingleElementArray(Expression expression) => ExpressionFactory.CreateArray(expression.AsEnumerable());
private static ArrayExpression GetAllowedValuesForUnionType(UnionType unionType, SyntaxBase? sourceSyntax)
=> ExpressionFactory.CreateArray(unionType.Members.Select(ToLiteralValue), sourceSyntax);
private ObjectExpression GetTypePropertiesForObjectType(ObjectTypeExpression expression)
{
var properties = new List<ObjectPropertyExpression> { TypeProperty(LanguageConstants.ObjectType, expression.SourceSyntax) };
List<ObjectPropertyExpression> propertySchemata = new();
foreach (var property in expression.PropertyExpressions)
{
var propertySchema = ApplyTypeModifiers(property, TypePropertiesForTypeExpression(property.Value));
propertySchemata.Add(ExpressionFactory.CreateObjectProperty(property.PropertyName, propertySchema, property.SourceSyntax));
}
properties.Add(ExpressionFactory.CreateObjectProperty("properties", ExpressionFactory.CreateObject(propertySchemata, expression.SourceSyntax)));
if (expression.AdditionalPropertiesExpression is { } addlPropsType)
{
var addlPropertiesSchema = ApplyTypeModifiers(addlPropsType, TypePropertiesForTypeExpression(addlPropsType.Value));
properties.Add(ExpressionFactory.CreateObjectProperty("additionalProperties", addlPropertiesSchema, addlPropsType.SourceSyntax));
}
return ExpressionFactory.CreateObject(properties, expression.SourceSyntax);
}
private ObjectExpression GetTypePropertiesForTupleType(TupleTypeExpression expression) => ExpressionFactory.CreateObject(new[]
{
TypeProperty(LanguageConstants.ArrayType, expression.SourceSyntax),
ExpressionFactory.CreateObjectProperty("prefixItems",
ExpressionFactory.CreateArray(
expression.ItemExpressions.Select(item => ApplyTypeModifiers(item, TypePropertiesForTypeExpression(item.Value))),
expression.SourceSyntax),
expression.SourceSyntax),
ExpressionFactory.CreateObjectProperty("items", ExpressionFactory.CreateBooleanLiteral(false), expression.SourceSyntax),
});
private ObjectExpression GetTypePropertiesForUnionTypeExpression(UnionTypeExpression expression)
{
var (nullable, nonLiteralTypeName, allowedValues) = TypeHelper.TryRemoveNullability(expression.ExpressedUnionType) switch
{
UnionType nonNullableUnion => (true, GetNonLiteralTypeName(nonNullableUnion.Members.First().Type), GetAllowedValuesForUnionType(nonNullableUnion, expression.SourceSyntax)),
TypeSymbol nonNullable => (true, GetNonLiteralTypeName(nonNullable), SingleElementArray(ToLiteralValue(nonNullable))),
_ => (false, GetNonLiteralTypeName(expression.ExpressedUnionType.Members.First().Type), GetAllowedValuesForUnionType(expression.ExpressedUnionType, expression.SourceSyntax)),
};
var properties = new List<ObjectPropertyExpression>
{
TypeProperty(nonLiteralTypeName, expression.SourceSyntax),
AllowedValuesProperty(allowedValues, expression.SourceSyntax),
};
if (nullable)
{
properties.Add(ExpressionFactory.CreateObjectProperty("nullable", ExpressionFactory.CreateBooleanLiteral(true), expression.SourceSyntax));
}
return ExpressionFactory.CreateObject(properties, expression.SourceSyntax);
}
private ObjectExpression GetTypePropertiesForDiscriminatedObjectExpression(DiscriminatedObjectTypeExpression expression)
{
var properties = new List<ObjectPropertyExpression>
{
TypeProperty("object", expression.SourceSyntax),
ExpressionFactory.CreateObjectProperty(
"discriminator",
GetTypePropertiesForDiscriminator(expression),
expression.SourceSyntax),
};
return ExpressionFactory.CreateObject(properties, expression.SourceSyntax);
}
private ObjectExpression GetTypePropertiesForDiscriminator(
DiscriminatedObjectTypeExpression discriminatedObjectTypeExpr)
{
var objectProperties = new List<ObjectPropertyExpression>();
var discriminatorPropertyName = discriminatedObjectTypeExpr.ExpressedDiscriminatedObjectType.DiscriminatorProperty.Name;
objectProperties.Add(ExpressionFactory.CreateObjectProperty("propertyName", ExpressionFactory.CreateStringLiteral(discriminatorPropertyName)));
objectProperties.Add(
ExpressionFactory.CreateObjectProperty(
"mapping",
ExpressionFactory.CreateObject(
GetDiscriminatedUnionMappingEntries(discriminatedObjectTypeExpr))));
return ExpressionFactory.CreateObject(properties: objectProperties);
}
private IEnumerable<ObjectPropertyExpression> GetDiscriminatedUnionMappingEntries(DiscriminatedObjectTypeExpression discriminatedObjectTypeExpr)
{
var discriminatorPropertyName = discriminatedObjectTypeExpr.ExpressedDiscriminatedObjectType.DiscriminatorProperty.Name;
foreach (var memberExpression in discriminatedObjectTypeExpr.MemberExpressions)
{
var mappingsEnumerable = memberExpression switch
{
TypeAliasReferenceExpression or
SynthesizedTypeAliasReferenceExpression or
ImportedTypeReferenceExpression or
WildcardImportTypePropertyReferenceExpression or
ITypeReferenceAccessExpression => ResolveTypeReferenceExpression(memberExpression) switch
{
ResolvedInternalReference udtRef => GetDiscriminatedUnionMappingEntries(discriminatorPropertyName, udtRef.Declaration, udtRef),
ResourceDerivedTypeResolution rdtRef => GetDiscriminatedUnionMappingEntries(discriminatorPropertyName, rdtRef),
_ => throw new UnreachableException(),
},
_ => GetDiscriminatedUnionMappingEntries(discriminatorPropertyName, memberExpression, null),
};
foreach (var mapping in mappingsEnumerable)
{
yield return mapping;
}
}
}
private IEnumerable<ObjectPropertyExpression> GetDiscriminatedUnionMappingEntries(
string discriminatorPropertyName,
TypeExpression memberDeclaration,
ITypeReferenceExpressionResolution? memberResolution)
{
if (memberDeclaration is ObjectTypeExpression objectUnionMemberExpr)
{
yield return ExpressionFactory.CreateObjectProperty(
DiscriminatorValue(discriminatorPropertyName, objectUnionMemberExpr.ExpressedObjectType),
memberResolution?.GetTypePropertiesForResolvedReferenceExpression(sourceSyntax: null)
?? GetTypePropertiesForObjectType(objectUnionMemberExpr));
}
else if (memberDeclaration is DiscriminatedObjectTypeExpression nestedDiscriminatedMemberExpr)
{
var nestedDiscriminatorPropertyName = nestedDiscriminatedMemberExpr.ExpressedDiscriminatedObjectType.DiscriminatorProperty.Name;
if (nestedDiscriminatorPropertyName != discriminatorPropertyName)
{
// This should have been caught during type checking
throw new ArgumentException("Invalid discriminated union type encountered during serialization.");
}
foreach (var nestedPropertyExpr in GetDiscriminatedUnionMappingEntries(nestedDiscriminatedMemberExpr))
{
yield return nestedPropertyExpr;
}
}
else
{
// This should have been caught during type checking
throw new ArgumentException("Invalid discriminated union type encountered during serialization.");
}
}
private static IEnumerable<ObjectPropertyExpression> GetDiscriminatedUnionMappingEntries(
string discriminatorPropertyName,
ResourceDerivedTypeResolution resolution)
{
if (resolution.DerivedType is ObjectType @object)
{
yield return ExpressionFactory.CreateObjectProperty(
DiscriminatorValue(discriminatorPropertyName, @object),
resolution.GetTypePropertiesForResolvedReferenceExpression(sourceSyntax: null));
}
else if (resolution.DerivedType is DiscriminatedObjectType discriminatedObject)
{
foreach (var variant in discriminatedObject.UnionMembersByKey.Values)
{
var discriminatorValue = DiscriminatorValue(discriminatorPropertyName, variant);
var variantResolution = new ResourceDerivedTypeResolution(
resolution.RootResourceTypeReference,
(resolution as ITypeReferenceExpressionResolution).SegmentsForVariant(discriminatorValue),
variant);
yield return ExpressionFactory.CreateObjectProperty(
discriminatorValue,
variantResolution.GetTypePropertiesForResolvedReferenceExpression(sourceSyntax: null));
}
}
else
{
// This should have been caught during type checking
throw new ArgumentException("Invalid discriminated union type encountered during serialization.");
}
}
private static string DiscriminatorValue(string discriminatorPropertyName, ObjectType @object)
{
if (!@object.Properties.TryGetValue(discriminatorPropertyName, out var discriminatorTypeProperty)
|| discriminatorTypeProperty.TypeReference.Type is not StringLiteralType discriminatorStringLiteral)
{
// This should have been caught during type checking
throw new ArgumentException("Invalid discriminated union type encountered during serialization.");
}
return discriminatorStringLiteral.RawStringValue;
}
private static Expression ToLiteralValue(ITypeReference literalType) => literalType.Type switch
{
StringLiteralType @string => ExpressionFactory.CreateStringLiteral(@string.RawStringValue),
IntegerLiteralType @int => new IntegerLiteralExpression(null, @int.Value),
BooleanLiteralType @bool => ExpressionFactory.CreateBooleanLiteral(@bool.Value),
NullType => new NullLiteralExpression(null),
ObjectType @object => ExpressionFactory.CreateObject(@object.Properties.Select(kvp => ExpressionFactory.CreateObjectProperty(kvp.Key, ToLiteralValue(kvp.Value.TypeReference)))),
TupleType tuple => ExpressionFactory.CreateArray(tuple.Items.Select(ToLiteralValue)),
// This would have been caught by the DeclaredTypeManager during initial type assignment
_ => throw new ArgumentException("Union types used in ARM type checks must be composed entirely of literal types"),
};
private static string GetNonLiteralTypeName(TypeSymbol? type) => type switch
{
StringLiteralType or StringType => "string",
IntegerLiteralType or IntegerType => "int",
BooleanLiteralType or BooleanType => "bool",
ObjectType or DiscriminatedObjectType => "object",
ArrayType => "array",
UnionType @union => @union.Members.Select(m => GetNonLiteralTypeName(m.Type)).Distinct().Single(),
// This would have been caught by the DeclaredTypeManager during initial type assignment
_ => throw new ArgumentException($"Cannot resolve nonliteral type name of type {type?.GetType().Name}"),
};
private void EmitVariablesIfPresent(ExpressionEmitter emitter, IEnumerable<DeclaredVariableExpression> variables)
{
if (!variables.Any())
{
return;
}
emitter.EmitObjectProperty("variables", () =>
{
var loopVariables = variables.Where(x => x is { Value: ForLoopExpression });
var nonLoopVariables = variables.Where(x => x is { Value: not ForLoopExpression });
if (loopVariables.Any())
{
// we have variables whose values are loops
emitter.EmitArrayProperty("copy", () =>
{
foreach (var loopVariable in loopVariables)
{
var forLoopVariable = (ForLoopExpression)loopVariable.Value;
emitter.EmitCopyObject(loopVariable.Name, forLoopVariable.Expression, forLoopVariable.Body);
}
});
}
// emit non-loop variables
foreach (var variable in nonLoopVariables)
{
emitter.EmitProperty(variable.Name, variable.Value);
}
});
}
private void EmitProviders(ExpressionEmitter emitter, ImmutableArray<DeclaredProviderExpression> providers)
{
if (!providers.Any())
{
return;
}
emitter.EmitObjectProperty("imports", () =>
{
foreach (var provider in providers)
{