-
-
Notifications
You must be signed in to change notification settings - Fork 124
/
IndentedTextWriter.cs
515 lines (452 loc) · 19.3 KB
/
IndentedTextWriter.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.ComponentModel;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Text;
#pragma warning disable IDE0290
namespace ComputeSharp.SourceGeneration.Helpers;
/// <summary>
/// A helper type to build sequences of values with pooled buffers.
/// </summary>
internal sealed class IndentedTextWriter : IDisposable
{
/// <summary>
/// The default indentation (4 spaces).
/// </summary>
private const string DefaultIndentation = " ";
/// <summary>
/// The default new line (<c>'\n'</c>).
/// </summary>
private const char DefaultNewLine = '\n';
/// <summary>
/// The <see cref="ImmutableArrayBuilder{T}"/> instance that text will be written to.
/// </summary>
private ImmutableArrayBuilder<char> builder;
/// <summary>
/// The current indentation level.
/// </summary>
private int currentIndentationLevel;
/// <summary>
/// The current indentation, as text.
/// </summary>
private string currentIndentation = "";
/// <summary>
/// The cached array of available indentations, as text.
/// </summary>
private string[] availableIndentations;
/// <summary>
/// Creates a new <see cref="IndentedTextWriter"/> object.
/// </summary>
public IndentedTextWriter()
{
this.builder = new ImmutableArrayBuilder<char>();
this.currentIndentationLevel = 0;
this.currentIndentation = "";
this.availableIndentations = new string[4];
this.availableIndentations[0] = "";
for (int i = 1, n = this.availableIndentations.Length; i < n; i++)
{
this.availableIndentations[i] = this.availableIndentations[i - 1] + DefaultIndentation;
}
}
/// <summary>
/// Advances the current writer and gets a <see cref="Span{T}"/> to the requested memory area.
/// </summary>
/// <param name="requestedSize">The requested size to advance by.</param>
/// <returns>A <see cref="Span{T}"/> to the requested memory area.</returns>
/// <remarks>
/// No other data should be written to the writer while the returned <see cref="Span{T}"/>
/// is in use, as it could invalidate the memory area wrapped by it, if resizing occurs.
/// </remarks>
public Span<char> Advance(int requestedSize)
{
// Add the leading whitespace if needed (same as WriteRawText below)
if (this.builder.Count == 0 || this.builder.WrittenSpan[^1] == DefaultNewLine)
{
this.builder.AddRange(this.currentIndentation.AsSpan());
}
return this.builder.Advance(requestedSize);
}
/// <summary>
/// Increases the current indentation level.
/// </summary>
public void IncreaseIndent()
{
this.currentIndentationLevel++;
if (this.currentIndentationLevel == this.availableIndentations.Length)
{
Array.Resize(ref this.availableIndentations, this.availableIndentations.Length * 2);
}
// Set both the current indentation and the current position in the indentations
// array to the expected indentation for the incremented level (ie. one level more).
this.currentIndentation = this.availableIndentations[this.currentIndentationLevel]
??= this.availableIndentations[this.currentIndentationLevel - 1] + DefaultIndentation;
}
/// <summary>
/// Decreases the current indentation level.
/// </summary>
public void DecreaseIndent()
{
this.currentIndentationLevel--;
this.currentIndentation = this.availableIndentations[this.currentIndentationLevel];
}
/// <summary>
/// Writes a block to the underlying buffer.
/// </summary>
/// <returns>A <see cref="Block"/> value to close the open block with.</returns>
public Block WriteBlock()
{
WriteLine("{");
IncreaseIndent();
return new(this);
}
/// <summary>
/// Writes content to the underlying buffer.
/// </summary>
/// <param name="content">The content to write.</param>
/// <param name="isMultiline">Whether the input content is multiline.</param>
public void Write(string content, bool isMultiline = false)
{
Write(content.AsSpan(), isMultiline);
}
/// <summary>
/// Writes content to the underlying buffer.
/// </summary>
/// <param name="content">The content to write.</param>
/// <param name="isMultiline">Whether the input content is multiline.</param>
public void Write(ReadOnlySpan<char> content, bool isMultiline = false)
{
if (isMultiline)
{
while (content.Length > 0)
{
int newLineIndex = content.IndexOf(DefaultNewLine);
if (newLineIndex < 0)
{
// There are no new lines left, so the content can be written as a single line
WriteRawText(content);
break;
}
else
{
ReadOnlySpan<char> line = content[..newLineIndex];
// Write the current line (if it's empty, we can skip writing the text entirely).
// This ensures that raw multiline string literals with blank lines don't have
// extra whitespace at the start of those lines, which would otherwise happen.
WriteIf(!line.IsEmpty, line);
WriteLine();
// Move past the new line character (the result could be an empty span)
content = content[(newLineIndex + 1)..];
}
}
}
else
{
WriteRawText(content);
}
}
/// <summary>
/// Writes content to the underlying buffer.
/// </summary>
/// <param name="handler">The interpolated string handler with content to write.</param>
public void Write([InterpolatedStringHandlerArgument("")] ref WriteInterpolatedStringHandler handler)
{
_ = this;
}
/// <summary>
/// Writes content to the underlying buffer depending on an input condition.
/// </summary>
/// <param name="condition">The condition to use to decide whether or not to write content.</param>
/// <param name="content">The content to write.</param>
/// <param name="isMultiline">Whether the input content is multiline.</param>
public void WriteIf(bool condition, string content, bool isMultiline = false)
{
if (condition)
{
Write(content.AsSpan(), isMultiline);
}
}
/// <summary>
/// Writes content to the underlying buffer depending on an input condition.
/// </summary>
/// <param name="condition">The condition to use to decide whether or not to write content.</param>
/// <param name="content">The content to write.</param>
/// <param name="isMultiline">Whether the input content is multiline.</param>
public void WriteIf(bool condition, ReadOnlySpan<char> content, bool isMultiline = false)
{
if (condition)
{
Write(content, isMultiline);
}
}
/// <summary>
/// Writes content to the underlying buffer depending on an input condition.
/// </summary>
/// <param name="condition">The condition to use to decide whether or not to write content.</param>
/// <param name="handler">The interpolated string handler with content to write.</param>
public void WriteIf(bool condition, [InterpolatedStringHandlerArgument("", nameof(condition))] ref WriteIfInterpolatedStringHandler handler)
{
_ = this;
}
/// <summary>
/// Writes a line to the underlying buffer.
/// </summary>
/// <param name="skipIfPresent">Indicates whether to skip adding the line if there already is one.</param>
public void WriteLine(bool skipIfPresent = false)
{
if (skipIfPresent && this.builder.WrittenSpan is [.., '\n', '\n'])
{
return;
}
this.builder.Add(DefaultNewLine);
}
/// <summary>
/// Writes content to the underlying buffer and appends a trailing new line.
/// </summary>
/// <param name="content">The content to write.</param>
/// <param name="isMultiline">Whether the input content is multiline.</param>
public void WriteLine(string content, bool isMultiline = false)
{
WriteLine(content.AsSpan(), isMultiline);
}
/// <summary>
/// Writes content to the underlying buffer and appends a trailing new line.
/// </summary>
/// <param name="content">The content to write.</param>
/// <param name="isMultiline">Whether the input content is multiline.</param>
public void WriteLine(ReadOnlySpan<char> content, bool isMultiline = false)
{
Write(content, isMultiline);
WriteLine();
}
/// <summary>
/// Writes content to the underlying buffer and appends a trailing new line.
/// </summary>
/// <param name="handler">The interpolated string handler with content to write.</param>
public void WriteLine([InterpolatedStringHandlerArgument("")] ref WriteInterpolatedStringHandler handler)
{
WriteLine();
}
/// <summary>
/// Writes a line to the underlying buffer depending on an input condition.
/// </summary>
/// <param name="condition">The condition to use to decide whether or not to write content.</param>
/// <param name="skipIfPresent">Indicates whether to skip adding the line if there already is one.</param>
public void WriteLineIf(bool condition, bool skipIfPresent = false)
{
if (condition)
{
WriteLine(skipIfPresent);
}
}
/// <summary>
/// Writes content to the underlying buffer and appends a trailing new line depending on an input condition.
/// </summary>
/// <param name="condition">The condition to use to decide whether or not to write content.</param>
/// <param name="content">The content to write.</param>
/// <param name="isMultiline">Whether the input content is multiline.</param>
public void WriteLineIf(bool condition, string content, bool isMultiline = false)
{
if (condition)
{
WriteLine(content.AsSpan(), isMultiline);
}
}
/// <summary>
/// Writes content to the underlying buffer and appends a trailing new line depending on an input condition.
/// </summary>
/// <param name="condition">The condition to use to decide whether or not to write content.</param>
/// <param name="content">The content to write.</param>
/// <param name="isMultiline">Whether the input content is multiline.</param>
public void WriteLineIf(bool condition, ReadOnlySpan<char> content, bool isMultiline = false)
{
if (condition)
{
Write(content, isMultiline);
WriteLine();
}
}
/// <summary>
/// Writes content to the underlying buffer and appends a trailing new line depending on an input condition.
/// </summary>
/// <param name="condition">The condition to use to decide whether or not to write content.</param>
/// <param name="handler">The interpolated string handler with content to write.</param>
public void WriteLineIf(bool condition, [InterpolatedStringHandlerArgument("", nameof(condition))] ref WriteIfInterpolatedStringHandler handler)
{
if (condition)
{
WriteLine();
}
}
/// <inheritdoc/>
public override string ToString()
{
return this.builder.WrittenSpan.Trim().ToString();
}
/// <inheritdoc/>
public void Dispose()
{
this.builder.Dispose();
}
/// <summary>
/// Writes raw text to the underlying buffer, adding leading indentation if needed.
/// </summary>
/// <param name="content">The raw text to write.</param>
private void WriteRawText(ReadOnlySpan<char> content)
{
if (this.builder.Count == 0 || this.builder.WrittenSpan[^1] == DefaultNewLine)
{
this.builder.AddRange(this.currentIndentation.AsSpan());
}
this.builder.AddRange(content);
}
/// <summary>
/// A delegate representing a callback to write data into an <see cref="IndentedTextWriter"/> instance.
/// </summary>
/// <typeparam name="T">The type of data to use.</typeparam>
/// <param name="value">The input data to use to write into <paramref name="writer"/>.</param>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
public delegate void Callback<T>(T value, IndentedTextWriter writer);
/// <summary>
/// Represents an indented block that needs to be closed.
/// </summary>
/// <param name="writer">The input <see cref="IndentedTextWriter"/> instance to wrap.</param>
public struct Block(IndentedTextWriter writer) : IDisposable
{
/// <summary>
/// The <see cref="IndentedTextWriter"/> instance to write to.
/// </summary>
private IndentedTextWriter? writer = writer;
/// <inheritdoc/>
public void Dispose()
{
IndentedTextWriter? writer = this.writer;
this.writer = null;
if (writer is not null)
{
writer.DecreaseIndent();
writer.WriteLine("}");
}
}
}
/// <summary>
/// Provides a handler used by the language compiler to append interpolated strings into <see cref="IndentedTextWriter"/> instances.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
[InterpolatedStringHandler]
public readonly ref struct WriteInterpolatedStringHandler
{
/// <summary>The associated <see cref="IndentedTextWriter"/> to which to append.</summary>
private readonly IndentedTextWriter writer;
/// <summary>Creates a handler used to append an interpolated string into a <see cref="StringBuilder"/>.</summary>
/// <param name="literalLength">The number of constant characters outside of interpolation expressions in the interpolated string.</param>
/// <param name="formattedCount">The number of interpolation expressions in the interpolated string.</param>
/// <param name="writer">The associated <see cref="IndentedTextWriter"/> to which to append.</param>
/// <remarks>This is intended to be called only by compiler-generated code. Arguments are not validated as they'd otherwise be for members intended to be used directly.</remarks>
public WriteInterpolatedStringHandler(int literalLength, int formattedCount, IndentedTextWriter writer)
{
this.writer = writer;
}
/// <summary>Writes the specified string to the handler.</summary>
/// <param name="value">The string to write.</param>
public void AppendLiteral(string value)
{
this.writer.Write(value);
}
/// <summary>Writes the specified value to the handler.</summary>
/// <param name="value">The value to write.</param>
public void AppendFormatted(string? value)
{
AppendFormatted<string?>(value);
}
/// <summary>Writes the specified character span to the handler.</summary>
/// <param name="value">The span to write.</param>
public void AppendFormatted(ReadOnlySpan<char> value)
{
this.writer.Write(value);
}
/// <summary>Writes the specified value to the handler.</summary>
/// <param name="value">The value to write.</param>
/// <typeparam name="T">The type of the value to write.</typeparam>
public void AppendFormatted<T>(T value)
{
if (value is not null)
{
this.writer.Write(value.ToString());
}
}
/// <summary>Writes the specified value to the handler.</summary>
/// <param name="value">The value to write.</param>
/// <param name="format">The format string.</param>
/// <typeparam name="T">The type of the value to write.</typeparam>
public void AppendFormatted<T>(T value, string? format)
{
if (value is IFormattable)
{
this.writer.Write(((IFormattable)value).ToString(format, CultureInfo.InvariantCulture));
}
else if (value is not null)
{
this.writer.Write(value.ToString());
}
}
}
/// <summary>
/// Provides a handler used by the language compiler to conditionally append interpolated strings into <see cref="IndentedTextWriter"/> instances.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
[InterpolatedStringHandler]
public readonly ref struct WriteIfInterpolatedStringHandler
{
/// <summary>The associated <see cref="WriteInterpolatedStringHandler"/> to use.</summary>
private readonly WriteInterpolatedStringHandler handler;
/// <summary>Creates a handler used to append an interpolated string into a <see cref="StringBuilder"/>.</summary>
/// <param name="literalLength">The number of constant characters outside of interpolation expressions in the interpolated string.</param>
/// <param name="formattedCount">The number of interpolation expressions in the interpolated string.</param>
/// <param name="writer">The associated <see cref="IndentedTextWriter"/> to which to append.</param>
/// <param name="condition">The condition to use to decide whether or not to write content.</param>
/// <param name="shouldAppend">A value indicating whether formatting should proceed.</param>
/// <remarks>This is intended to be called only by compiler-generated code. Arguments are not validated as they'd otherwise be for members intended to be used directly.</remarks>
public WriteIfInterpolatedStringHandler(int literalLength, int formattedCount, IndentedTextWriter writer, bool condition, out bool shouldAppend)
{
if (condition)
{
this.handler = new WriteInterpolatedStringHandler(literalLength, formattedCount, writer);
shouldAppend = true;
}
else
{
this.handler = default;
shouldAppend = false;
}
}
/// <inheritdoc cref="WriteInterpolatedStringHandler.AppendLiteral(string)"/>
public void AppendLiteral(string value)
{
this.handler.AppendLiteral(value);
}
/// <inheritdoc cref="WriteInterpolatedStringHandler.AppendFormatted(string?)"/>
public void AppendFormatted(string? value)
{
this.handler.AppendFormatted(value);
}
/// <inheritdoc cref="WriteInterpolatedStringHandler.AppendFormatted(ReadOnlySpan{char})"/>
public void AppendFormatted(ReadOnlySpan<char> value)
{
this.handler.AppendFormatted(value);
}
/// <inheritdoc cref="WriteInterpolatedStringHandler.AppendFormatted{T}(T)"/>
public void AppendFormatted<T>(T value)
{
this.handler.AppendFormatted(value);
}
/// <inheritdoc cref="WriteInterpolatedStringHandler.AppendFormatted{T}(T, string?)"/>
public void AppendFormatted<T>(T value, string? format)
{
this.handler.AppendFormatted(value, format);
}
}
}