forked from microsoft/aspire
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReferenceExpression.cs
More file actions
419 lines (370 loc) · 19.4 KB
/
Copy pathReferenceExpression.cs
File metadata and controls
419 lines (370 loc) · 19.4 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
// 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.Runtime.CompilerServices;
using System.Text;
using Aspire.Hosting.Utils;
namespace Aspire.Hosting.ApplicationModel;
/// <summary>
/// Represents an expression that might be made up of multiple resource properties. For example,
/// a connection string might be made up of a host, port, and password from different endpoints.
/// </summary>
public class ReferenceExpression : IManifestExpressionProvider, IValueProvider, IValueWithReferences
{
/// <summary>
/// Represents an empty reference expression with no name, value providers, or arguments.
/// </summary>
/// <remarks>Use this field to represent a default or uninitialized reference expression. The instance has
/// an empty name and contains no value providers or arguments.</remarks>
public static readonly ReferenceExpression Empty = Create(string.Empty, [], [], []);
private readonly string[] _manifestExpressions;
private readonly string?[] _stringFormats;
private ReferenceExpression(string format, IValueProvider[] valueProviders, string[] manifestExpressions, string?[] stringFormats)
{
ArgumentNullException.ThrowIfNull(format);
ArgumentNullException.ThrowIfNull(valueProviders);
ArgumentNullException.ThrowIfNull(manifestExpressions);
Format = format;
ValueProviders = valueProviders;
_manifestExpressions = manifestExpressions;
_stringFormats = stringFormats;
}
/// <summary>
/// The format string for this expression.
/// </summary>
public string Format { get; }
/// <summary>
/// The manifest expressions for the parameters for the format string.
/// </summary>
public IReadOnlyList<string> ManifestExpressions => _manifestExpressions;
/// <summary>
/// The string formats of the parameters, e.g. "uri".
/// </summary>
public IReadOnlyList<string?> StringFormats => _stringFormats;
/// <summary>
/// The list of <see cref="IValueProvider"/> that will be used to resolve parameters for the format string.
/// </summary>
public IReadOnlyList<IValueProvider> ValueProviders { get; }
IEnumerable<object> IValueWithReferences.References => ValueProviders;
/// <summary>
/// The value expression for the format string.
/// </summary>
public string ValueExpression =>
string.Format(CultureInfo.InvariantCulture, Format, _manifestExpressions);
/// <summary>
/// Gets the value of the expression. The final string value after evaluating the format string and its parameters.
/// </summary>
/// <param name="context">A context for resolving the value.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/>.</param>
public async ValueTask<string?> GetValueAsync(ValueProviderContext context, CancellationToken cancellationToken)
{
// NOTE: any logical changes to this method should also be made to ExpressionResolver.EvalExpressionAsync
if (Format.Length == 0)
{
return null;
}
var args = new object?[ValueProviders.Count];
for (var i = 0; i < ValueProviders.Count; i++)
{
args[i] = await ValueProviders[i].GetValueAsync(context, cancellationToken).ConfigureAwait(false);
// Apply string format if needed
var stringFormat = _stringFormats[i];
if (stringFormat is not null && args[i] is string s)
{
args[i] = FormattingHelpers.FormatValue(s, stringFormat);
}
}
return string.Format(CultureInfo.InvariantCulture, Format, args);
}
/// <summary>
/// Gets the value of the expression. The final string value after evaluating the format string and its parameters.
/// </summary>
/// <param name="cancellationToken">A <see cref="CancellationToken"/>.</param>
public ValueTask<string?> GetValueAsync(CancellationToken cancellationToken)
{
return this.GetValueAsync(new(), cancellationToken);
}
internal static ReferenceExpression Create(string format, IValueProvider[] valueProviders, string[] manifestExpressions, string?[] stringFormats)
{
return new(format, valueProviders, manifestExpressions, stringFormats);
}
/// <summary>
/// Creates a new instance of <see cref="ReferenceExpression"/> with the specified format and value providers.
/// </summary>
/// <param name="handler">The handler that contains the format and value providers.</param>
/// <returns>A new instance of <see cref="ReferenceExpression"/> with the specified format and value providers.</returns>
public static ReferenceExpression Create(in ExpressionInterpolatedStringHandler handler)
{
return handler.GetExpression();
}
/// <summary>
/// Represents a handler for interpolated strings that contain expressions. Those expressions will either be literal strings or
/// instances of types that implement both <see cref="IValueProvider"/> and <see cref="IManifestExpressionProvider"/>.
/// </summary>
/// <param name="literalLength">The length of the literal part of the interpolated string.</param>
/// <param name="formattedCount">The number of formatted parts in the interpolated string.</param>
[InterpolatedStringHandler]
public ref struct ExpressionInterpolatedStringHandler(int literalLength, int formattedCount)
{
private static readonly char[] s_braces = ['{', '}'];
private readonly StringBuilder _builder = new(literalLength * 2);
private readonly List<IValueProvider> _valueProviders = new(formattedCount);
private readonly List<string> _manifestExpressions = new(formattedCount);
private readonly List<string?> _stringFormats = new(formattedCount);
/// <summary>
/// Appends a literal value to the expression.
/// </summary>
/// <param name="value">The literal string value to be appended to the interpolated string.</param>
public readonly void AppendLiteral(string value)
{
// Only escape single braces, leave already escaped braces untouched
_builder.Append(EscapeUnescapedBraces(value));
}
/// <summary>
/// Appends a formatted value to the expression.
/// </summary>
/// <param name="value">The formatted string to be appended to the interpolated string.</param>
public readonly void AppendFormatted(string? value)
{
AppendFormatted(value, format: null);
}
/// <summary>
/// Appends a formatted value to the expression.
/// </summary>
/// <param name="value">The formatted string to be appended to the interpolated string.</param>
/// <param name="format">The format to be applied to the value. e.g., "uri"</param>
public readonly void AppendFormatted(string? value, string? format = null)
{
// The value that comes in is a literal string that is not meant to be interpreted.
// But the _builder later gets treated as a format string, so we just need to escape the braces.
if (value is not null)
{
if (format is not null)
{
value = FormattingHelpers.FormatValue(value, format);
}
_builder.Append(EscapeUnescapedBraces(value));
}
}
/// <summary>
/// Appends a formatted value to the expression. The value must implement <see cref="IValueProvider"/> and <see cref="IManifestExpressionProvider"/>.
/// </summary>
/// <param name="valueProvider">An instance of an object which implements <see cref="IValueProvider"/> and <see cref="IManifestExpressionProvider"/>.</param>
/// <exception cref="InvalidOperationException"></exception>
public void AppendFormatted<T>(T valueProvider) where T : IValueProvider, IManifestExpressionProvider
{
AppendFormatted(valueProvider, format: null);
}
/// <summary>
/// Appends a formatted value to the expression. The value must implement <see cref="IValueProvider"/> and <see cref="IManifestExpressionProvider"/>.
/// </summary>
/// <param name="valueProvider">An instance of an object which implements <see cref="IValueProvider"/> and <see cref="IManifestExpressionProvider"/>.</param>
/// <param name="format">The format to be applied to the value. e.g., "uri"</param>
/// <exception cref="InvalidOperationException"></exception>
public void AppendFormatted<T>(T valueProvider, string? format = null) where T : IValueProvider, IManifestExpressionProvider
{
var index = _valueProviders.Count;
_builder.Append(CultureInfo.InvariantCulture, $"{{{index}}}");
_valueProviders.Add(valueProvider);
_manifestExpressions.Add(valueProvider.ValueExpression);
_stringFormats.Add(format);
}
/// <summary>
/// Appends a formatted value to the expression. The value must implement <see cref="IValueProvider"/> and <see cref="IManifestExpressionProvider"/>.
/// </summary>
/// <param name="valueProvider">An instance of an object which implements <see cref="IValueProvider"/> and <see cref="IManifestExpressionProvider"/>.</param>
/// <exception cref="InvalidOperationException"></exception>
public void AppendFormatted<T>(IResourceBuilder<T> valueProvider)
where T : IResource, IValueProvider, IManifestExpressionProvider
{
AppendFormatted(valueProvider, format: null);
}
/// <summary>
/// Appends a formatted value to the expression. The value must implement <see cref="IValueProvider"/> and <see cref="IManifestExpressionProvider"/>.
/// </summary>
/// <param name="valueProvider">An instance of an object which implements <see cref="IValueProvider"/> and <see cref="IManifestExpressionProvider"/>.</param>
/// <param name="format">The format to be applied to the value. e.g., "uri"</param>
/// <exception cref="InvalidOperationException"></exception>
public void AppendFormatted<T>(IResourceBuilder<T> valueProvider, string? format = null)
where T : IResource, IValueProvider, IManifestExpressionProvider
{
var index = _valueProviders.Count;
_builder.Append(CultureInfo.InvariantCulture, $"{{{index}}}");
_valueProviders.Add(valueProvider.Resource);
_manifestExpressions.Add(valueProvider.Resource.ValueExpression);
_stringFormats.Add(format);
}
internal readonly ReferenceExpression GetExpression() =>
new(_builder.ToString(), [.. _valueProviders], [.. _manifestExpressions], [.. _stringFormats]);
private static string EscapeUnescapedBraces(string input)
{
// Fast path: nothing to escape
if (input.IndexOfAny(s_braces) == -1)
{
return input;
}
// Allocate a bit of extra space in case we need to escape a few braces.
var sb = new StringBuilder(input.Length + 4);
for (var i = 0; i < input.Length; i++)
{
var c = input[i];
if (IsBrace(c))
{
if (IsNextCharSame(input, i))
{
// Already escaped, copy both and skip next
sb.Append(c).Append(c);
i++;
}
else
{
// Escape single brace
sb.Append(c).Append(c);
}
}
else
{
sb.Append(c);
}
}
return sb.ToString();
static bool IsBrace(char ch) => ch == '{' || ch == '}';
static bool IsNextCharSame(string s, int idx) =>
idx + 1 < s.Length && s[idx + 1] == s[idx];
}
}
}
/// <summary>
/// A builder for creating <see cref="ReferenceExpression"/> instances.
/// </summary>
public class ReferenceExpressionBuilder
{
private readonly StringBuilder _builder = new();
private readonly List<IValueProvider> _valueProviders = new();
private readonly List<string> _manifestExpressions = new();
private readonly List<string?> _stringFormats = new();
/// <summary>
/// Indicates whether the expression is empty.
/// </summary>
public bool IsEmpty => _builder.Length == 0;
/// <summary>
/// Appends an interpolated string to the expression.
/// </summary>
/// <param name="handler"></param>
public void Append([InterpolatedStringHandlerArgument("")] in ReferenceExpressionBuilderInterpolatedStringHandler handler)
{
}
/// <summary>
/// Appends a literal value to the expression.
/// </summary>
/// <param name="value">The literal string value to be appended to the interpolated string.</param>
public void AppendLiteral(string value)
{
_builder.Append(value);
}
/// <summary>
/// Appends a formatted value to the expression.
/// </summary>
/// <param name="value">The formatted string to be appended to the interpolated string.</param>
public void AppendFormatted(string? value)
{
_builder.Append(value);
}
/// <summary>
/// Appends a formatted value to the expression. The value must implement <see cref="IValueProvider"/> and <see cref="IManifestExpressionProvider"/>.
/// </summary>
/// <param name="valueProvider">An instance of an object which implements <see cref="IValueProvider"/> and <see cref="IManifestExpressionProvider"/>.</param>
/// <exception cref="InvalidOperationException"></exception>
public void AppendFormatted<T>(T valueProvider) where T : IValueProvider, IManifestExpressionProvider
{
AppendFormatted(valueProvider, format: null);
}
/// <summary>
/// Appends a formatted value to the expression. The value must implement <see cref="IValueProvider"/> and <see cref="IManifestExpressionProvider"/>.
/// </summary>
/// <param name="valueProvider">An instance of an object which implements <see cref="IValueProvider"/> and <see cref="IManifestExpressionProvider"/>.</param>
/// <param name="format">The format to be applied to the value. e.g., "uri"</param>
/// <exception cref="InvalidOperationException"></exception>
public void AppendFormatted<T>(T valueProvider, string? format) where T : IValueProvider, IManifestExpressionProvider
{
var index = _valueProviders.Count;
_builder.Append(CultureInfo.InvariantCulture, $"{{{index}}}");
_valueProviders.Add(valueProvider);
_manifestExpressions.Add(valueProvider.ValueExpression);
_stringFormats.Add(format);
}
/// <summary>
/// Builds the <see cref="ReferenceExpression"/>.
/// </summary>
public ReferenceExpression Build() =>
ReferenceExpression.Create(_builder.ToString(), [.. _valueProviders], [.. _manifestExpressions], [.. _stringFormats]);
/// <summary>
/// Represents a handler for interpolated strings that contain expressions. Those expressions will either be literal strings or
/// instances of types that implement both <see cref="IValueProvider"/> and <see cref="IManifestExpressionProvider"/>.
/// </summary>
/// <param name="literalLength">The length of the literal part of the interpolated string.</param>
/// <param name="formattedCount">The number of formatted parts in the interpolated string.</param>
/// <param name="builder">The builder that will be used to create the <see cref="ReferenceExpression"/>.</param>
[InterpolatedStringHandler]
#pragma warning disable CS9113 // Parameter is unread.
public ref struct ReferenceExpressionBuilderInterpolatedStringHandler(int literalLength, int formattedCount, ReferenceExpressionBuilder builder)
#pragma warning restore CS9113 // Parameter is unread.
{
/// <summary>
/// Appends a literal value to the expression.
/// </summary>
/// <param name="value">The literal string value to be appended to the interpolated string.</param>
public readonly void AppendLiteral(string value)
{
builder.AppendLiteral(value);
}
/// <summary>
/// Appends a formatted value to the expression.
/// </summary>
/// <param name="value">The formatted string to be appended to the interpolated string.</param>
public readonly void AppendFormatted(string? value)
{
builder.AppendFormatted(value);
}
/// <summary>
/// Appends a formatted value to the expression. The value must implement <see cref="IValueProvider"/> and <see cref="IManifestExpressionProvider"/>.
/// </summary>
/// <param name="valueProvider">An instance of an object which implements <see cref="IValueProvider"/> and <see cref="IManifestExpressionProvider"/>.</param>
/// <exception cref="InvalidOperationException"></exception>
public void AppendFormatted<T>(T valueProvider) where T : IValueProvider, IManifestExpressionProvider
{
AppendFormatted(valueProvider, format: null);
}
/// <summary>
/// Appends a formatted value to the expression. The value must implement <see cref="IValueProvider"/> and <see cref="IManifestExpressionProvider"/>.
/// </summary>
/// <param name="valueProvider">An instance of an object which implements <see cref="IValueProvider"/> and <see cref="IManifestExpressionProvider"/>.</param>
/// <param name="format">The format to be applied to the value. e.g., "uri"</param>
/// <exception cref="InvalidOperationException"></exception>
public void AppendFormatted<T>(T valueProvider, string? format) where T : IValueProvider, IManifestExpressionProvider
{
builder.AppendFormatted(valueProvider, format);
}
/// <summary>
/// Appends a formatted value to the expression. The value must implement <see cref="IValueProvider"/> and <see cref="IManifestExpressionProvider"/>.
/// </summary>
/// <param name="valueProvider">An instance of an object which implements <see cref="IValueProvider"/> and <see cref="IManifestExpressionProvider"/>.</param>
/// <exception cref="InvalidOperationException"></exception>
public void AppendFormatted<T>(IResourceBuilder<T> valueProvider)
where T : IResource, IValueProvider, IManifestExpressionProvider
{
AppendFormatted(valueProvider, format: null);
}
/// <summary>
/// Appends a formatted value to the expression. The value must implement <see cref="IValueProvider"/> and <see cref="IManifestExpressionProvider"/>.
/// </summary>
/// <param name="valueProvider">An instance of an object which implements <see cref="IValueProvider"/> and <see cref="IManifestExpressionProvider"/>.</param>
/// <param name="format">The format to be applied to the value. e.g., "uri"</param>
/// <exception cref="InvalidOperationException"></exception>
public void AppendFormatted<T>(IResourceBuilder<T> valueProvider, string? format)
where T : IResource, IValueProvider, IManifestExpressionProvider
{
builder.AppendFormatted(valueProvider.Resource, format);
}
}
}