-
Notifications
You must be signed in to change notification settings - Fork 4.1k
/
Copy pathRecordStructTests.cs
7349 lines (6649 loc) · 264 KB
/
RecordStructTests.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics
{
[CompilerTrait(CompilerFeature.RecordStructs)]
public class RecordStructTests : CompilingTestBase
{
private static CSharpCompilation CreateCompilation(CSharpTestSource source)
=> CSharpTestBase.CreateCompilation(new[] { source, IsExternalInitTypeDefinition },
parseOptions: TestOptions.RegularPreview);
private CompilationVerifier CompileAndVerify(
CSharpTestSource src,
string? expectedOutput = null,
IEnumerable<MetadataReference>? references = null)
=> base.CompileAndVerify(
new[] { src, IsExternalInitTypeDefinition },
expectedOutput: expectedOutput,
parseOptions: TestOptions.RegularPreview,
references: references,
// init-only is unverifiable
verify: Verification.Skipped);
[Fact]
public void StructRecord1()
{
var src = @"
record struct Point(int X, int Y);";
var verifier = CompileAndVerify(src).VerifyDiagnostics();
verifier.VerifyIL("Point.Equals(object)", @"
{
// Code size 23 (0x17)
.maxstack 2
IL_0000: ldarg.1
IL_0001: isinst ""Point""
IL_0006: brfalse.s IL_0015
IL_0008: ldarg.0
IL_0009: ldarg.1
IL_000a: unbox.any ""Point""
IL_000f: call ""bool Point.Equals(Point)""
IL_0014: ret
IL_0015: ldc.i4.0
IL_0016: ret
}");
verifier.VerifyIL("Point.Equals(Point)", @"
{
// Code size 49 (0x31)
.maxstack 3
IL_0000: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get""
IL_0005: ldarg.0
IL_0006: ldfld ""int Point.<X>k__BackingField""
IL_000b: ldarg.1
IL_000c: ldfld ""int Point.<X>k__BackingField""
IL_0011: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)""
IL_0016: brfalse.s IL_002f
IL_0018: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get""
IL_001d: ldarg.0
IL_001e: ldfld ""int Point.<Y>k__BackingField""
IL_0023: ldarg.1
IL_0024: ldfld ""int Point.<Y>k__BackingField""
IL_0029: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)""
IL_002e: ret
IL_002f: ldc.i4.0
IL_0030: ret
}");
}
[Fact]
public void StructRecord2()
{
var src = @"
using System;
record struct S(int X, int Y)
{
public static void Main()
{
var s1 = new S(0, 1);
var s2 = new S(0, 1);
Console.WriteLine(s1.X);
Console.WriteLine(s1.Y);
Console.WriteLine(s1.Equals(s2));
Console.WriteLine(s1.Equals(new S(1, 0)));
}
}";
var verifier = CompileAndVerify(src, expectedOutput: @"0
1
True
False").VerifyDiagnostics();
}
[Fact]
public void StructRecord3()
{
var src = @"
using System;
record struct S(int X, int Y)
{
public bool Equals(S s) => false;
public static void Main()
{
var s1 = new S(0, 1);
Console.WriteLine(s1.Equals(s1));
}
}";
var verifier = CompileAndVerify(src, expectedOutput: @"False")
.VerifyDiagnostics(
// (5,17): warning CS8851: 'S' defines 'Equals' but not 'GetHashCode'
// public bool Equals(S s) => false;
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("S").WithLocation(5, 17));
verifier.VerifyIL("S.Main", @"
{
// Code size 23 (0x17)
.maxstack 3
.locals init (S V_0) //s1
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.0
IL_0003: ldc.i4.1
IL_0004: call ""S..ctor(int, int)""
IL_0009: ldloca.s V_0
IL_000b: ldloc.0
IL_000c: call ""bool S.Equals(S)""
IL_0011: call ""void System.Console.WriteLine(bool)""
IL_0016: ret
}");
}
[Fact]
public void StructRecord5()
{
var src = @"
using System;
record struct S(int X, int Y)
{
public bool Equals(S s)
{
Console.Write(""s"");
return true;
}
public static void Main()
{
var s1 = new S(0, 1);
s1.Equals((object)s1);
s1.Equals(s1);
}
}";
CompileAndVerify(src, expectedOutput: @"ss")
.VerifyDiagnostics(
// (5,17): warning CS8851: 'S' defines 'Equals' but not 'GetHashCode'
// public bool Equals(S s)
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("S").WithLocation(5, 17));
}
[Fact]
public void StructRecordDefaultCtor()
{
const string src = @"
public record struct S(int X);";
const string src2 = @"
class C
{
public S M() => new S();
}";
var comp = CreateCompilation(src + src2);
comp.VerifyDiagnostics();
comp = CreateCompilation(src);
var comp2 = CreateCompilation(src2, references: new[] { comp.EmitToImageReference() });
comp2.VerifyDiagnostics();
}
[Fact]
public void Equality_01()
{
var source =
@"using static System.Console;
record struct S;
class Program
{
static void Main()
{
var x = new S();
var y = new S();
WriteLine(x.Equals(y));
WriteLine(((object)x).Equals(y));
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe);
var verifier = CompileAndVerify(comp, expectedOutput: @"True
True").VerifyDiagnostics();
verifier.VerifyIL("S.Equals(S)", @"
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldc.i4.1
IL_0001: ret
}");
verifier.VerifyIL("S.Equals(object)", @"
{
// Code size 23 (0x17)
.maxstack 2
IL_0000: ldarg.1
IL_0001: isinst ""S""
IL_0006: brfalse.s IL_0015
IL_0008: ldarg.0
IL_0009: ldarg.1
IL_000a: unbox.any ""S""
IL_000f: call ""bool S.Equals(S)""
IL_0014: ret
IL_0015: ldc.i4.0
IL_0016: ret
}");
}
[Fact]
public void RecordStructLanguageVersion()
{
var src1 = @"
struct Point(int x, int y);
";
var src2 = @"
record struct Point { }
";
var src3 = @"
record struct Point(int x, int y);
";
var comp = CreateCompilation(new[] { src1, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll);
comp.VerifyDiagnostics(
// (2,13): error CS1514: { expected
// struct Point(int x, int y);
Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(2, 13),
// (2,13): error CS1513: } expected
// struct Point(int x, int y);
Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(2, 13),
// (2,13): error CS8803: Top-level statements must precede namespace and type declarations.
// struct Point(int x, int y);
Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "(int x, int y);").WithLocation(2, 13),
// (2,13): error CS8805: Program using top-level statements must be an executable.
// struct Point(int x, int y);
Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable, "(int x, int y);").WithLocation(2, 13),
// (2,13): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// struct Point(int x, int y);
Diagnostic(ErrorCode.ERR_IllegalStatement, "(int x, int y)").WithLocation(2, 13),
// (2,14): error CS8185: A declaration is not allowed in this context.
// struct Point(int x, int y);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x").WithLocation(2, 14),
// (2,14): error CS0165: Use of unassigned local variable 'x'
// struct Point(int x, int y);
Diagnostic(ErrorCode.ERR_UseDefViolation, "int x").WithArguments("x").WithLocation(2, 14),
// (2,21): error CS8185: A declaration is not allowed in this context.
// struct Point(int x, int y);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int y").WithLocation(2, 21),
// (2,21): error CS0165: Use of unassigned local variable 'y'
// struct Point(int x, int y);
Diagnostic(ErrorCode.ERR_UseDefViolation, "int y").WithArguments("y").WithLocation(2, 21)
);
comp = CreateCompilation(new[] { src2, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll);
comp.VerifyDiagnostics(
// (2,8): error CS8652: The feature 'record structs' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version.
// record struct Point { }
Diagnostic(ErrorCode.ERR_FeatureInPreview, "struct").WithArguments("record structs").WithLocation(2, 8)
);
comp = CreateCompilation(new[] { src3, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll);
comp.VerifyDiagnostics(
// (2,8): error CS8652: The feature 'record structs' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version.
// record struct Point(int x, int y);
Diagnostic(ErrorCode.ERR_FeatureInPreview, "struct").WithArguments("record structs").WithLocation(2, 8)
);
comp = CreateCompilation(new[] { src1, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseDll);
comp.VerifyDiagnostics(
// (2,13): error CS1514: { expected
// struct Point(int x, int y);
Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(2, 13),
// (2,13): error CS1513: } expected
// struct Point(int x, int y);
Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(2, 13),
// (2,13): error CS8803: Top-level statements must precede namespace and type declarations.
// struct Point(int x, int y);
Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "(int x, int y);").WithLocation(2, 13),
// (2,13): error CS8805: Program using top-level statements must be an executable.
// struct Point(int x, int y);
Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable, "(int x, int y);").WithLocation(2, 13),
// (2,13): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// struct Point(int x, int y);
Diagnostic(ErrorCode.ERR_IllegalStatement, "(int x, int y)").WithLocation(2, 13),
// (2,14): error CS8185: A declaration is not allowed in this context.
// struct Point(int x, int y);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x").WithLocation(2, 14),
// (2,14): error CS0165: Use of unassigned local variable 'x'
// struct Point(int x, int y);
Diagnostic(ErrorCode.ERR_UseDefViolation, "int x").WithArguments("x").WithLocation(2, 14),
// (2,21): error CS8185: A declaration is not allowed in this context.
// struct Point(int x, int y);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int y").WithLocation(2, 21),
// (2,21): error CS0165: Use of unassigned local variable 'y'
// struct Point(int x, int y);
Diagnostic(ErrorCode.ERR_UseDefViolation, "int y").WithArguments("y").WithLocation(2, 21)
);
comp = CreateCompilation(new[] { src2, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseDll);
comp.VerifyDiagnostics();
comp = CreateCompilation(new[] { src3, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseDll);
comp.VerifyDiagnostics();
}
[Fact]
public void RecordStructLanguageVersion_Nested()
{
var src1 = @"
class C
{
struct Point(int x, int y);
}
";
var src2 = @"
class D
{
record struct Point { }
}
";
var src3 = @"
struct E
{
record struct Point(int x, int y);
}
";
var src4 = @"
namespace NS
{
record struct Point { }
}
";
var comp = CreateCompilation(src1, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (4,17): error CS1514: { expected
// struct Point(int x, int y);
Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(4, 17),
// (4,17): error CS1513: } expected
// struct Point(int x, int y);
Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(4, 17),
// (4,31): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration
// struct Point(int x, int y);
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 31),
// (4,31): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration
// struct Point(int x, int y);
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 31)
);
comp = CreateCompilation(new[] { src2, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (4,12): error CS8652: The feature 'record structs' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version.
// record struct Point { }
Diagnostic(ErrorCode.ERR_FeatureInPreview, "struct").WithArguments("record structs").WithLocation(4, 12)
);
comp = CreateCompilation(new[] { src3, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (4,12): error CS8652: The feature 'record structs' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version.
// record struct Point(int x, int y);
Diagnostic(ErrorCode.ERR_FeatureInPreview, "struct").WithArguments("record structs").WithLocation(4, 12)
);
comp = CreateCompilation(src4, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (4,12): error CS8652: The feature 'record structs' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version.
// record struct Point { }
Diagnostic(ErrorCode.ERR_FeatureInPreview, "struct").WithArguments("record structs").WithLocation(4, 12)
);
comp = CreateCompilation(src1);
comp.VerifyDiagnostics(
// (4,17): error CS1514: { expected
// struct Point(int x, int y);
Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(4, 17),
// (4,17): error CS1513: } expected
// struct Point(int x, int y);
Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(4, 17),
// (4,31): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration
// struct Point(int x, int y);
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 31),
// (4,31): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration
// struct Point(int x, int y);
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 31)
);
comp = CreateCompilation(src2);
comp.VerifyDiagnostics();
comp = CreateCompilation(src3);
comp.VerifyDiagnostics();
comp = CreateCompilation(src4);
comp.VerifyDiagnostics();
}
[Fact]
public void TypeDeclaration_IsStruct()
{
var src = @"
record struct Point(int x, int y);
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
CompileAndVerify(comp, symbolValidator: validateModule, sourceSymbolValidator: validateModule);
Assert.True(SyntaxFacts.IsTypeDeclaration(SyntaxKind.RecordStructDeclaration));
static void validateModule(ModuleSymbol module)
{
var isSourceSymbol = module is SourceModuleSymbol;
var point = module.GlobalNamespace.GetTypeMember("Point");
Assert.True(point.IsValueType);
Assert.False(point.IsReferenceType);
Assert.False(point.IsRecord);
Assert.Equal(TypeKind.Struct, point.TypeKind);
Assert.Equal(SpecialType.System_ValueType, point.BaseTypeNoUseSiteDiagnostics.SpecialType);
Assert.Equal("Point", point.ToTestDisplayString());
if (isSourceSymbol)
{
Assert.True(point is SourceNamedTypeSymbol);
Assert.True(point.IsRecordStruct);
Assert.True(point.GetPublicSymbol().IsRecord);
Assert.Equal("record struct Point", point.ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword)));
}
else
{
Assert.True(point is PENamedTypeSymbol);
Assert.False(point.IsRecordStruct);
Assert.False(point.GetPublicSymbol().IsRecord);
Assert.Equal("struct Point", point.ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword)));
}
}
}
[Fact]
public void TypeDeclaration_IsStruct_InConstraints()
{
var src = @"
record struct Point(int x, int y);
class C<T> where T : struct
{
void M(C<Point> c) { }
}
class C2<T> where T : new()
{
void M(C2<Point> c) { }
}
class C3<T> where T : class
{
void M(C3<Point> c) { } // 1
}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (16,22): error CS0452: The type 'Point' must be a reference type in order to use it as parameter 'T' in the generic type or method 'C3<T>'
// void M(C3<Point> c) { } // 1
Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "c").WithArguments("C3<T>", "T", "Point").WithLocation(16, 22)
);
}
[Fact]
public void TypeDeclaration_IsStruct_Unmanaged()
{
var src = @"
record struct Point(int x, int y);
record struct Point2(string x, string y);
class C<T> where T : unmanaged
{
void M(C<Point> c) { }
void M2(C<Point2> c) { } // 1
}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (8,23): error CS8377: The type 'Point2' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'C<T>'
// void M2(C<Point2> c) { } // 1
Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "c").WithArguments("C<T>", "T", "Point2").WithLocation(8, 23)
);
}
[Fact]
public void IsRecord_Generic()
{
var src = @"
record struct Point<T>(T x, T y);
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
CompileAndVerify(comp, symbolValidator: validateModule, sourceSymbolValidator: validateModule);
static void validateModule(ModuleSymbol module)
{
var isSourceSymbol = module is SourceModuleSymbol;
var point = module.GlobalNamespace.GetTypeMember("Point");
Assert.True(point.IsValueType);
Assert.False(point.IsReferenceType);
Assert.False(point.IsRecord);
Assert.Equal(TypeKind.Struct, point.TypeKind);
Assert.Equal(SpecialType.System_ValueType, point.BaseTypeNoUseSiteDiagnostics.SpecialType);
Assert.True(SyntaxFacts.IsTypeDeclaration(SyntaxKind.RecordStructDeclaration));
if (isSourceSymbol)
{
Assert.True(point is SourceNamedTypeSymbol);
Assert.True(point.IsRecordStruct);
Assert.True(point.GetPublicSymbol().IsRecord);
}
else
{
Assert.True(point is PENamedTypeSymbol);
Assert.False(point.IsRecordStruct);
Assert.False(point.GetPublicSymbol().IsRecord);
}
}
}
[Fact]
public void IsRecord_Retargeting()
{
var src = @"
public record struct Point(int x, int y);
";
var comp = CreateCompilation(src, targetFramework: TargetFramework.Mscorlib40);
var comp2 = CreateCompilation("", targetFramework: TargetFramework.Mscorlib46, references: new[] { comp.ToMetadataReference() });
var point = comp2.GlobalNamespace.GetTypeMember("Point");
Assert.Equal("Point", point.ToTestDisplayString());
Assert.IsType<RetargetingNamedTypeSymbol>(point);
Assert.True(point.IsRecordStruct);
Assert.True(point.GetPublicSymbol().IsRecord);
}
[Fact]
public void IsRecord_AnonymousType()
{
var src = @"
class C
{
void M()
{
var x = new { X = 1 };
}
}
";
var comp = CreateCompilation(src);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree, ignoreAccessibility: false);
var creation = tree.GetRoot().DescendantNodes().OfType<AnonymousObjectCreationExpressionSyntax>().Single();
var type = model.GetTypeInfo(creation).Type!;
Assert.Equal("<anonymous type: System.Int32 X>", type.ToTestDisplayString());
Assert.IsType<AnonymousTypeManager.AnonymousTypePublicSymbol>(((Symbols.PublicModel.NonErrorNamedTypeSymbol)type).UnderlyingNamedTypeSymbol);
Assert.False(type.IsRecord);
}
[Fact]
public void IsRecord_ErrorType()
{
var src = @"
class C
{
Error M() => throw null;
}
";
var comp = CreateCompilation(src);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree, ignoreAccessibility: false);
var method = tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single();
var type = model.GetDeclaredSymbol(method)!.ReturnType;
Assert.Equal("Error", type.ToTestDisplayString());
Assert.IsType<ExtendedErrorTypeSymbol>(((Symbols.PublicModel.ErrorTypeSymbol)type).UnderlyingNamedTypeSymbol);
Assert.False(type.IsRecord);
}
[Fact]
public void IsRecord_Pointer()
{
var src = @"
class C
{
int* M() => throw null;
}
";
var comp = CreateCompilation(src, options: TestOptions.UnsafeReleaseDll);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree, ignoreAccessibility: false);
var method = tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single();
var type = model.GetDeclaredSymbol(method)!.ReturnType;
Assert.Equal("System.Int32*", type.ToTestDisplayString());
Assert.IsType<PointerTypeSymbol>(((Symbols.PublicModel.PointerTypeSymbol)type).UnderlyingTypeSymbol);
Assert.False(type.IsRecord);
}
[Fact]
public void IsRecord_Dynamic()
{
var src = @"
class C
{
void M(dynamic d)
{
}
}
";
var comp = CreateCompilation(src);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree, ignoreAccessibility: false);
var method = tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single();
var type = model.GetDeclaredSymbol(method)!.GetParameterType(0);
Assert.Equal("dynamic", type.ToTestDisplayString());
Assert.IsType<DynamicTypeSymbol>(((Symbols.PublicModel.DynamicTypeSymbol)type).UnderlyingTypeSymbol);
Assert.False(type.IsRecord);
}
[Fact]
public void TypeDeclaration_MayNotHaveBaseType()
{
var src = @"
record struct Point(int x, int y) : object;
record struct Point2(int x, int y) : System.ValueType;
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (2,37): error CS0527: Type 'object' in interface list is not an interface
// record struct Point(int x, int y) : object;
Diagnostic(ErrorCode.ERR_NonInterfaceInInterfaceList, "object").WithArguments("object").WithLocation(2, 37),
// (3,38): error CS0527: Type 'ValueType' in interface list is not an interface
// record struct Point2(int x, int y) : System.ValueType;
Diagnostic(ErrorCode.ERR_NonInterfaceInInterfaceList, "System.ValueType").WithArguments("System.ValueType").WithLocation(3, 38)
);
}
[Fact]
public void TypeDeclaration_MayNotHaveTypeConstraintsWithoutTypeParameters()
{
var src = @"
record struct Point(int x, int y) where T : struct;
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (2,35): error CS0080: Constraints are not allowed on non-generic declarations
// record struct Point(int x, int y) where T : struct;
Diagnostic(ErrorCode.ERR_ConstraintOnlyAllowedOnGenericDecl, "where").WithLocation(2, 35)
);
}
[Fact]
public void TypeDeclaration_AllowedModifiers()
{
var src = @"
readonly partial record struct S1;
public record struct S2;
internal record struct S3;
public class Base
{
public int S6;
}
public class C : Base
{
private protected record struct S4;
protected internal record struct S5;
new record struct S6;
}
unsafe record struct S7;
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeDebugDll);
comp.VerifyDiagnostics();
Assert.Equal(Accessibility.Internal, comp.GlobalNamespace.GetTypeMember("S1").DeclaredAccessibility);
Assert.Equal(Accessibility.Public, comp.GlobalNamespace.GetTypeMember("S2").DeclaredAccessibility);
Assert.Equal(Accessibility.Internal, comp.GlobalNamespace.GetTypeMember("S3").DeclaredAccessibility);
Assert.Equal(Accessibility.ProtectedAndInternal, comp.GlobalNamespace.GetTypeMember("C").GetTypeMember("S4").DeclaredAccessibility);
Assert.Equal(Accessibility.ProtectedOrInternal, comp.GlobalNamespace.GetTypeMember("C").GetTypeMember("S5").DeclaredAccessibility);
}
[Fact]
public void TypeDeclaration_DisallowedModifiers()
{
var src = @"
abstract record struct S1;
volatile record struct S2;
extern record struct S3;
virtual record struct S4;
override record struct S5;
async record struct S6;
ref record struct S7;
unsafe record struct S8;
static record struct S9;
sealed record struct S10;
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (2,24): error CS0106: The modifier 'abstract' is not valid for this item
// abstract record struct S1;
Diagnostic(ErrorCode.ERR_BadMemberFlag, "S1").WithArguments("abstract").WithLocation(2, 24),
// (3,24): error CS0106: The modifier 'volatile' is not valid for this item
// volatile record struct S2;
Diagnostic(ErrorCode.ERR_BadMemberFlag, "S2").WithArguments("volatile").WithLocation(3, 24),
// (4,22): error CS0106: The modifier 'extern' is not valid for this item
// extern record struct S3;
Diagnostic(ErrorCode.ERR_BadMemberFlag, "S3").WithArguments("extern").WithLocation(4, 22),
// (5,23): error CS0106: The modifier 'virtual' is not valid for this item
// virtual record struct S4;
Diagnostic(ErrorCode.ERR_BadMemberFlag, "S4").WithArguments("virtual").WithLocation(5, 23),
// (6,24): error CS0106: The modifier 'override' is not valid for this item
// override record struct S5;
Diagnostic(ErrorCode.ERR_BadMemberFlag, "S5").WithArguments("override").WithLocation(6, 24),
// (7,21): error CS0106: The modifier 'async' is not valid for this item
// async record struct S6;
Diagnostic(ErrorCode.ERR_BadMemberFlag, "S6").WithArguments("async").WithLocation(7, 21),
// (8,19): error CS0106: The modifier 'ref' is not valid for this item
// ref record struct S7;
Diagnostic(ErrorCode.ERR_BadMemberFlag, "S7").WithArguments("ref").WithLocation(8, 19),
// (9,22): error CS0227: Unsafe code may only appear if compiling with /unsafe
// unsafe record struct S8;
Diagnostic(ErrorCode.ERR_IllegalUnsafe, "S8").WithLocation(9, 22),
// (10,22): error CS0106: The modifier 'static' is not valid for this item
// static record struct S9;
Diagnostic(ErrorCode.ERR_BadMemberFlag, "S9").WithArguments("static").WithLocation(10, 22),
// (11,22): error CS0106: The modifier 'sealed' is not valid for this item
// sealed record struct S10;
Diagnostic(ErrorCode.ERR_BadMemberFlag, "S10").WithArguments("sealed").WithLocation(11, 22)
);
}
[Fact]
public void TypeDeclaration_DuplicatesModifiers()
{
var src = @"
public public record struct S2;
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (2,8): error CS1004: Duplicate 'public' modifier
// public public record struct S2;
Diagnostic(ErrorCode.ERR_DuplicateModifier, "public").WithArguments("public").WithLocation(2, 8)
);
}
[Fact]
public void TypeDeclaration_BeforeTopLevelStatement()
{
var src = @"
record struct S;
System.Console.WriteLine();
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (3,1): error CS8803: Top-level statements must precede namespace and type declarations.
// System.Console.WriteLine();
Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "System.Console.WriteLine();").WithLocation(3, 1)
);
}
[Fact]
public void TypeDeclaration_WithTypeParameters()
{
var src = @"
S<string> local = default;
local.ToString();
record struct S<T>;
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
Assert.Equal(new[] { "T" }, comp.GlobalNamespace.GetTypeMember("S").TypeParameters.ToTestDisplayStrings());
}
[Fact]
public void TypeDeclaration_AllowedModifiersForMembers()
{
var src = @"
record struct S
{
protected int Property { get; set; } // 1
internal protected string field; // 2, 3
abstract void M(); // 4
virtual void M2() { } // 5
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (4,19): error CS0666: 'S.Property': new protected member declared in struct
// protected int Property { get; set; } // 1
Diagnostic(ErrorCode.ERR_ProtectedInStruct, "Property").WithArguments("S.Property").WithLocation(4, 19),
// (5,31): error CS0666: 'S.field': new protected member declared in struct
// internal protected string field; // 2, 3
Diagnostic(ErrorCode.ERR_ProtectedInStruct, "field").WithArguments("S.field").WithLocation(5, 31),
// (5,31): warning CS0649: Field 'S.field' is never assigned to, and will always have its default value null
// internal protected string field; // 2, 3
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("S.field", "null").WithLocation(5, 31),
// (6,19): error CS0621: 'S.M()': virtual or abstract members cannot be private
// abstract void M(); // 4
Diagnostic(ErrorCode.ERR_VirtualPrivate, "M").WithArguments("S.M()").WithLocation(6, 19),
// (7,18): error CS0621: 'S.M2()': virtual or abstract members cannot be private
// virtual void M2() { } // 5
Diagnostic(ErrorCode.ERR_VirtualPrivate, "M2").WithArguments("S.M2()").WithLocation(7, 18)
);
}
[Fact]
public void TypeDeclaration_ImplementInterface()
{
var src = @"
I i = (I)default(S);
System.Console.Write(i.M(""four""));
I i2 = (I)default(S2);
System.Console.Write(i2.M(""four""));
interface I
{
int M(string s);
}
public record struct S : I
{
public int M(string s)
=> s.Length;
}
public record struct S2 : I
{
int I.M(string s)
=> s.Length + 1;
}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "45");
AssertEx.Equal(new[] {
"System.Int32 S.M(System.String s)",
"System.String S.ToString()",
"System.Boolean S.PrintMembers(System.Text.StringBuilder builder)",
"System.Boolean S.op_Inequality(S left, S right)",
"System.Boolean S.op_Equality(S left, S right)",
"System.Int32 S.GetHashCode()",
"System.Boolean S.Equals(System.Object obj)",
"System.Boolean S.Equals(S other)",
"S..ctor()" },
comp.GetMember<NamedTypeSymbol>("S").GetMembers().ToTestDisplayStrings());
}
[Fact]
public void TypeDeclaration_SatisfiesStructConstraint()
{
var src = @"
S s = default;
System.Console.Write(M(s));
static int M<T>(T t) where T : struct, I
=> t.Property;
public interface I
{
int Property { get; }
}
public record struct S : I
{
public int Property => 42;
}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "42");
}
[Fact]
public void TypeDeclaration_AccessingThis()
{
var src = @"
S s = new S();
System.Console.Write(s.M());
public record struct S
{
public int Property => 42;
public int M()
=> this.Property;
}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
var verifier = CompileAndVerify(comp, expectedOutput: "42");
verifier.VerifyIL("S.M", @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""int S.Property.get""
IL_0006: ret
}
");
}
[Fact]
public void TypeDeclaration_NoBaseInitializer()
{
var src = @"
public record struct S
{
public S(int i) : base() { }
}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (4,12): error CS0522: 'S': structs cannot call base class constructors
// public S(int i) : base() { }
Diagnostic(ErrorCode.ERR_StructWithBaseConstructorCall, "S").WithArguments("S").WithLocation(4, 12)
);
}
[Fact]
public void TypeDeclaration_NoParameterlessConstructor()
{
var src = @"
public record struct S
{
public S() { }
}
";
// This will be allowed in C# 10
// Tracking issue https://github.com/dotnet/roslyn/issues/52240
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (4,12): error CS0568: Structs cannot contain explicit parameterless constructors
// public S() { }
Diagnostic(ErrorCode.ERR_StructsCantContainDefaultConstructor, "S").WithLocation(4, 12)
);
}
[Fact]
public void TypeDeclaration_NoInstanceInitializers()
{
var src = @"
public record struct S
{
public int field = 42;
public int Property { get; set; } = 43;
}
";
// This will be allowed in C# 10, or we need to improve the message
// Tracking issue https://github.com/dotnet/roslyn/issues/52240
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (4,16): error CS0573: 'S': cannot have instance property or field initializers in structs
// public int field = 42;
Diagnostic(ErrorCode.ERR_FieldInitializerInStruct, "field").WithArguments("S").WithLocation(4, 16),