-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGeneratorTestContextBuilder.cs
More file actions
781 lines (708 loc) · 30.8 KB
/
Copy pathGeneratorTestContextBuilder.cs
File metadata and controls
781 lines (708 loc) · 30.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
using System.Collections.Immutable;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Loader;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Text;
using Serilog;
using Serilog.Core;
namespace Rocket.Surgery.Extensions.Testing.SourceGenerators;
/// <summary>
/// An immutable builder for creating a <see cref="GeneratorTestContext" />
/// </summary>
public record GeneratorTestContextBuilder
{
/// <summary>
/// Create a new instance of the <see cref="GeneratorTestContextBuilder" /> with the default references
/// </summary>
/// <remarks>This method adds the default references to the compilation (things that are needed for most code to compile)</remarks>
/// <returns></returns>
public static GeneratorTestContextBuilder Create() => new GeneratorTestContextBuilder().WithDefaultReferences();
/// <summary>
/// Create a new instance of the <see cref="GeneratorTestContextBuilder" /> without the default references
/// </summary>
/// <returns></returns>
public static GeneratorTestContextBuilder CreateWithoutDefaultReferences() => new();
private ImmutableDictionary<string, ImmutableDictionary<string, string>> _options = [];
private ImmutableDictionary<string, string> _globalOptions = [];
private ILogger? _logger;
private string? _projectName;
private AssemblyLoadContext? _assemblyLoadContext;
private CSharpParseOptions _parseOptions = new();
private DiagnosticSeverity? _diagnosticSeverity = VerifyGeneratorTextContext.diagnosticSeverityFilter;
private ImmutableHashSet<MetadataReference>
_metadataReferences = ImmutableHashSet<MetadataReference>.Empty.WithComparer(ReferenceEqualityComparer.Instance);
private ImmutableHashSet<string> _referenceNames = ImmutableHashSet<string>.Empty.WithComparer(StringComparer.OrdinalIgnoreCase);
private ImmutableHashSet<Type> _relatedTypes = [];
private ImmutableArray<NamedSourceText> _sources = [];
private ImmutableArray<AdditionalText> _additionalTexts = [];
private ImmutableArray<GeneratorTestResultsCustomizer> _customizers = [];
private ImmutableHashSet<string> _ignoredFilePaths = [];
private ImmutableDictionary<string, MarkedLocation> _markedLocations = [];
private GeneratorTestContextBuilder() { }
/// <summary>
/// Attach a logger to the builder
/// </summary>
/// <param name="logger"></param>
/// <returns></returns>
public GeneratorTestContextBuilder WithLogger(ILogger logger) => this with { _logger = logger, };
/// <summary>
/// Configure the diagnostic severity to be returned
/// </summary>
/// <param name="diagnosticSeverity"></param>
/// <returns></returns>
public GeneratorTestContextBuilder WithDiagnosticSeverity(DiagnosticSeverity? diagnosticSeverity) => this with { _diagnosticSeverity = diagnosticSeverity, };
/// <summary>
/// Add a customizer to custom the data returned through verify
/// </summary>
/// <param name="customizer"></param>
/// <returns></returns>
public GeneratorTestContextBuilder WithCustomizer(GeneratorTestResultsCustomizer customizer) => this with { _customizers = _customizers.Add(customizer), };
/// <summary>
/// Set the project name for the compilation
/// </summary>
/// <param name="projectName"></param>
/// <returns></returns>
public GeneratorTestContextBuilder WithProjectName(string projectName) => this with { _projectName = projectName, };
/// <summary>
/// Set the assembly load context for the compilation
/// </summary>
/// <param name="assemblyLoadContext"></param>
/// <returns></returns>
public GeneratorTestContextBuilder WithAssemblyLoadContext(AssemblyLoadContext assemblyLoadContext) => this with { _assemblyLoadContext = assemblyLoadContext, };
/// <summary>
/// Set the C# language version for the compilation
/// </summary>
/// <param name="languageVersion"></param>
/// <returns></returns>
public GeneratorTestContextBuilder WithLanguageVersion(LanguageVersion languageVersion)
{
return this with
{
_parseOptions = new(languageVersion, _parseOptions.DocumentationMode, _parseOptions.Kind, _parseOptions.PreprocessorSymbolNames.ToArray()),
};
}
/// <summary>
/// Set the documentation mode for the compilation
/// </summary>
/// <param name="documentationMode"></param>
/// <returns></returns>
public GeneratorTestContextBuilder WithDocumentationMode(DocumentationMode documentationMode)
{
return this with
{
_parseOptions = new(_parseOptions.LanguageVersion, documentationMode, _parseOptions.Kind, _parseOptions.PreprocessorSymbolNames.ToArray()),
};
}
/// <summary>
/// Add a preprocessor symbol to the compilation
/// </summary>
/// <param name="preprocessorSymbolNames"></param>
/// <returns></returns>
[OverloadResolutionPriority(-1)]
public GeneratorTestContextBuilder AddPreprocessorSymbol(params string[] preprocessorSymbolNames)
{
return this with
{
_parseOptions = new(
_parseOptions.LanguageVersion,
_parseOptions.DocumentationMode,
_parseOptions.Kind,
_parseOptions.PreprocessorSymbolNames.Union(preprocessorSymbolNames).ToArray()
),
};
}
/// <summary>
/// Add a preprocessor symbol to the compilation
/// </summary>
/// <param name="preprocessorSymbolNames"></param>
/// <returns></returns>
[OverloadResolutionPriority(0)]
public GeneratorTestContextBuilder AddPreprocessorSymbol(params IEnumerable<string> preprocessorSymbolNames)
{
var preprocessorSymbolNameList = preprocessorSymbolNames.ToList();
return this with
{
_parseOptions = new(
_parseOptions.LanguageVersion,
_parseOptions.DocumentationMode,
_parseOptions.Kind,
_parseOptions.PreprocessorSymbolNames.Union(preprocessorSymbolNameList).ToArray()
),
};
}
/// <summary>
/// Add a preprocessor symbol to the compilation
/// </summary>
/// <param name="preprocessorSymbolNames"></param>
/// <returns></returns>
[OverloadResolutionPriority(1)]
public GeneratorTestContextBuilder AddPreprocessorSymbol(params IReadOnlyCollection<string> preprocessorSymbolNames)
{
return this with
{
_parseOptions = new(
_parseOptions.LanguageVersion,
_parseOptions.DocumentationMode,
_parseOptions.Kind,
_parseOptions.PreprocessorSymbolNames.Union(preprocessorSymbolNames).ToArray()
),
};
}
/// <summary>
/// What kind of source code is being compiled
/// </summary>
/// <param name="sourceCodeKind"></param>
/// <returns></returns>
public GeneratorTestContextBuilder WithSourceCodeKind(SourceCodeKind sourceCodeKind)
{
return this with
{
_parseOptions = new(
_parseOptions.LanguageVersion,
_parseOptions.DocumentationMode,
sourceCodeKind,
_parseOptions.PreprocessorSymbolNames.ToArray()
),
};
}
/// <summary>
/// Set features for the compilation
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <returns></returns>
public GeneratorTestContextBuilder WithFeature(string key, string? value = null)
{
return this with
{
_parseOptions = new CSharpParseOptions(
_parseOptions.LanguageVersion,
_parseOptions.DocumentationMode,
_parseOptions.Kind,
_parseOptions.PreprocessorSymbolNames.ToArray()
)
.WithFeatures(_parseOptions.Features.Concat(new KeyValuePair<string, string>[] { new(key, value ?? string.Empty), })),
};
}
/// <summary>
/// Ignore a given output file, if you don't want to see it's results.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public GeneratorTestContextBuilder IgnoreOutputFile(string path) => this with { _ignoredFilePaths = _ignoredFilePaths.Add(path), };
/// <summary>
/// Add a generator to the compilation
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public GeneratorTestContextBuilder WithGenerator(Type type) => this with { _relatedTypes = _relatedTypes.Add(type), };
/// <summary>
/// Add a generator to the compilation
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public GeneratorTestContextBuilder WithGenerator<T>()
where T : new() => WithGenerator(typeof(T));
/// <summary>
/// Add a analyzer to the compilation
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public GeneratorTestContextBuilder WithAnalyzer(Type type) => this with { _relatedTypes = _relatedTypes.Add(type), };
/// <summary>
/// Add a analyzer to the compilation
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public GeneratorTestContextBuilder WithAnalyzer<T>()
where T : DiagnosticAnalyzer, new() => WithAnalyzer(typeof(T));
/// <summary>
/// Add a codefix provider to the compilation
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public GeneratorTestContextBuilder WithCodeFix(Type type) => this with { _relatedTypes = _relatedTypes.Add(type), };
/// <summary>
/// Add a codefix provider to the compilation
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public GeneratorTestContextBuilder WithCodeFix<T>()
where T : CodeFixProvider, new() => WithCodeFix(typeof(T));
/// <summary>
/// Add a code refactoring provider to the compilation
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public GeneratorTestContextBuilder WithCodeRefactoring(Type type) => this with { _relatedTypes = _relatedTypes.Add(type), };
/// <summary>
/// Add a code refactoring provider to the compilation
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public GeneratorTestContextBuilder WithCodeRefactoring<T>()
where T : CodeRefactoringProvider, new() => WithCodeFix(typeof(T));
/// <summary>
/// Add an in memory compiled assembly to the compilation
/// </summary>
/// <param name="additionalCompilations"></param>
/// <returns></returns>
[OverloadResolutionPriority(-1)]
public GeneratorTestContextBuilder AddCompilationReferences(params GeneratorTestResults[] additionalCompilations)
{
return additionalCompilations.Any(z => z.MetadataReference is null)
? throw new ArgumentException("All additional compilations must have a metadata reference", nameof(additionalCompilations))
: ( AddReferencesInternal(additionalCompilations.Select(z => z.MetadataReference!).ToArray()) with
{
_referenceNames = _referenceNames.Union(additionalCompilations.Select(z => z.Assembly!.GetName().Name)),
} );
}
/// <summary>
/// Add an in memory compiled assembly to the compilation
/// </summary>
/// <param name="additionalCompilations"></param>
/// <returns></returns>
[OverloadResolutionPriority(0)]
public GeneratorTestContextBuilder AddCompilationReferences(params IEnumerable<GeneratorTestResults> additionalCompilations)
{
var generatorTestResultsEnumerable = additionalCompilations.ToList();
return generatorTestResultsEnumerable.Any(z => z.MetadataReference is null)
? throw new ArgumentException("All additional compilations must have a metadata reference", nameof(additionalCompilations))
: AddReferencesInternal(generatorTestResultsEnumerable.Select(z => z.MetadataReference!).ToArray()) with
{
_referenceNames = _referenceNames.Union(generatorTestResultsEnumerable.Select(z => z.Assembly!.GetName().Name)),
};
}
/// <summary>
/// Add an in memory compiled assembly to the compilation
/// </summary>
/// <param name="additionalCompilations"></param>
/// <returns></returns>
[OverloadResolutionPriority(1)]
public GeneratorTestContextBuilder AddCompilationReferences(params IReadOnlyCollection<GeneratorTestResults> additionalCompilations)
{
return additionalCompilations.Any(z => z.MetadataReference is null)
? throw new ArgumentException("All additional compilations must have a metadata reference", nameof(additionalCompilations))
: ( AddReferencesInternal(additionalCompilations.Select(z => z.MetadataReference!).ToArray()) with
{
_referenceNames = _referenceNames.Union(additionalCompilations.Select(z => z.Assembly!.GetName().Name)),
} );
}
/// <summary>
/// Add references to the given assembly names
/// </summary>
/// <param name="assemblyNames"></param>
/// <returns></returns>
[OverloadResolutionPriority(-1)]
public GeneratorTestContextBuilder AddReferences(params string[] assemblyNames)
{
// this "core assemblies hack" is from https://stackoverflow.com/a/47196516/4418060
var coreAssemblyPath = Path.GetDirectoryName(typeof(object).Assembly.Location)!;
return AddReferencesInternal(
assemblyNames.Select(z => MetadataReference.CreateFromFile(Path.Combine(coreAssemblyPath, z))).OfType<MetadataReference>().ToArray()
) with
{
_referenceNames = _referenceNames.Union(assemblyNames),
};
}
/// <summary>
/// Add references to the given assembly names
/// </summary>
/// <param name="assemblyNames"></param>
/// <returns></returns>
[OverloadResolutionPriority(0)]
public GeneratorTestContextBuilder AddReferences(params IEnumerable<string> assemblyNames)
{
var assemblyNameList = assemblyNames.ToList();
// this "core assemblies hack" is from https://stackoverflow.com/a/47196516/4418060
var coreAssemblyPath = Path.GetDirectoryName(typeof(object).Assembly.Location)!;
return AddReferencesInternal(
assemblyNameList.Select(z => MetadataReference.CreateFromFile(Path.Combine(coreAssemblyPath, z))).OfType<MetadataReference>().ToArray()
) with
{
_referenceNames = _referenceNames.Union(assemblyNameList),
};
}
/// <summary>
/// Add references to the given assembly names
/// </summary>
/// <param name="assemblyNames"></param>
/// <returns></returns>
[OverloadResolutionPriority(1)]
public GeneratorTestContextBuilder AddReferences(params IReadOnlyCollection<string> assemblyNames)
{
// this "core assemblies hack" is from https://stackoverflow.com/a/47196516/4418060
var coreAssemblyPath = Path.GetDirectoryName(typeof(object).Assembly.Location)!;
return AddReferencesInternal(
assemblyNames.Select(z => MetadataReference.CreateFromFile(Path.Combine(coreAssemblyPath, z))).OfType<MetadataReference>().ToArray()
) with
{
_referenceNames = _referenceNames.Union(assemblyNames),
};
}
/// <summary>
/// Add a set of metadata references to the compilation
/// </summary>
/// <param name="references"></param>
/// <returns></returns>
[OverloadResolutionPriority(-1)]
public GeneratorTestContextBuilder AddReferences(params MetadataReference[] references)
{
var names = _referenceNames.ToBuilder();
foreach (var reference in references)
{
names.Add(Path.GetFileName(reference.Display ?? ""));
}
return AddReferencesInternal(references) with
{
_referenceNames = names.ToImmutable(),
};
}
/// <summary>
/// Add a set of metadata references to the compilation
/// </summary>
/// <param name="references"></param>
/// <returns></returns>
[OverloadResolutionPriority(0)]
public GeneratorTestContextBuilder AddReferences(params IEnumerable<MetadataReference> references)
{
var referenceList = references.ToList();
var names = _referenceNames.ToBuilder();
foreach (var reference in referenceList)
{
names.Add(Path.GetFileName(reference.Display ?? ""));
}
return AddReferencesInternal(referenceList) with
{
_referenceNames = names.ToImmutable(),
};
}
/// <summary>
/// Add a set of metadata references to the compilation
/// </summary>
/// <param name="references"></param>
/// <returns></returns>
[OverloadResolutionPriority(1)]
public GeneratorTestContextBuilder AddReferences(params IReadOnlyCollection<MetadataReference> references)
{
var names = _referenceNames.ToBuilder();
foreach (var reference in references)
{
names.Add(Path.GetFileName(reference.Display ?? ""));
}
return AddReferencesInternal(references) with
{
_referenceNames = names.ToImmutable(),
};
}
/// <summary>
/// Add a set of metadata references to the compilation using the runtime type to identify the assembly
/// </summary>
/// <param name="references"></param>
/// <returns></returns>
[OverloadResolutionPriority(-1)]
public GeneratorTestContextBuilder AddReferences(params Type[] references) => AddReferences(references.Select(z => z.Assembly).ToArray());
/// <summary>
/// Add a set of metadata references to the compilation using the runtime type to identify the assembly
/// </summary>
/// <param name="references"></param>
/// <returns></returns>
[OverloadResolutionPriority(0)]
public GeneratorTestContextBuilder AddReferences(params IEnumerable<Type> references)
{
var referenceList = references.ToList();
return AddReferences(referenceList.Select(z => z.Assembly).ToArray());
}
/// <summary>
/// Add a set of metadata references to the compilation using the runtime type to identify the assembly
/// </summary>
/// <param name="references"></param>
/// <returns></returns>
[OverloadResolutionPriority(1)]
public GeneratorTestContextBuilder AddReferences(params IReadOnlyCollection<Type> references) => AddReferences(references.Select(z => z.Assembly).ToArray());
/// <summary>
/// Add a set of metadata references to the compilation using the runtime assembly to identify the assembly
/// </summary>
/// <param name="references"></param>
/// <returns></returns>
[OverloadResolutionPriority(-1)]
public GeneratorTestContextBuilder AddReferences(params Assembly[] references)
{
return AddReferencesInternal(references.Select(z => MetadataReference.CreateFromFile(z.Location)).OfType<MetadataReference>().ToArray()) with
{
_referenceNames = _referenceNames.Union(references.Select(z => z.GetName().Name ?? "")),
};
}
/// <summary>
/// Add a set of metadata references to the compilation using the runtime assembly to identify the assembly
/// </summary>
/// <param name="references"></param>
/// <returns></returns>
[OverloadResolutionPriority(0)]
public GeneratorTestContextBuilder AddReferences(params IEnumerable<Assembly> references)
{
var referenceList = references.ToList();
return AddReferencesInternal(referenceList.Select(z => MetadataReference.CreateFromFile(z.Location)).OfType<MetadataReference>().ToArray()) with
{
_referenceNames = _referenceNames.Union(referenceList.Select(z => z.GetName().Name ?? "")),
};
}
/// <summary>
/// Add a set of metadata references to the compilation using the runtime assembly to identify the assembly
/// </summary>
/// <param name="references"></param>
/// <returns></returns>
[OverloadResolutionPriority(1)]
public GeneratorTestContextBuilder AddReferences(params IReadOnlyCollection<Assembly> references)
{
return AddReferencesInternal(references.Select(z => MetadataReference.CreateFromFile(z.Location)).OfType<MetadataReference>().ToArray()) with
{
_referenceNames = _referenceNames.Union(references.Select(z => z.GetName().Name ?? "")),
};
}
/// <summary>
/// Set the default references for the compilation
/// </summary>
/// <returns></returns>
public GeneratorTestContextBuilder WithDefaultReferences()
{
return AddReferences(
"mscorlib.dll",
"netstandard.dll",
"System.dll",
"System.Core.dll",
#if NETCOREAPP
"System.Private.CoreLib.dll",
#endif
"System.Runtime.dll"
);
}
/// <summary>
/// Add a set of metadata references to the compilation
/// </summary>
/// <param name="references"></param>
/// <returns></returns>
private GeneratorTestContextBuilder AddReferencesInternal(IEnumerable<MetadataReference> references)
{
var set = _metadataReferences.ToBuilder();
foreach (var reference in references)
{
set.Add(reference);
}
return this with
{
_metadataReferences = set.ToImmutable(),
};
}
/// <summary>
/// Add the given source text to the compilation
/// </summary>
/// <param name="additionalSources"></param>
/// <returns></returns>
[OverloadResolutionPriority(-1)]
public GeneratorTestContextBuilder AddSources(params SourceText[] additionalSources) => this with { _sources = _sources.AddRange(additionalSources.Select(z => new NamedSourceText(z))), };
/// <summary>
/// Add the given source text to the compilation
/// </summary>
/// <param name="additionalSources"></param>
/// <returns></returns>
[OverloadResolutionPriority(0)]
public GeneratorTestContextBuilder AddSources(params IEnumerable<SourceText> additionalSources)
{
var sourceList = additionalSources.ToList();
return this with { _sources = _sources.AddRange(sourceList.Select(z => new NamedSourceText(z))), };
}
/// <summary>
/// Add the given source text to the compilation
/// </summary>
/// <param name="additionalSources"></param>
/// <returns></returns>
[OverloadResolutionPriority(1)]
public GeneratorTestContextBuilder AddSources(params IReadOnlyCollection<SourceText> additionalSources) => this with { _sources = _sources.AddRange(additionalSources.Select(z => new NamedSourceText(z))), };
/// <summary>
/// Add the given source text to the compilation as a string
/// </summary>
/// <param name="additionalSources"></param>
/// <returns></returns>
[OverloadResolutionPriority(-1)]
public GeneratorTestContextBuilder AddSources(params string[] additionalSources)
{
return this with
{
_sources = _sources.AddRange(additionalSources.Select(s => SourceText.From(s, Encoding.UTF8)).Select(z => new NamedSourceText(z))),
};
}
/// <summary>
/// Add the given source text to the compilation as a string
/// </summary>
/// <param name="additionalSources"></param>
/// <returns></returns>
[OverloadResolutionPriority(0)]
public GeneratorTestContextBuilder AddSources(params IEnumerable<string> additionalSources)
{
var sourceList = additionalSources.ToList();
return this with
{
_sources = _sources.AddRange(sourceList.Select(s => SourceText.From(s, Encoding.UTF8)).Select(z => new NamedSourceText(z))),
};
}
/// <summary>
/// Add the given source text to the compilation as a string
/// </summary>
/// <param name="additionalSources"></param>
/// <returns></returns>
[OverloadResolutionPriority(1)]
public GeneratorTestContextBuilder AddSources(params IReadOnlyCollection<string> additionalSources)
{
return this with
{
_sources = _sources.AddRange(additionalSources.Select(s => SourceText.From(s, Encoding.UTF8)).Select(z => new NamedSourceText(z))),
};
}
/// <summary>
/// Add the given source text to the compilation
/// </summary>
/// <returns></returns>
public GeneratorTestContextBuilder AddSource(string name, SourceText source) => this with { _sources = _sources.Add(new(source) { Name = name, }), };
/// <summary>
/// Add the given source text to the compilation
/// </summary>
/// <returns></returns>
public GeneratorTestContextBuilder AddSource(string name, string source) => this with { _sources = _sources.Add(new(SourceText.From(source, Encoding.UTF8)) { Name = name, }), };
/// <summary>
/// Add the given source text to the compilation
/// </summary>
/// <returns></returns>
public GeneratorTestContextBuilder AddMarkup(string name, CodeMarkup source)
{
return this with
{
_markedLocations = _markedLocations.SetItem(name, new(source.Location, source.Trigger)),
_sources = _sources.Add(new(SourceText.From(source.Code, Encoding.UTF8)) { Name = name, }),
};
}
/// <summary>
/// Add the given source text to the compilation
/// </summary>
/// <returns></returns>
public GeneratorTestContextBuilder AddMarkup(string name, string source) => AddMarkup(name, new CodeMarkup(source));
/// <summary>
/// Add the given additional text to the compilation
/// </summary>
/// <param name="additionalTexts"></param>
/// <returns></returns>
[OverloadResolutionPriority(-1)]
public GeneratorTestContextBuilder AddAdditionalTexts(params AdditionalText[] additionalTexts) => this with { _additionalTexts = _additionalTexts.AddRange(additionalTexts), };
/// <summary>
/// Add the given additional text to the compilation
/// </summary>
/// <param name="additionalTexts"></param>
/// <returns></returns>
[OverloadResolutionPriority(0)]
public GeneratorTestContextBuilder AddAdditionalTexts(params IEnumerable<AdditionalText> additionalTexts)
{
var additionalTextList = additionalTexts.ToList();
return this with { _additionalTexts = _additionalTexts.AddRange(additionalTextList), };
}
/// <summary>
/// Add the given additional text to the compilation
/// </summary>
/// <param name="additionalTexts"></param>
/// <returns></returns>
[OverloadResolutionPriority(1)]
public GeneratorTestContextBuilder AddAdditionalTexts(params IReadOnlyCollection<AdditionalText> additionalTexts) => this with { _additionalTexts = _additionalTexts.AddRange(additionalTexts), };
/// <summary>
/// Add the given additional text to the compilation for the given path
/// </summary>
/// <param name="path"></param>
/// <param name="source"></param>
/// <returns></returns>
public GeneratorTestContextBuilder AddAdditionalText(string path, SourceText source) => this with { _additionalTexts = _additionalTexts.Add(new GeneratorAdditionalText(path, source)), };
/// <summary>
/// Add the given additional text to the compilation for the given path
/// </summary>
/// <param name="path"></param>
/// <param name="source"></param>
/// <returns></returns>
public GeneratorTestContextBuilder AddAdditionalText(string path, string source) => this with { _additionalTexts = _additionalTexts.Add(new GeneratorAdditionalText(path, SourceText.From(source, Encoding.UTF8))), };
/// <summary>
/// Set the options for a given file to the compilation to be used by generators
/// </summary>
/// <param name="tree"></param>
/// <param name="key"></param>
/// <param name="value"></param>
/// <returns></returns>
public GeneratorTestContextBuilder AddOption(SyntaxTree tree, string key, string value) => AddOption(tree.FilePath, key, value);
/// <summary>
/// Set the options for a given file to the compilation to be used by generators
/// </summary>
/// <param name="tree"></param>
/// <param name="key"></param>
/// <param name="value"></param>
/// <returns></returns>
public GeneratorTestContextBuilder AddOption(AdditionalText tree, string key, string value) => AddOption(tree.Path, key, value);
/// <summary>
/// Set the options for a given file to the compilation to be used by generators
/// </summary>
/// <param name="path"></param>
/// <param name="key"></param>
/// <param name="value"></param>
/// <returns></returns>
public GeneratorTestContextBuilder AddOption(string path, string key, string value)
{
var rootOptions = _options;
if (_options.TryGetValue(path, out var fileOptions))
{
fileOptions = fileOptions.SetItem(key, value);
rootOptions = rootOptions.SetItem(path, fileOptions);
}
else
{
rootOptions = rootOptions.SetItem(path, ImmutableDictionary<string, string>.Empty.SetItem(key, value));
}
return this with { _options = rootOptions, };
}
/// <summary>
/// Set the global options for the compilation to be used by generators
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <returns></returns>
public GeneratorTestContextBuilder AddGlobalOption(string key, string value) => this with { _globalOptions = _globalOptions.SetItem(key, value), };
/// <summary>
/// Create the <see cref="GeneratorTestContext" /> from the builder
/// </summary>
/// <returns></returns>
public GeneratorTestContext Build()
{
return new(
_projectName ?? "TestProject",
_logger ?? Logger.None,
_assemblyLoadContext ?? new CollectibleTestAssemblyLoadContext(),
_metadataReferences,
_referenceNames,
_relatedTypes,
_sources,
_ignoredFilePaths,
_options,
_globalOptions,
_parseOptions,
_additionalTexts,
_markedLocations,
_diagnosticSeverity,
_customizers
);
}
/// <summary>
/// Generate and return the results of the generators
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public Task<GeneratorTestResults> GenerateAsync(CancellationToken cancellationToken = default) => Build().GenerateAsync(cancellationToken);
}