-
Notifications
You must be signed in to change notification settings - Fork 727
/
ArmDeclarationToExpressionConverter.cs
535 lines (474 loc) · 26.6 KB
/
ArmDeclarationToExpressionConverter.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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.Immutable;
using Azure.Deployments.Core.Definitions.Schema;
using Azure.Deployments.Core.Entities;
using Azure.Deployments.Expression.Engines;
using Azure.Deployments.Expression.Expressions;
using Azure.Deployments.Templates.Extensions;
using Bicep.Core.ArmHelpers;
using Bicep.Core.Extensions;
using Bicep.Core.Intermediate;
using Bicep.Core.Parsing;
using Bicep.Core.Syntax;
using Bicep.Core.TypeSystem;
using Bicep.Core.TypeSystem.Types;
using Microsoft.WindowsAzure.ResourceStack.Common.Extensions;
using Newtonsoft.Json.Linq;
namespace Bicep.Core.Emit.CompileTimeImports;
internal class ArmDeclarationToExpressionConverter
{
private const string VariablesFunctionName = "variables";
private const string CopyIndexFunctionName = "copyindex";
private readonly SchemaValidationContext schemaContext;
private readonly ImmutableDictionary<string, TemplateFunction> functionsByFullyQualifiedName;
private readonly TemplateVariablesEvaluator variablesEvaluator;
private readonly ImmutableDictionary<ArmIdentifier, string> armIdentifierToSymbolNameMapping;
private readonly SyntaxBase? sourceSyntax;
private string? activeCopyLoopName;
internal ArmDeclarationToExpressionConverter(Template template,
ImmutableDictionary<ArmIdentifier, string> armIdentifierToSymbolNameMapping,
SyntaxBase? sourceSyntax) : this(SchemaValidationContext.ForTemplate(template),
template.GetFunctionDefinitions().ToImmutableDictionary(fd => fd.Key, fd => fd.Function, StringComparer.OrdinalIgnoreCase),
new(template),
armIdentifierToSymbolNameMapping,
sourceSyntax)
{ }
private ArmDeclarationToExpressionConverter(SchemaValidationContext schemaContext,
ImmutableDictionary<string, TemplateFunction> functionsByFullyQualifiedName,
TemplateVariablesEvaluator variablesEvaluator,
ImmutableDictionary<ArmIdentifier, string> armIdentifierToSymbolNameMapping,
SyntaxBase? sourceSyntax)
{
this.schemaContext = schemaContext;
this.functionsByFullyQualifiedName = functionsByFullyQualifiedName;
this.variablesEvaluator = variablesEvaluator;
this.armIdentifierToSymbolNameMapping = armIdentifierToSymbolNameMapping;
this.sourceSyntax = sourceSyntax;
}
internal ArmDeclarationToExpressionConverter WithSourceSyntax(SyntaxBase? sourceSyntax) => new(schemaContext,
functionsByFullyQualifiedName,
variablesEvaluator,
armIdentifierToSymbolNameMapping,
sourceSyntax);
internal DeclaredTypeExpression CreateDeclaredTypeExpressionFor(string typePointer)
=> CreateDeclaredTypeExpressionFor(armIdentifierToSymbolNameMapping[new(ArmSymbolType.Type, typePointer)], ArmTemplateHelpers.DereferenceArmType(schemaContext, typePointer));
internal DeclaredVariableExpression CreateDeclaredVariableExpressionFor(string originalName)
=> new(sourceSyntax,
armIdentifierToSymbolNameMapping[new(ArmSymbolType.Variable, originalName)],
ConvertToVariableValue(originalName),
// Variables cannot have descriptions in an ARM template -- this is only supported in Bicep
Description: null,
// An imported variable is never automatically re-exported
Exported: null);
internal DeclaredFunctionExpression CreateDeclaredFunctionExpressionFor(string fullyQualifiedFunctionName)
{
var convertedSymbolName = armIdentifierToSymbolNameMapping[new(ArmSymbolType.Function, fullyQualifiedFunctionName)];
var (namespaceName, functionName) = convertedSymbolName.IndexOf('.') switch
{
int delimiterIndex when delimiterIndex > -1 => (convertedSymbolName[..delimiterIndex], convertedSymbolName[(delimiterIndex + 1)..]),
_ => (EmitConstants.UserDefinedFunctionsNamespace, convertedSymbolName),
};
if (!functionsByFullyQualifiedName.TryGetValue(fullyQualifiedFunctionName, out var function))
{
throw new InvalidOperationException($"Function {fullyQualifiedFunctionName} was not found in template.");
}
return new(sourceSyntax,
namespaceName,
functionName,
CreateLambdaExpressionFor(function),
Description: function.Metadata?.Value is JObject @object &&
@object.TryGetValue(LanguageConstants.MetadataDescriptionPropertyName, StringComparison.OrdinalIgnoreCase, out var descriptionToken) &&
descriptionToken is JValue { Value: string description }
? ExpressionFactory.CreateStringLiteral(description, sourceSyntax)
: null,
// An imported function is never automatically re-exported
Exported: null);
}
#region typeConversion
private DeclaredTypeExpression CreateDeclaredTypeExpressionFor(string convertedSymbolName, ITemplateSchemaNode schemaNode)
{
var modifiers = GetTypeModifiers(schemaNode);
return new(sourceSyntax,
convertedSymbolName,
ConvertToTypeExpression(schemaNode),
modifiers.Description,
modifiers.Metadata,
modifiers.Secure,
modifiers.MinLength,
modifiers.MaxLength,
modifiers.MinValue,
modifiers.MaxValue,
modifiers.Sealed,
// An imported type is never automatically re-exported
Exported: null);
}
private TypeExpression ConvertToTypeExpression(ITemplateSchemaNode schemaNode) => schemaNode.Nullable?.Value switch
{
true => new NullableTypeExpression(sourceSyntax, ConvertToTypeExpressionIgnoringNullability(schemaNode)),
false => new NonNullableTypeExpression(sourceSyntax, ConvertToTypeExpressionIgnoringNullability(schemaNode)),
_ => ConvertToTypeExpressionIgnoringNullability(schemaNode),
};
private record TypeModifiers(Expression? Description,
Expression? Metadata,
Expression? Secure,
Expression? MinLength,
Expression? MaxLength,
Expression? MinValue,
Expression? MaxValue,
Expression? Sealed);
private TypeModifiers GetTypeModifiers(ITemplateSchemaNode schemaNode) => new(
GetDescription(schemaNode) is string description ? ExpressionFactory.CreateStringLiteral(description, sourceSyntax) : null,
schemaNode.Metadata?.Value is JToken md && ConvertToExpression(ImmutableDictionary<JToken, LanguageExpression>.Empty, md) is ObjectExpression @object
? ExcludingPropertiesNamed(@object, LanguageConstants.MetadataDescriptionPropertyName, LanguageConstants.MetadataExportedPropertyName)
: null,
schemaNode.Type?.Value switch
{
TemplateParameterType.SecureString or TemplateParameterType.SecureObject => ExpressionFactory.CreateBooleanLiteral(true, sourceSyntax),
_ => null,
},
schemaNode.MinLength?.Value is long minLength
? ExpressionFactory.CreateIntegerLiteral(minLength, sourceSyntax)
: null,
schemaNode.MaxLength?.Value is long maxLength
? ExpressionFactory.CreateIntegerLiteral(maxLength, sourceSyntax)
: null,
schemaNode.MinValue?.Value is long minValue
? ExpressionFactory.CreateIntegerLiteral(minValue, sourceSyntax)
: null,
schemaNode.MaxValue?.Value is long maxValue
? ExpressionFactory.CreateIntegerLiteral(maxValue, sourceSyntax)
: null,
schemaNode.AdditionalProperties?.BooleanValue is false || schemaNode.Items?.BooleanValue is false
? ExpressionFactory.CreateBooleanLiteral(true, sourceSyntax)
: null);
private TypeExpression ConvertToTypeExpressionIgnoringNullability(ITemplateSchemaNode schemaNode)
{
// drop constraints that would have already been processed: Nullable, Min/MaxValue, Min/MaxLength, Pattern
var bicepType = ArmTemplateTypeLoader.ToTypeReference(schemaContext, new TemplateTypeDefinition
{
AdditionalProperties = schemaNode.AdditionalProperties,
AllowedValues = schemaNode.AllowedValues,
Discriminator = schemaNode.Discriminator,
Items = schemaNode.Items,
PrefixItems = schemaNode.PrefixItems,
Properties = schemaNode.Properties,
Ref = schemaNode.Ref,
Required = schemaNode.Required,
Sealed = schemaNode.Sealed,
Type = schemaNode.Type,
}).Type;
if (schemaNode.AllowedValues?.Value is { } allowedValues)
{
// "allowedValues" in ARM has two meanings:
// 1. { "type": "array", "allowedValues": ["foo", "bar"] } means that the node permits an array containing any subset of the allowed values
// 2. { "type": <type>, "allowedValues": [<legal values for <type>>] } means that the node permits any single one of the allowed values
// in either case, the contents of allowedValues will be the members of a literal type union, and each item must therefore be a valid type expression
var memberTypes = allowedValues.Select(ConvertAllowedValueToTypeExpression).ToImmutableArray();
// If we've hit the former case, the Bicep type symbol for the node will be an ArrayType whose item type is a union (e.g., ('foo' | 'bar')[])
if (bicepType is ArrayType bicepArrayType)
{
var itemTypeExpression = GetAllowedValuesTypeExpression(memberTypes, bicepArrayType.Item.Type);
return new ArrayTypeExpression(sourceSyntax,
new TypedArrayType(itemTypeExpression.ExpressedType, TypeSymbolValidationFlags.Default),
itemTypeExpression);
}
// If we've hit the latter case, the Bicep type symbol for the node will be a UnionType
return GetAllowedValuesTypeExpression(memberTypes, bicepType);
}
if (schemaNode.Ref?.Value is string @ref)
{
return new SynthesizedTypeAliasReferenceExpression(sourceSyntax, armIdentifierToSymbolNameMapping[new(ArmSymbolType.Type, @ref)], bicepType);
}
return schemaNode.Type.Value switch
{
TemplateParameterType.String or
TemplateParameterType.SecureString => new AmbientTypeReferenceExpression(sourceSyntax, LanguageConstants.TypeNameString, bicepType),
TemplateParameterType.Int => new AmbientTypeReferenceExpression(sourceSyntax, LanguageConstants.TypeNameInt, bicepType),
TemplateParameterType.Bool => new AmbientTypeReferenceExpression(sourceSyntax, LanguageConstants.TypeNameBool, bicepType),
TemplateParameterType.Array => ConvertArrayNodeToTypeExpression(schemaNode),
TemplateParameterType.Object or
TemplateParameterType.SecureObject => ConvertObjectNodeToTypeExpression(schemaNode),
_ => throw new InvalidOperationException($"Unrecognized ARM template type: {schemaNode.Type.Value}"),
};
}
private TypeExpression GetAllowedValuesTypeExpression(ImmutableArray<TypeExpression> memberTypes, TypeSymbol bicepType)
{
if (memberTypes.Length == 1)
{
return memberTypes.Single();
}
if (bicepType is not UnionType bicepUnionType)
{
throw new InvalidOperationException("This should have been handled by ArmTemplateTypeLoader");
}
return new UnionTypeExpression(sourceSyntax, bicepUnionType, memberTypes);
}
private static string? GetDescription(ITemplateSchemaNode schemaNode)
=> GetMetadataProperty(schemaNode, LanguageConstants.MetadataDescriptionPropertyName) is JValue { Value: string description }
? description
: null;
private static JToken? GetMetadataProperty(ITemplateSchemaNode schemaNode, string propertyName)
=> (schemaNode.Metadata?.Value as JObject)?.TryGetValue(propertyName, StringComparison.InvariantCultureIgnoreCase, out var property) == true
? property
: null;
private TypeExpression ConvertAllowedValueToTypeExpression(JToken token) => token switch
{
JObject @object => ConvertAllowedValueToTypeExpression(@object),
JArray @array => ConvertAllowedValueToTypeExpression(@array),
JValue jValue => jValue.Value switch
{
string @string => new StringLiteralTypeExpression(sourceSyntax, TypeFactory.CreateStringLiteralType(@string)),
long @long => new IntegerLiteralTypeExpression(sourceSyntax, TypeFactory.CreateIntegerLiteralType(@long)),
bool @bool => new BooleanLiteralTypeExpression(sourceSyntax, TypeFactory.CreateBooleanLiteralType(@bool)),
null => new NullLiteralTypeExpression(sourceSyntax, new NullType()),
_ => throw new InvalidOperationException($"Unrecognized JValue value of type {jValue.Value?.GetType().Name}"),
},
_ => throw new InvalidOperationException($"Unrecognized JToken of type {token.GetType().Name}")
};
private ObjectTypeExpression ConvertAllowedValueToTypeExpression(JObject @object)
{
var propertyExpressions = @object.Properties()
.Select(p => new ObjectTypePropertyExpression(sourceSyntax, p.Name, ConvertAllowedValueToTypeExpression(p.Value)))
.ToImmutableArray();
return new(sourceSyntax,
new ObjectType(string.Empty,
TypeSymbolValidationFlags.Default,
propertyExpressions.Select(p => new TypeProperty(p.PropertyName, p.Value.ExpressedType)),
additionalPropertiesType: null),
propertyExpressions,
AdditionalPropertiesExpression: null);
}
private TupleTypeExpression ConvertAllowedValueToTypeExpression(JArray @array)
{
var itemExpressions = @array.Select(childToken => new TupleTypeItemExpression(sourceSyntax, ConvertAllowedValueToTypeExpression(childToken)))
.ToImmutableArray();
return new(sourceSyntax,
new(itemExpressions.Select(i => i.Value.ExpressedType).ToImmutableArray<ITypeReference>(), TypeSymbolValidationFlags.Default),
itemExpressions);
}
private TypeExpression ConvertArrayNodeToTypeExpression(ITemplateSchemaNode schemaNode)
{
if (schemaNode.PrefixItems is { } prefixItems)
{
var itemExpressions = ImmutableArray.CreateRange(prefixItems.Select(i =>
{
var modifiers = GetTypeModifiers(i);
return new TupleTypeItemExpression(sourceSyntax,
ConvertToTypeExpression(i),
modifiers.Description,
modifiers.Metadata,
modifiers.Secure,
modifiers.MinLength,
modifiers.MaxLength,
modifiers.MinValue,
modifiers.MaxValue,
modifiers.Sealed);
}));
return new TupleTypeExpression(sourceSyntax,
new(ImmutableArray.CreateRange<ITypeReference>(itemExpressions.Select(i => i.Value.ExpressedType)),
TypeSymbolValidationFlags.Default),
itemExpressions);
}
if (schemaNode.Items?.SchemaNode is { } itemsSchemaNode)
{
var itemTypeExpression = ConvertToTypeExpression(itemsSchemaNode);
return new ArrayTypeExpression(sourceSyntax,
new TypedArrayType(itemTypeExpression.ExpressedType, TypeSymbolValidationFlags.Default),
itemTypeExpression);
}
return new AmbientTypeReferenceExpression(sourceSyntax, LanguageConstants.ArrayType, LanguageConstants.Array);
}
private TypeExpression ConvertObjectNodeToTypeExpression(ITemplateSchemaNode schemaNode)
{
if (schemaNode.Properties is null &&
schemaNode.AdditionalProperties is null &&
schemaNode.Sealed is null &&
schemaNode.Discriminator is null)
{
return new AmbientTypeReferenceExpression(sourceSyntax, LanguageConstants.ObjectType, LanguageConstants.Object);
}
var properties = ImmutableArray.CreateRange(schemaNode.Properties.CoalesceEnumerable()
.Select(kvp =>
{
var modifiers = GetTypeModifiers(kvp.Value);
return new ObjectTypePropertyExpression(sourceSyntax,
kvp.Key,
ConvertToTypeExpression(kvp.Value),
modifiers.Description,
modifiers.Metadata,
modifiers.Secure,
modifiers.MinLength,
modifiers.MaxLength,
modifiers.MinValue,
modifiers.MaxValue,
modifiers.Sealed);
}));
ObjectTypeAdditionalPropertiesExpression? addlProperties = null;
if (schemaNode.AdditionalProperties?.SchemaNode is { } additionalPropertiesSchema)
{
var modifiers = GetTypeModifiers(additionalPropertiesSchema);
addlProperties = new(sourceSyntax,
ConvertToTypeExpression(additionalPropertiesSchema),
modifiers.Description,
modifiers.Metadata,
modifiers.Secure,
modifiers.MinLength,
modifiers.MaxLength,
modifiers.MinValue,
modifiers.MaxValue,
modifiers.Sealed);
}
return new ObjectTypeExpression(sourceSyntax,
new(string.Empty,
TypeSymbolValidationFlags.Default,
properties.Select(pe => new TypeProperty(pe.PropertyName, pe.Value.ExpressedType)),
addlProperties?.Value.ExpressedType),
properties,
addlProperties);
}
private ObjectExpression? ExcludingPropertiesNamed(ObjectExpression @object, params string[] keysToExclude)
{
var toExclude = keysToExclude.ToImmutableHashSet(StringComparer.OrdinalIgnoreCase);
return @object.Properties.Where(p => p.TryGetKeyText() is not string key || !toExclude.Contains(key)).ToImmutableArray() switch
{
var props when props.Length == 0 => null,
var props when props.Length == @object.Properties.Length => @object,
var props => new(@object.SourceSyntax, props),
};
}
#endregion typeConversion
#region variableConversion
private Expression ConvertToVariableValue(string originalName)
{
if (variablesEvaluator.TryGetUnevaluatedDeclaringToken(originalName) is JToken singularDeclaration)
{
return ConvertToExpression(ExpressionsEngine.ParseLanguageExpressionsRecursive(singularDeclaration), singularDeclaration);
}
if (variablesEvaluator.TryGetUnevaluatedCopyDeclaration(originalName) is not { } copyDeclaration)
{
throw new InvalidOperationException($"Variable {originalName} was not found in template.");
}
this.activeCopyLoopName = originalName;
var expression = new ForLoopExpression(sourceSyntax,
new FunctionCallExpression(sourceSyntax, "range", ImmutableArray.Create(ExpressionFactory.CreateIntegerLiteral(0, sourceSyntax),
ConvertToExpression(ExpressionsEngine.ParseLanguageExpressionsRecursive(copyDeclaration.CountToken), copyDeclaration.CountToken))),
ConvertToExpression(ExpressionsEngine.ParseLanguageExpressionsRecursive(copyDeclaration.ValueItemToken), copyDeclaration.ValueItemToken),
null,
null);
this.activeCopyLoopName = null;
return expression;
}
private Expression ConvertToExpression(IReadOnlyDictionary<JToken, LanguageExpression> parsedExpressions, JToken toConvert)
{
ObjectPropertyExpression convertObjectProperty(JProperty property)
{
// The ExpressionsEngine.ParseLanguageExpressionsRecursive method represent key name lookups
// by storing the JProperty, rather than the key string.
var key = parsedExpressions.TryGetValue(property, out var keyExpression) ?
ConvertToExpression(keyExpression) :
ConvertToExpression(parsedExpressions, property.Name);
return new(
sourceSyntax,
key,
ConvertToExpression(parsedExpressions, property.Value));
}
if (parsedExpressions.TryGetValue(toConvert, out var armExpression))
{
return ConvertToExpression(armExpression);
}
return toConvert switch
{
JObject objectToCovert => ExpressionFactory.CreateObject(
objectToCovert.Properties().Select(convertObjectProperty),
sourceSyntax),
JArray arrayToConvert => ExpressionFactory.CreateArray(
arrayToConvert.Select(item => ConvertToExpression(parsedExpressions, item)),
sourceSyntax),
_ => toConvert.Type switch
{
JTokenType.Integer => ExpressionFactory.CreateIntegerLiteral(toConvert.ToObject<long>(), sourceSyntax),
// there's no Bicep expression that corresponds to .Float, so use a `json('<float>')` function expression
JTokenType.Float => new FunctionCallExpression(sourceSyntax,
"json",
ImmutableArray.Create<Expression>(ExpressionFactory.CreateStringLiteral(toConvert.ToString()))),
JTokenType.Boolean => ExpressionFactory.CreateBooleanLiteral(toConvert.ToObject<bool>(), sourceSyntax),
JTokenType.Null => new NullLiteralExpression(sourceSyntax),
// everything else (.String, .Date, .Uri, etc.) is some specialization of string
_ => ExpressionFactory.CreateStringLiteral(toConvert.ToString(), sourceSyntax),
},
};
}
private Expression ConvertToExpression(LanguageExpression armExpression) => armExpression switch
{
JTokenExpression jTokenExpression => ConvertToExpression(ImmutableDictionary<JToken, LanguageExpression>.Empty, jTokenExpression.Value),
FunctionExpression functionExpression => ConvertToExpression(functionExpression),
_ => throw new InvalidOperationException($"Encountered an unrecognized LanguageExpression of type {armExpression.GetType().Name}"),
};
private Expression ConvertToExpression(FunctionExpression func)
{
if (func.Properties?.LastOrDefault() is LanguageExpression outermostPropertyAccess)
{
var baseExpression = ConvertToExpression(new FunctionExpression(func.Function,
func.Parameters,
func.Properties.Take(func.Properties.Length - 1).ToArray()));
return ConvertToExpression(outermostPropertyAccess) switch
{
StringLiteralExpression stringLiteralPropertyName when Lexer.IsValidIdentifier(stringLiteralPropertyName.Value) => new PropertyAccessExpression(sourceSyntax, baseExpression, stringLiteralPropertyName.Value, AccessExpressionFlags.None),
Expression otherwise => new ArrayAccessExpression(sourceSyntax, baseExpression, otherwise, AccessExpressionFlags.None),
};
}
if (armIdentifierToSymbolNameMapping.TryGetValue(new(ArmSymbolType.Function, func.Function), out var userDefinedFunctionName))
{
var (namespaceName, functionName) = userDefinedFunctionName.IndexOf('.') switch
{
int delimiterIndex when delimiterIndex > -1 => (userDefinedFunctionName[..delimiterIndex], userDefinedFunctionName[(delimiterIndex + 1)..]),
_ => (EmitConstants.UserDefinedFunctionsNamespace, userDefinedFunctionName),
};
return new SynthesizedUserDefinedFunctionCallExpression(sourceSyntax,
namespaceName,
functionName,
func.Parameters.Select(ConvertToExpression).ToImmutableArray());
}
return func.Function.ToLowerInvariant() switch
{
VariablesFunctionName => ConvertToExpression(func.Parameters.Single()) switch
{
StringLiteralExpression constantVariableName => new SynthesizedVariableReferenceExpression(sourceSyntax,
armIdentifierToSymbolNameMapping[new(ArmSymbolType.Variable, constantVariableName.Value)]),
// if the argument to variables() was itself a runtime-evaluated expression, just treat this as a function call
Expression otherwise => new FunctionCallExpression(sourceSyntax, VariablesFunctionName, ImmutableArray.Create(otherwise)),
},
CopyIndexFunctionName when variablesEvaluator.TryEvaluate(func.Parameters[0]) is JValue { Value: string copyIndexName } &&
StringComparer.OrdinalIgnoreCase.Equals(activeCopyLoopName, copyIndexName) => func.Parameters.Skip(1).FirstOrDefault() switch
{
LanguageExpression startIndexExpression => new BinaryExpression(sourceSyntax,
BinaryOperator.Add,
new CopyIndexExpression(sourceSyntax, armIdentifierToSymbolNameMapping[new(ArmSymbolType.Variable, activeCopyLoopName)]),
ConvertToExpression(startIndexExpression)),
_ => new CopyIndexExpression(sourceSyntax, armIdentifierToSymbolNameMapping[new(ArmSymbolType.Variable, activeCopyLoopName)]),
},
// this is less robust than decompilation analysis (e.g., the "add" function will not be transformed to a binary expression), but since this expression is produced only to be lightly manipulated and recompiled to ARM JSON, it's fine to be lax here
// this choice should be revisited if this converter is used outside of the Bicep.Core.Emit namespace
_ => new FunctionCallExpression(sourceSyntax, func.Function, func.Parameters.Select(ConvertToExpression).ToImmutableArray()),
};
}
#endregion variableConversion
#region functionConversion
private LambdaExpression CreateLambdaExpressionFor(TemplateFunction function)
{
var parameterNames = ImmutableArray.CreateBuilder<string>();
var parameterTypes = ImmutableArray.CreateBuilder<TypeExpression?>();
foreach (var functionParameter in function.Parameters.CoalesceEnumerable())
{
parameterNames.Add(functionParameter.Name.Value);
parameterTypes.Add(ConvertToTypeExpression(functionParameter));
}
return new(sourceSyntax,
parameterNames.ToImmutable(),
parameterTypes.ToImmutable(),
ConvertToExpression(ExpressionsEngine.ParseLanguageExpressionsRecursive(function.Output.Value.Value), function.Output.Value.Value),
ConvertToTypeExpression(function.Output));
}
#endregion functionConversion
}