From 974bb4e130336996bd073b94e438235cffbb7489 Mon Sep 17 00:00:00 2001 From: Fred Silberberg Date: Wed, 10 May 2023 13:13:36 -0700 Subject: [PATCH] Implement Required Members for VB (#66084) * Add and implement IPropertySymbol.IsRequired and IFieldSymbol.IsRequired. * Add and implement NamedTypeSymbol.AllRequiredMembers. * Implement MethodSymbol.HasSetsRequiredMembers * Implement checking required members in constructors, sketch out test methods. * Implement remaining errors: * Block inheriting from types with required members * Block calling constructors with invalid required member lists * Block substituting types with required members in As New, unless the parameterless ctor has SetsRequiredMembers. * Fill out all tests * PR feedback * PR feedback# * PR Feedback * Compile errors, missed feedback item. * Fix compile errors, add a few more tests. * Addressed a number of PR feedback comments. Lots of new tests, fixed a few revealed bugs, handle Nothing converted to a struct with required members. * PR feedback * Remove Nothing handling to align with C#. * Remove suppressions of cascading errors. * Expand unbound test coverage. * Expand tuple test coverage. * Pass correct containing type in local rewriting of tuples. * Fix test baseline * Simplify EnsureRequiredMembersCalcuated. * Add additional test verification. * Remove unnecessary imports * Tighten retargeting asserts and add a test * Fix C# equivalent code. --- .../Compiler Breaking Changes - DotNet 7.md | 8 + .../Symbol/Symbols/RequiredMembersTests.cs | 978 +++++-- src/Compilers/Test/Core/CommonTestBase.cs | 36 +- .../VisualBasic/CompilationTestUtils.vb | 2 +- .../Test/Utilities/VisualBasic/MockSymbols.vb | 12 + .../Portable/Binding/Binder_Attributes.vb | 2 + .../Binding/Binder_ObjectInitializer.vb | 81 +- .../Portable/Binding/Binder_XmlLiterals.vb | 12 + .../VisualBasic/Portable/Errors/ErrorFacts.vb | 5 + .../VisualBasic/Portable/Errors/Errors.vb | 8 +- .../LocalRewriter_TupleLiteralExpression.vb | 5 + .../SynthesizedContainer.vb | 6 + .../AnonymousTypeOrDelegatePublicSymbol.vb | 7 +- .../AnonymousTypeOrDelegateTemplateSymbol.vb | 6 + .../AnonymousType_PropertySymbol.vb | 6 + .../Portable/Symbols/ConstraintsHelper.vb | 86 +- .../Portable/Symbols/ErrorMethodSymbol.vb | 6 + .../Portable/Symbols/ErrorTypeSymbol.vb | 6 + .../Portable/Symbols/FieldSymbol.vb | 4 +- .../Symbols/Metadata/PE/PEFieldSymbol.vb | 11 + .../Symbols/Metadata/PE/PEMethodSymbol.vb | 50 +- .../Symbols/Metadata/PE/PENamedTypeSymbol.vb | 6 + .../Symbols/Metadata/PE/PEPropertySymbol.vb | 12 + .../Portable/Symbols/MethodSymbol.vb | 2 + .../Portable/Symbols/NamedTypeSymbol.vb | 108 + .../Symbols/ObsoleteAttributeHelpers.vb | 3 +- .../Portable/Symbols/PropertySymbol.vb | 4 +- .../Symbols/ReducedExtensionMethodSymbol.vb | 6 + .../Retargeting/RetargetingFieldSymbol.vb | 7 + .../Retargeting/RetargetingMethodSymbol.vb | 6 + .../Retargeting/RetargetingNamedTypeSymbol.vb | 7 + .../Retargeting/RetargetingPropertySymbol.vb | 7 + .../Symbols/SignatureOnlyMethodSymbol.vb | 6 + .../Symbols/SignatureOnlyPropertySymbol.vb | 6 + .../Portable/Symbols/Source/LambdaSymbol.vb | 5 + .../Symbols/Source/SourceFieldSymbol.vb | 6 + .../Source/SourceMemberContainerTypeSymbol.vb | 6 + .../Symbols/Source/SourceMethodSymbol.vb | 6 + .../Symbols/Source/SourceNamedTypeSymbol.vb | 5 + .../Source/SourceNamedTypeSymbol_ComClass.vb | 18 + .../SourceNamedTypeSymbol_GroupClass.vb | 10 +- .../Symbols/Source/SourcePropertySymbol.vb | 6 + .../Symbols/Source/SynthesizedFieldSymbol.vb | 6 + .../Symbols/SubstitutedFieldSymbol.vb | 6 + .../Symbols/SubstitutedMethodSymbol.vb | 6 + .../Portable/Symbols/SubstitutedNamedType.vb | 6 + .../Symbols/SubstitutedPropertySymbol.vb | 6 + .../Portable/Symbols/SymbolExtensions.vb | 7 + .../Portable/Symbols/Symbol_Attributes.vb | 2 + .../SynthesizedBackingFieldBase.vb | 6 + .../SynthesizedDelegateMethodSymbol.vb | 6 + .../SynthesizedEventDelegateSymbol.vb | 10 +- .../SynthesizedGlobalMethodBase.vb | 6 + .../SynthesizedMethodBase.vb | 6 + ...SynthesizedOverridingWitheventsProperty.vb | 6 + .../SynthesizedPropertyBase.vb | 6 + .../Symbols/Tuples/TupleFieldSymbol.vb | 6 + .../Symbols/Tuples/TupleMethodSymbol.vb | 6 + .../Symbols/Tuples/TuplePropertySymbol.vb | 6 + .../Symbols/Tuples/TupleTypeSymbol.vb | 5 + .../Portable/Symbols/UnboundGenericType.vb | 6 + .../VisualBasic/Portable/VBResources.resx | 15 + .../Portable/xlf/VBResources.cs.xlf | 25 + .../Portable/xlf/VBResources.de.xlf | 25 + .../Portable/xlf/VBResources.es.xlf | 25 + .../Portable/xlf/VBResources.fr.xlf | 25 + .../Portable/xlf/VBResources.it.xlf | 25 + .../Portable/xlf/VBResources.ja.xlf | 25 + .../Portable/xlf/VBResources.ko.xlf | 25 + .../Portable/xlf/VBResources.pl.xlf | 25 + .../Portable/xlf/VBResources.pt-BR.xlf | 25 + .../Portable/xlf/VBResources.ru.xlf | 25 + .../Portable/xlf/VBResources.tr.xlf | 25 + .../Portable/xlf/VBResources.zh-Hans.xlf | 25 + .../Portable/xlf/VBResources.zh-Hant.xlf | 25 + .../Semantics/RequiredMembersTests.vb | 2479 +++++++++++++++++ .../Symbols/DisplayClassVariable.vb | 6 + .../Symbols/EEMethodSymbol.vb | 5 + .../Symbols/EENamedTypeSymbol.vb | 6 + 79 files changed, 4305 insertions(+), 224 deletions(-) create mode 100644 docs/compilers/Visual Basic/Compiler Breaking Changes - DotNet 7.md create mode 100644 src/Compilers/VisualBasic/Test/Semantic/Semantics/RequiredMembersTests.vb diff --git a/docs/compilers/Visual Basic/Compiler Breaking Changes - DotNet 7.md b/docs/compilers/Visual Basic/Compiler Breaking Changes - DotNet 7.md new file mode 100644 index 0000000000000..82ce50df2cdc5 --- /dev/null +++ b/docs/compilers/Visual Basic/Compiler Breaking Changes - DotNet 7.md @@ -0,0 +1,8 @@ +# This document lists known breaking changes in Roslyn after .NET 6 all the way to .NET 7. + +## `RequiredMembersAttribute` cannot be manually applied + +**Introduced in VS 17.6** + +As part of implementing VB support for consuming `required` APIs, it is now an error to manually apply `RequiredMembersAttribute` in +source. VB will now correctly interpret these attributes in metadata and allow instanciating types with required members. \ No newline at end of file diff --git a/src/Compilers/CSharp/Test/Symbol/Symbols/RequiredMembersTests.cs b/src/Compilers/CSharp/Test/Symbol/Symbols/RequiredMembersTests.cs index 7cc6d7980fdc9..0119faf1fbe84 100644 --- a/src/Compilers/CSharp/Test/Symbol/Symbols/RequiredMembersTests.cs +++ b/src/Compilers/CSharp/Test/Symbol/Symbols/RequiredMembersTests.cs @@ -18,26 +18,9 @@ namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols; [CompilerTrait(CompilerFeature.RequiredMembers)] public class RequiredMembersTests : CSharpTestBase { - private const string RequiredMemberAttributeVB = @" -Namespace System.Runtime.CompilerServices - - Public Class RequiredMemberAttribute - Inherits Attribute - End Class -End Namespace -Namespace System.Diagnostics.CodeAnalysis - - Public Class SetsRequiredMembersAttribute - Inherits Attribute - End Class -End Namespace"; - private static CSharpCompilation CreateCompilationWithRequiredMembers(CSharpTestSource source, IEnumerable? references = null, CSharpParseOptions? parseOptions = null, CSharpCompilationOptions? options = null, string? assemblyName = null, TargetFramework targetFramework = TargetFramework.Standard) => CreateCompilation(new[] { source, RequiredMemberAttribute, SetsRequiredMembersAttribute, CompilerFeatureRequiredAttribute }, references, options: options, parseOptions: parseOptions, assemblyName: assemblyName, targetFramework: targetFramework); - private Compilation CreateVisualBasicCompilationWithRequiredMembers(string source) - => CreateVisualBasicCompilation(new[] { source, RequiredMemberAttributeVB }); - private static Action ValidateRequiredMembersInModule(string[] memberPaths, string expectedAttributeLayout) { return module => @@ -1759,26 +1742,59 @@ public class C [Fact] public void EnforcedRequiredMembers_NoInheritance_Unsettable_FromMetadata() { - var vb = @" -Imports System.Runtime.CompilerServices + // Equivalent to: + // public class C + // { + // public required readonly int Field1; + // public required int Prop1 { get; } + // } + var il = @" +.class public auto ansi C + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .field private int32 _Prop1 + .field public initonly int32 Field1 + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) - -Public Class C - - Public Readonly Property Prop1 As Integer - - Public Readonly Field1 As Integer -End Class -"; + .method public specialname rtspecialname + instance void .ctor () cil managed + { + ldarg.0 + call instance void [mscorlib]System.Object::.ctor() + ret + } + + .method public specialname + instance int32 get_Prop1 () cil managed + { + IL_0000: ldarg.0 + IL_0001: ldfld int32 C::_Prop1 + IL_0006: br.s IL_0008 - var vbComp = CreateVisualBasicCompilationWithRequiredMembers(vb); - vbComp.VerifyEmitDiagnostics(); + IL_0008: ret + } + + .property instance int32 Prop1() + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .get instance int32 C::get_Prop1() + } +}"; + + var ilRef = CompileIL(il); var c = @" var c = new C(); c = new C() { Prop1 = 1, Field1 = 1 }; "; - var comp = CreateCompilation(new[] { c }, references: new[] { vbComp.EmitToImageReference() }); + var comp = CreateCompilation(new[] { c }, references: new[] { ilRef }, targetFramework: TargetFramework.Net70); comp.VerifyDiagnostics( // (2,13): error CS9035: Required member 'C.Prop1' must be set in the object initializer or attribute constructor. // var c = new C(); @@ -2442,6 +2458,88 @@ public class Derived : Base CompileAndVerify(comp).VerifyDiagnostics(); } + [Fact] + public void EnforcedRequiredMembers_Override_DiffersByModreq_NoneSet() + { + // Equivalent to + // class Base + // { + // public virtual required modopt(object) int Prop1 { get; set; } + // } + var @base = @" +.class public auto ansi beforefieldinit Base + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .field private int32 'k__BackingField' + + .method public hidebysig specialname newslot virtual + instance int32 get_Prop1 () cil managed + { + ldarg.0 + ldfld int32 Base::'k__BackingField' + ret + } + + .method public hidebysig specialname newslot virtual + instance void set_Prop1 ( + int32 'value' + ) cil managed + { + ldarg.0 + ldarg.1 + stfld int32 Base::'k__BackingField' + ret + } + + .method public hidebysig specialname rtspecialname + instance void .ctor () cil managed + { + .custom instance void [mscorlib]System.ObsoleteAttribute::.ctor(string, bool) = ( + 01 00 5f 43 6f 6e 73 74 72 75 63 74 6f 72 73 20 + 6f 66 20 74 79 70 65 73 20 77 69 74 68 20 72 65 + 71 75 69 72 65 64 20 6d 65 6d 62 65 72 73 20 61 + 72 65 20 6e 6f 74 20 73 75 70 70 6f 72 74 65 64 + 20 69 6e 20 74 68 69 73 20 76 65 72 73 69 6f 6e + 20 6f 66 20 79 6f 75 72 20 63 6f 6d 70 69 6c 65 + 72 2e 01 00 00 + ) + .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerFeatureRequiredAttribute::.ctor(string) = ( + 01 00 0f 52 65 71 75 69 72 65 64 4d 65 6d 62 65 + 72 73 00 00 + ) + ldarg.0 + call instance void [mscorlib]System.Object::.ctor() + ret + } + + .property instance int32 modopt([mscorlib]System.Object) Prop1() + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .get instance int32 Base::get_Prop1() + .set instance void Base::set_Prop1(int32) + } +}"; + + var code = @" +_ = new Derived() { Prop1 = 1 }; + +public class Derived : Base +{ + public override required int Prop1 { get; set; } +} +"; + + var baseRef = CompileIL(@base); + + var comp = CreateCompilation(code, new[] { baseRef }, targetFramework: TargetFramework.Net70); + CompileAndVerify(comp, verify: Verification.FailsPEVerify).VerifyDiagnostics(); + } + [Fact] public void EnforcedRequiredMembers_OverrideRetargeted_AllSet() { @@ -2508,28 +2606,118 @@ public class Derived : Base Assert.IsType(comp.GetTypeByMetadataName("Base")); } - [Fact] - public void EnforcedRequiredMembers_ShadowedInSource_01() + /// + /// Equivalent to + /// + /// public class Base + /// { + /// public required int P { get; set; } + /// } + /// public class Derived : Base + /// { + /// public new required int P { get; set; } + /// } + /// + /// + private const string ShadowingBaseAndDerivedIL = @" +.class public auto ansi Base + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .field private int32 _P + + .method public specialname rtspecialname + instance void .ctor () cil managed { - var vb = @" -Imports System.Runtime.CompilerServices - -Public Class Base - - Public Property P As Integer -End Class - - -Public Class Derived - Inherits Base - - Public Shadows Property P As Integer -End Class -"; + ldarg.0 + call instance void [mscorlib]System.Object::.ctor() + ret + } + + .method public specialname + instance int32 get_P () cil managed + { + IL_0000: ldarg.0 + IL_0001: ldfld int32 Base::_P + IL_0006: br.s IL_0008 + + IL_0008: ret + } + + .method public specialname + instance void set_P ( + int32 AutoPropertyValue + ) cil managed + { + ldarg.0 + ldarg.1 + stfld int32 Base::_P + ret + } + + .property instance int32 P() + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .get instance int32 Base::get_P() + .set instance void Base::set_P(int32) + } +} + +.class public auto ansi Derived + extends Base +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .field private int32 _P + + .method public specialname + instance int32 get_P () cil managed + { + IL_0000: ldarg.0 + IL_0001: ldfld int32 Derived::_P + IL_0006: br.s IL_0008 + + IL_0008: ret + } + + .method public specialname + instance void set_P ( + int32 AutoPropertyValue + ) cil managed + { + ldarg.0 + ldarg.1 + stfld int32 Derived::_P + ret + } + + .method public specialname rtspecialname + instance void .ctor () cil managed + { + nop + ldarg.0 + call instance void Base::.ctor() + ret + } - var vbComp = CreateVisualBasicCompilationWithRequiredMembers(vb); - CompileAndVerify(vbComp).VerifyDiagnostics(); + .property instance int32 P() + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .get instance int32 Derived::get_P() + .set instance void Derived::set_P(int32) + } +}"; + [Fact] + public void EnforcedRequiredMembers_ShadowedInSource_01() + { var c = @" _ = new Derived2(); _ = new Derived3(); @@ -2541,7 +2729,9 @@ public Derived2(int x) {} } class Derived3 : Derived { }"; - var comp = CreateCompilation(c, new[] { vbComp.EmitToImageReference() }); + var ilRef = CompileIL(ShadowingBaseAndDerivedIL); + + var comp = CreateCompilation(c, new[] { ilRef }, targetFramework: TargetFramework.Net70); comp.VerifyDiagnostics( // (7,12): error CS9038: The required members list for the base type 'Derived' is malformed and cannot be interpreted. To use this constructor, apply the 'SetsRequiredMembers' attribute. // public Derived2() {} @@ -2558,24 +2748,7 @@ class Derived3 : Derived { }"; [Fact] public void EnforcedRequiredMembers_ShadowedInSource_01_HasSetsRequiredMembers() { - var vb = @" -Imports System.Runtime.CompilerServices - -Public Class Base - - Public Property P As Integer -End Class - - -Public Class Derived - Inherits Base - - Public Shadows Property P As Integer -End Class -"; - - var vbComp = CreateVisualBasicCompilationWithRequiredMembers(vb); - CompileAndVerify(vbComp).VerifyDiagnostics(); + var ilRef = CompileIL(ShadowingBaseAndDerivedIL); var c = @" using System.Diagnostics.CodeAnalysis; @@ -2589,30 +2762,117 @@ public Derived2() {} public Derived2(int x) {} }"; - var comp = CreateCompilation(c, new[] { vbComp.EmitToImageReference() }); + var comp = CreateCompilation(c, new[] { ilRef }, targetFramework: TargetFramework.Net70); comp.VerifyDiagnostics(); } [Fact] public void EnforcedRequiredMembers_ShadowedInSource_02() { - var vb = @" -Imports System.Runtime.CompilerServices - -Public Class Base - - Public Property P As Integer -End Class - - -Public Class Derived - Inherits Base - Public Shadows Property P As Integer -End Class -"; + // Equivalent to + // public class Base + // { + // public required int P { get; set; } + // } + // [RequiredMember]public class Derived : Base + // { + // public new int P { get; set; } + // } + // + string il = @" +.class public auto ansi Base + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .field private int32 _P - var vbComp = CreateVisualBasicCompilationWithRequiredMembers(vb); - CompileAndVerify(vbComp).VerifyDiagnostics(); + .method public specialname rtspecialname + instance void .ctor () cil managed + { + ldarg.0 + call instance void [mscorlib]System.Object::.ctor() + ret + } + + .method public specialname + instance int32 get_P () cil managed + { + IL_0000: ldarg.0 + IL_0001: ldfld int32 Base::_P + IL_0006: br.s IL_0008 + + IL_0008: ret + } + + .method public specialname + instance void set_P ( + int32 AutoPropertyValue + ) cil managed + { + ldarg.0 + ldarg.1 + stfld int32 Base::_P + ret + } + + .property instance int32 P() + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .get instance int32 Base::get_P() + .set instance void Base::set_P(int32) + } +} + +.class public auto ansi Derived + extends Base +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .field private int32 _P + + .method public specialname + instance int32 get_P () cil managed + { + IL_0000: ldarg.0 + IL_0001: ldfld int32 Derived::_P + IL_0006: br.s IL_0008 + + IL_0008: ret + } + + .method public specialname + instance void set_P ( + int32 AutoPropertyValue + ) cil managed + { + ldarg.0 + ldarg.1 + stfld int32 Derived::_P + ret + } + + .method public specialname rtspecialname + instance void .ctor () cil managed + { + nop + ldarg.0 + call instance void Base::.ctor() + ret + } + + .property instance int32 P() + { + .get instance int32 Derived::get_P() + .set instance void Derived::set_P(int32) + } +}"; + + var ilRef = CompileIL(il); var c = @" _ = new Derived2(); @@ -2624,7 +2884,7 @@ public Derived2() {} } class Derived3 : Derived { }"; - var comp = CreateCompilation(c, new[] { vbComp.EmitToImageReference() }); + var comp = CreateCompilation(c, new[] { ilRef }, targetFramework: TargetFramework.Net70); comp.VerifyDiagnostics( // (7,12): error CS9038: The required members list for the base type 'Derived' is malformed and cannot be interpreted. To use this constructor, apply the 'SetsRequiredMembers' attribute. // public Derived2() {} @@ -2638,22 +2898,105 @@ class Derived3 : Derived { }"; [Fact] public void EnforcedRequiredMembers_ShadowedInSource_03() { - var vb = @" -Imports System.Runtime.CompilerServices - -Public Class Base - - Public Property P As Integer -End Class - -Public Class Derived - Inherits Base - Public Shadows Property P As Integer -End Class -"; + // Equivalent to + // public class Base + // { + // public required int P { get; set; } + // } + // public class Derived : Base + // { + // public new int P { get; set; } + // } + // + string il = @" +.class public auto ansi Base + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .field private int32 _P + + .method public specialname rtspecialname + instance void .ctor () cil managed + { + ldarg.0 + call instance void [mscorlib]System.Object::.ctor() + ret + } + + .method public specialname + instance int32 get_P () cil managed + { + IL_0000: ldarg.0 + IL_0001: ldfld int32 Base::_P + IL_0006: br.s IL_0008 + + IL_0008: ret + } + + .method public specialname + instance void set_P ( + int32 AutoPropertyValue + ) cil managed + { + ldarg.0 + ldarg.1 + stfld int32 Base::_P + ret + } + + .property instance int32 P() + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .get instance int32 Base::get_P() + .set instance void Base::set_P(int32) + } +} + +.class public auto ansi Derived + extends Base +{ + .field private int32 _P + + .method public specialname + instance int32 get_P () cil managed + { + IL_0000: ldarg.0 + IL_0001: ldfld int32 Derived::_P + IL_0006: br.s IL_0008 + + IL_0008: ret + } + + .method public specialname + instance void set_P ( + int32 AutoPropertyValue + ) cil managed + { + ldarg.0 + ldarg.1 + stfld int32 Derived::_P + ret + } + + .method public specialname rtspecialname + instance void .ctor () cil managed + { + nop + ldarg.0 + call instance void Base::.ctor() + ret + } - var vbComp = CreateVisualBasicCompilationWithRequiredMembers(vb); - CompileAndVerify(vbComp).VerifyDiagnostics(); + .property instance int32 P() + { + .get instance int32 Derived::get_P() + .set instance void Derived::set_P(int32) + } +}"; var c = @" _ = new Derived2(); @@ -2665,7 +3008,9 @@ public Derived2() {} } class Derived3 : Derived { }"; - var comp = CreateCompilation(c, new[] { vbComp.EmitToImageReference() }); + var ilRef = CompileIL(il); + + var comp = CreateCompilation(c, new[] { ilRef }, targetFramework: TargetFramework.Net70); comp.VerifyDiagnostics( // (7,12): error CS9038: The required members list for the base type 'Derived' is malformed and cannot be interpreted. To use this constructor, apply the 'SetsRequiredMembers' attribute. // public Derived2() {} @@ -3071,38 +3416,133 @@ public DerivedDerived1() [Fact] public void EnforcedRequiredMembers_ShadowedFromMetadata_01() { - var vb = @" -Imports System.Diagnostics.CodeAnalysis -Imports System.Runtime.CompilerServices - -Public Class Base - - Public Property P As Integer -End Class - - -Public Class Derived - Inherits Base - - Public Shadows Property P As Integer - - Public Sub New() - End Sub - - - Public Sub New(unused As Integer) - End Sub -End Class -"; + // Equivalent to + // public class Base + // { + // public required int P { get; set; } + // } + // public class Derived : Base + // { + // public new required int P { get; set; } + // public Derived() {} + // [SetsRequiredMembers] public Derived(int unused) {} + // } + var il = @" +.class public auto ansi Base + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .field private int32 _P + + .method public specialname rtspecialname + instance void .ctor () cil managed + { + ldarg.0 + call instance void [mscorlib]System.Object::.ctor() + ret + } - var vbComp = CreateVisualBasicCompilationWithRequiredMembers(vb); - CompileAndVerify(vbComp).VerifyDiagnostics(); + .method public specialname + instance int32 get_P () cil managed + { + IL_0000: ldarg.0 + IL_0001: ldfld int32 Base::_P + IL_0006: br.s IL_0008 + + IL_0008: ret + } + + .method public specialname + instance void set_P ( + int32 AutoPropertyValue + ) cil managed + { + ldarg.0 + ldarg.1 + stfld int32 Base::_P + ret + } + + .property instance int32 P() + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .get instance int32 Base::get_P() + .set instance void Base::set_P(int32) + } +} + +.class public auto ansi Derived + extends Base +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .field private int32 _P + + .method public specialname + instance int32 get_P () cil managed + { + IL_0000: ldarg.0 + IL_0001: ldfld int32 Derived::_P + IL_0006: br.s IL_0008 + + IL_0008: ret + } + + .method public specialname + instance void set_P ( + int32 AutoPropertyValue + ) cil managed + { + ldarg.0 + ldarg.1 + stfld int32 Derived::_P + ret + } + + .method public specialname rtspecialname + instance void .ctor () cil managed + { + nop + ldarg.0 + call instance void Base::.ctor() + ret + } + + .method public specialname rtspecialname + instance void .ctor ( + int32 'unused' + ) cil managed + { + .custom instance void [mscorlib]System.Diagnostics.CodeAnalysis.SetsRequiredMembersAttribute::.ctor() = ( + 01 00 00 00 + ) + ldarg.0 + call instance void Base::.ctor() + ret + } + + .property instance int32 P() + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .get instance int32 Derived::get_P() + .set instance void Derived::set_P(int32) + } +}"; + + var ilRef = CompileIL(il); var c = """ _ = new Derived(); _ = new Derived(1); """; - var comp = CreateCompilation(c, new[] { vbComp.EmitToImageReference() }); + var comp = CreateCompilation(c, new[] { ilRef }, targetFramework: TargetFramework.Net70); comp.VerifyDiagnostics( // (1,9): error CS9037: The required members list for 'Derived' is malformed and cannot be interpreted. // _ = new Derived(); @@ -3113,37 +3553,130 @@ End Class [Fact] public void EnforcedRequiredMembers_ShadowedFromMetadata_02() { - var vb = @" -Imports System.Diagnostics.CodeAnalysis -Imports System.Runtime.CompilerServices - -Public Class Base - - Public Property P As Integer -End Class - - -Public Class Derived - Inherits Base - Public Shadows Property P As Integer - - Public Sub New() - End Sub - - - Public Sub New(unused As Integer) - End Sub -End Class -"; + // Equivalent to + // public class Base + // { + // public required int P { get; set; } + // } + // [RequiredMember] public class Derived : Base + // { + // public new int P { get; set; } + // public Derived() {} + // [SetsRequiredMembers] public Derived(int unused) {} + // } + var il = @" +.class public auto ansi Base + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .field private int32 _P + + .method public specialname rtspecialname + instance void .ctor () cil managed + { + ldarg.0 + call instance void [mscorlib]System.Object::.ctor() + ret + } + + .method public specialname + instance int32 get_P () cil managed + { + IL_0000: ldarg.0 + IL_0001: ldfld int32 Base::_P + IL_0006: br.s IL_0008 + + IL_0008: ret + } - var vbComp = CreateVisualBasicCompilationWithRequiredMembers(vb); - CompileAndVerify(vbComp).VerifyDiagnostics(); + .method public specialname + instance void set_P ( + int32 AutoPropertyValue + ) cil managed + { + ldarg.0 + ldarg.1 + stfld int32 Base::_P + ret + } + + .property instance int32 P() + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .get instance int32 Base::get_P() + .set instance void Base::set_P(int32) + } +} + +.class public auto ansi Derived + extends Base +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .field private int32 _P + + .method public specialname + instance int32 get_P () cil managed + { + IL_0000: ldarg.0 + IL_0001: ldfld int32 Derived::_P + IL_0006: br.s IL_0008 + + IL_0008: ret + } + + .method public specialname + instance void set_P ( + int32 AutoPropertyValue + ) cil managed + { + ldarg.0 + ldarg.1 + stfld int32 Derived::_P + ret + } + + .method public specialname rtspecialname + instance void .ctor () cil managed + { + nop + ldarg.0 + call instance void Base::.ctor() + ret + } + + .method public specialname rtspecialname + instance void .ctor ( + int32 'unused' + ) cil managed + { + .custom instance void [mscorlib]System.Diagnostics.CodeAnalysis.SetsRequiredMembersAttribute::.ctor() = ( + 01 00 00 00 + ) + ldarg.0 + call instance void Base::.ctor() + ret + } + + .property instance int32 P() + { + .get instance int32 Derived::get_P() + .set instance void Derived::set_P(int32) + } +}"; + + var ilRef = CompileIL(il); var c = """ _ = new Derived(); _ = new Derived(1); """; - var comp = CreateCompilation(c, new[] { vbComp.EmitToImageReference() }); + var comp = CreateCompilation(c, new[] { ilRef }, targetFramework: TargetFramework.Net70); comp.VerifyDiagnostics( // (1,9): error CS9037: The required members list for 'Derived' is malformed and cannot be interpreted. // _ = new Derived(); @@ -3154,36 +3687,127 @@ End Class [Fact] public void EnforcedRequiredMembers_ShadowedFromMetadata_03() { - var vb = @" -Imports System.Diagnostics.CodeAnalysis -Imports System.Runtime.CompilerServices - -Public Class Base - - Public Property P As Integer -End Class - -Public Class Derived - Inherits Base - Public Shadows Property P As Integer - - Public Sub New() - End Sub - - - Public Sub New(unused As Integer) - End Sub -End Class -"; + // Equivalent to + // public class Base + // { + // public required int P { get; set; } + // } + // public class Derived : Base + // { + // public new int P { get; set; } + // public Derived() {} + // [SetsRequiredMembers] public Derived(int unused) {} + // } + var il = @" +.class public auto ansi Base + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .field private int32 _P + + .method public specialname rtspecialname + instance void .ctor () cil managed + { + ldarg.0 + call instance void [mscorlib]System.Object::.ctor() + ret + } + + .method public specialname + instance int32 get_P () cil managed + { + IL_0000: ldarg.0 + IL_0001: ldfld int32 Base::_P + IL_0006: br.s IL_0008 + + IL_0008: ret + } + + .method public specialname + instance void set_P ( + int32 AutoPropertyValue + ) cil managed + { + ldarg.0 + ldarg.1 + stfld int32 Base::_P + ret + } + + .property instance int32 P() + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .get instance int32 Base::get_P() + .set instance void Base::set_P(int32) + } +} + +.class public auto ansi Derived + extends Base +{ + .field private int32 _P + + .method public specialname + instance int32 get_P () cil managed + { + IL_0000: ldarg.0 + IL_0001: ldfld int32 Derived::_P + IL_0006: br.s IL_0008 + + IL_0008: ret + } + + .method public specialname + instance void set_P ( + int32 AutoPropertyValue + ) cil managed + { + ldarg.0 + ldarg.1 + stfld int32 Derived::_P + ret + } + + .method public specialname rtspecialname + instance void .ctor () cil managed + { + nop + ldarg.0 + call instance void Base::.ctor() + ret + } + + .method public specialname rtspecialname + instance void .ctor ( + int32 'unused' + ) cil managed + { + .custom instance void [mscorlib]System.Diagnostics.CodeAnalysis.SetsRequiredMembersAttribute::.ctor() = ( + 01 00 00 00 + ) + ldarg.0 + call instance void Base::.ctor() + ret + } + + .property instance int32 P() + { + .get instance int32 Derived::get_P() + .set instance void Derived::set_P(int32) + } +}"; - var vbComp = CreateVisualBasicCompilationWithRequiredMembers(vb); - CompileAndVerify(vbComp).VerifyDiagnostics(); + var ilRef = CompileIL(il); var c = """ _ = new Derived(); _ = new Derived(1); """; - var comp = CreateCompilation(c, new[] { vbComp.EmitToImageReference() }); + var comp = CreateCompilation(c, new[] { ilRef }, targetFramework: TargetFramework.Net70); comp.VerifyDiagnostics( // (1,9): error CS9037: The required members list for 'Derived' is malformed and cannot be interpreted. // _ = new Derived(); diff --git a/src/Compilers/Test/Core/CommonTestBase.cs b/src/Compilers/Test/Core/CommonTestBase.cs index 8f104ed92ad31..20fa9ae7b4c42 100644 --- a/src/Compilers/Test/Core/CommonTestBase.cs +++ b/src/Compilers/Test/Core/CommonTestBase.cs @@ -12,6 +12,7 @@ using System.Text; using System.Xml.Linq; using Microsoft.CodeAnalysis.CodeGen; +using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Operations; @@ -325,9 +326,33 @@ protected CSharp.CSharpCompilation CreateCSharpCompilation( IEnumerable referencedAssemblies = null, IEnumerable referencedCompilations = null) { + return CreateCSharpCompilation(assemblyName, assemblyIdentity: null, code, parseOptions, compilationOptions, referencedAssemblies, referencedCompilations); + } + + protected CSharp.CSharpCompilation CreateCSharpCompilation( + AssemblyIdentity assemblyIdentity, + string code, + CSharp.CSharpParseOptions parseOptions = null, + CSharp.CSharpCompilationOptions compilationOptions = null, + IEnumerable referencedAssemblies = null, + IEnumerable referencedCompilations = null) + { + return CreateCSharpCompilation(assemblyName: null, assemblyIdentity, code, parseOptions, compilationOptions, referencedAssemblies, referencedCompilations); + } + + private CSharp.CSharpCompilation CreateCSharpCompilation( + string assemblyName, + AssemblyIdentity assemblyIdentity, + string code, + CSharp.CSharpParseOptions parseOptions = null, + CSharp.CSharpCompilationOptions compilationOptions = null, + IEnumerable referencedAssemblies = null, + IEnumerable referencedCompilations = null) + { + Debug.Assert(assemblyName == null || assemblyIdentity == null || assemblyIdentity.Name == assemblyName); if (assemblyName == null) { - assemblyName = GetUniqueName(); + assemblyName = assemblyIdentity?.Name ?? GetUniqueName(); } if (parseOptions == null) @@ -359,7 +384,14 @@ protected CSharp.CSharpCompilation CreateCSharpCompilation( var tree = CSharp.SyntaxFactory.ParseSyntaxTree(SourceText.From(code, encoding: null, SourceHashAlgorithms.Default), options: parseOptions); - return CSharp.CSharpCompilation.Create(assemblyName, new[] { tree }, references, compilationOptions); + var compilation = CSharp.CSharpCompilation.Create(assemblyName, new[] { tree }, references, compilationOptions); + + if (assemblyIdentity != null) + { + ((SourceAssemblySymbol)compilation.Assembly).lazyAssemblyIdentity = assemblyIdentity; + } + + return compilation; } protected VisualBasic.VisualBasicCompilation CreateVisualBasicCompilation( diff --git a/src/Compilers/Test/Utilities/VisualBasic/CompilationTestUtils.vb b/src/Compilers/Test/Utilities/VisualBasic/CompilationTestUtils.vb index a07cdc63ee720..a39b2dd93158a 100644 --- a/src/Compilers/Test/Utilities/VisualBasic/CompilationTestUtils.vb +++ b/src/Compilers/Test/Utilities/VisualBasic/CompilationTestUtils.vb @@ -947,7 +947,7 @@ Friend Module CompilationUtils actualLine = actualReader.ReadLine() End While - Assert.Equal(expectedPooledBuilder.ToStringAndFree(), actualPooledBuilder.ToStringAndFree()) + AssertEx.Equal(expectedPooledBuilder.ToStringAndFree(), actualPooledBuilder.ToStringAndFree()) End Sub ' There are certain cases where multiple distinct errors are diff --git a/src/Compilers/Test/Utilities/VisualBasic/MockSymbols.vb b/src/Compilers/Test/Utilities/VisualBasic/MockSymbols.vb index 67f9358bac5a2..03c4231d9650d 100644 --- a/src/Compilers/Test/Utilities/VisualBasic/MockSymbols.vb +++ b/src/Compilers/Test/Utilities/VisualBasic/MockSymbols.vb @@ -378,6 +378,12 @@ Friend Class MockNamedTypeSymbol Friend NotOverridable Overrides Function GetSynthesizedWithEventsOverrides() As IEnumerable(Of PropertySymbol) Return SpecializedCollections.EmptyEnumerable(Of PropertySymbol)() End Function + + Friend Overrides ReadOnly Property HasAnyDeclaredRequiredMembers As Boolean + Get + Return False + End Get + End Property End Class Friend Class MockMethodSymbol @@ -637,6 +643,12 @@ Friend Class MockMethodSymbol Friend Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer Throw ExceptionUtilities.Unreachable End Function + + Friend Overrides ReadOnly Property HasSetsRequiredMembers As Boolean + Get + Return False + End Get + End Property End Class Friend Class MockModuleSymbol diff --git a/src/Compilers/VisualBasic/Portable/Binding/Binder_Attributes.vb b/src/Compilers/VisualBasic/Portable/Binding/Binder_Attributes.vb index b6a8c5334f762..fa54ad39218b9 100644 --- a/src/Compilers/VisualBasic/Portable/Binding/Binder_Attributes.vb +++ b/src/Compilers/VisualBasic/Portable/Binding/Binder_Attributes.vb @@ -347,6 +347,8 @@ Namespace Microsoft.CodeAnalysis.VisualBasic End If Next + CheckRequiredMembersInObjectInitializer(methodSym, methodSym.ContainingType, boundNamedArguments, node.Name, diagnostics) + If Not errorsReported Then ' There should not be any used temporaries or copy back expressions because arguments must ' be constants and they cannot be passed byref. diff --git a/src/Compilers/VisualBasic/Portable/Binding/Binder_ObjectInitializer.vb b/src/Compilers/VisualBasic/Portable/Binding/Binder_ObjectInitializer.vb index 3a49c58742927..04e5f17926272 100644 --- a/src/Compilers/VisualBasic/Portable/Binding/Binder_ObjectInitializer.vb +++ b/src/Compilers/VisualBasic/Portable/Binding/Binder_ObjectInitializer.vb @@ -90,7 +90,8 @@ Namespace Microsoft.CodeAnalysis.VisualBasic ' NOTE: in case the structure has a constructor with all optional parameters ' we don't catch it here; this matches Dev10 behavior - Dim ctors = DirectCast(type0, NamedTypeSymbol).InstanceConstructors + Dim namedType = DirectCast(type0, NamedTypeSymbol) + Dim ctors = namedType.InstanceConstructors If Not ctors.IsEmpty Then For Each constructor In ctors @@ -113,6 +114,13 @@ Namespace Microsoft.CodeAnalysis.VisualBasic ' Emitter will just emit 'initobj' instead of constructor call instead ' create a simplified object creation expression + Dim initializerOpt As BoundObjectInitializerExpressionBase = BindObjectCollectionOrMemberInitializer(node, + type0, + asNewVariablePlaceholderOpt, + diagnostics) + + CheckRequiredMembersInObjectInitializer(constructorSymbol, namedType, If(initializerOpt?.Initializers, ImmutableArray(Of BoundExpression).Empty), typeNode, diagnostics) + Return New BoundObjectCreationExpression( node, constructorSymbol, @@ -123,10 +131,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic QualificationKind.QualifiedViaTypeName)), arguments:=ImmutableArray(Of BoundExpression).Empty, defaultArguments:=BitVector.Null, - BindObjectCollectionOrMemberInitializer(node, - type0, - asNewVariablePlaceholderOpt, - diagnostics), + initializerOpt, type0) End If @@ -491,8 +496,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic children.ToImmutableAndFree(), type0, hasErrors:=True) Else + Dim constructorSymbol As MethodSymbol = DirectCast(methodResult.Candidate.UnderlyingSymbol, MethodSymbol) + + CheckRequiredMembersInObjectInitializer(constructorSymbol, constructorSymbol.ContainingType, If(objectInitializerExpressionOpt?.Initializers, ImmutableArray(Of BoundExpression).Empty), typeNode, diagnostics) + resultExpression = New BoundObjectCreationExpression(node, - DirectCast(methodResult.Candidate.UnderlyingSymbol, MethodSymbol), + constructorSymbol, constructorsGroup, boundArguments, argumentInfo.DefaultArguments, @@ -508,6 +517,66 @@ Namespace Microsoft.CodeAnalysis.VisualBasic Return resultExpression End Function + Friend Shared Sub CheckRequiredMembersInObjectInitializer( + constructor As MethodSymbol, + containingType As NamedTypeSymbol, + initializers As ImmutableArray(Of BoundExpression), + creationSyntax As SyntaxNode, + diagnostics As BindingDiagnosticBag) + + ' The only time constructor will be null is if we're trying to invoke a parameterless struct ctor, and it's not accessible (such as being protected). + Debug.Assert((constructor IsNot Nothing AndAlso ReferenceEquals(constructor.ContainingType, containingType)) OrElse containingType.IsStructureType()) + + If constructor IsNot Nothing AndAlso constructor.HasSetsRequiredMembers Then + Return + End If + + If containingType.HasRequiredMembersError Then + ' A use-site diagnostic will be reported on the use, so we don't need to do any more checking here. + Return + End If + + Dim requiredMembers = containingType.AllRequiredMembers + + If requiredMembers.Count = 0 Then + Return + End If + + Dim requiredMembersBuilder = requiredMembers.ToBuilder() + + If Not initializers.IsDefaultOrEmpty Then + For Each initializer In initializers + Dim assignmentOperator = TryCast(initializer, BoundAssignmentOperator) + If assignmentOperator Is Nothing Then + Continue For + End If + + Dim memberSymbol As Symbol = If( + DirectCast(TryCast(assignmentOperator.Left, BoundPropertyAccess)?.PropertySymbol, Symbol), + TryCast(assignmentOperator.Left, BoundFieldAccess)?.FieldSymbol) + + If memberSymbol Is Nothing Then + Continue For + End If + + Dim requiredMember As Symbol = Nothing + If Not requiredMembersBuilder.TryGetValue(memberSymbol.Name, requiredMember) Then + Continue For + End If + + If Not memberSymbol.Equals(requiredMember, TypeCompareKind.AllIgnoreOptionsForVB) Then + Continue For + End If + + requiredMembersBuilder.Remove(memberSymbol.Name) + Next + End If + + For Each kvp In requiredMembersBuilder + diagnostics.Add(ERRID.ERR_RequiredMemberMustBeSet, creationSyntax.Location, kvp.Value) + Next + End Sub + Private Function BindNoPiaObjectCreationExpression( node As SyntaxNode, [interface] As TypeSymbol, diff --git a/src/Compilers/VisualBasic/Portable/Binding/Binder_XmlLiterals.vb b/src/Compilers/VisualBasic/Portable/Binding/Binder_XmlLiterals.vb index c4b652f056ce8..d7bbfeb39bdfb 100644 --- a/src/Compilers/VisualBasic/Portable/Binding/Binder_XmlLiterals.vb +++ b/src/Compilers/VisualBasic/Portable/Binding/Binder_XmlLiterals.vb @@ -1713,6 +1713,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic End Get End Property + Public Overrides ReadOnly Property IsRequired As Boolean + Get + Return False + End Get + End Property + Private NotInheritable Class ReducedExtensionAccessorSymbol Inherits MethodSymbol @@ -1987,6 +1993,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic Friend Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer Throw ExceptionUtilities.Unreachable End Function + + Friend Overrides ReadOnly Property HasSetsRequiredMembers As Boolean + Get + Return False + End Get + End Property End Class Private NotInheritable Class ReducedAccessorParameterSymbol diff --git a/src/Compilers/VisualBasic/Portable/Errors/ErrorFacts.vb b/src/Compilers/VisualBasic/Portable/Errors/ErrorFacts.vb index b2c86e6decfa5..b06e4c7c71ce4 100644 --- a/src/Compilers/VisualBasic/Portable/Errors/ErrorFacts.vb +++ b/src/Compilers/VisualBasic/Portable/Errors/ErrorFacts.vb @@ -1357,6 +1357,11 @@ Namespace Microsoft.CodeAnalysis.VisualBasic ERRID.ERR_StdInOptionProvidedButConsoleInputIsNotRedirected, ERRID.ERR_UnsupportedCompilerFeature, ERRID.ERR_DoNotUseCompilerFeatureRequired, + ERRID.ERR_RequiredMemberMustBeSet, + ERRID.ERR_CannotInheritFromTypeWithRequiredMembers, + ERRID.ERR_RequiredMembersInvalid, + ERRID.ERR_NewConstraintCannotHaveRequiredMembers, + ERRID.ERR_DoNotUseRequiredMember, ERRID.ERR_NextAvailable, ERRID.WRN_UseOfObsoleteSymbol2, ERRID.WRN_InvalidOverrideDueToTupleNames2, diff --git a/src/Compilers/VisualBasic/Portable/Errors/Errors.vb b/src/Compilers/VisualBasic/Portable/Errors/Errors.vb index 74959580a6ffb..660b3233e63a8 100644 --- a/src/Compilers/VisualBasic/Portable/Errors/Errors.vb +++ b/src/Compilers/VisualBasic/Portable/Errors/Errors.vb @@ -1767,7 +1767,13 @@ Namespace Microsoft.CodeAnalysis.VisualBasic ERR_UnsupportedCompilerFeature = 37319 ERR_DoNotUseCompilerFeatureRequired = 37320 - ERR_NextAvailable = 37321 + ERR_RequiredMemberMustBeSet = 37321 + ERR_CannotInheritFromTypeWithRequiredMembers = 37322 + ERR_RequiredMembersInvalid = 37323 + ERR_NewConstraintCannotHaveRequiredMembers = 37324 + ERR_DoNotUseRequiredMember = 37325 + + ERR_NextAvailable = 37326 '// WARNINGS BEGIN HERE WRN_UseOfObsoleteSymbol2 = 40000 diff --git a/src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_TupleLiteralExpression.vb b/src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_TupleLiteralExpression.vb index 19fa112e96043..d525a88cef3b0 100644 --- a/src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_TupleLiteralExpression.vb +++ b/src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_TupleLiteralExpression.vb @@ -62,12 +62,15 @@ Namespace Microsoft.CodeAnalysis.VisualBasic Dim smallestConstructor As MethodSymbol = smallestCtor.AsMember(smallestType) Dim currentCreation As BoundObjectCreationExpression = New BoundObjectCreationExpression(syntax, smallestConstructor, smallestCtorArguments, initializerOpt:=Nothing, type:=smallestType) + Binder.CheckRequiredMembersInObjectInitializer(smallestConstructor, smallestType, initializers:=ImmutableArray(Of BoundExpression).Empty, syntax, _diagnostics) + If underlyingTupleTypeChain.Count > 0 Then Dim tuple8Type As NamedTypeSymbol = underlyingTupleTypeChain.Peek() Dim tuple8Ctor As MethodSymbol = DirectCast(TupleTypeSymbol.GetWellKnownMemberInType(tuple8Type.OriginalDefinition, TupleTypeSymbol.GetTupleCtor(TupleTypeSymbol.RestPosition), _diagnostics, syntax), MethodSymbol) + If tuple8Ctor Is Nothing Then Return New BoundBadExpression( syntax, @@ -78,6 +81,8 @@ Namespace Microsoft.CodeAnalysis.VisualBasic hasErrors:=True) End If + Binder.CheckRequiredMembersInObjectInitializer(tuple8Ctor, tuple8Ctor.ContainingType, initializers:=ImmutableArray(Of BoundExpression).Empty, syntax, _diagnostics) + ' make successively larger creation expressions containing the previous one Do Dim ctorArguments As ImmutableArray(Of BoundExpression) = ImmutableArray.Create(rewrittenArguments, diff --git a/src/Compilers/VisualBasic/Portable/Lowering/StateMachineRewriter/SynthesizedContainer.vb b/src/Compilers/VisualBasic/Portable/Lowering/StateMachineRewriter/SynthesizedContainer.vb index 33c4331f7713c..7c75699b163bd 100644 --- a/src/Compilers/VisualBasic/Portable/Lowering/StateMachineRewriter/SynthesizedContainer.vb +++ b/src/Compilers/VisualBasic/Portable/Lowering/StateMachineRewriter/SynthesizedContainer.vb @@ -321,5 +321,11 @@ Namespace Microsoft.CodeAnalysis.VisualBasic Friend NotOverridable Overrides Function GetSynthesizedWithEventsOverrides() As IEnumerable(Of PropertySymbol) Return SpecializedCollections.EmptyEnumerable(Of PropertySymbol)() End Function + + Friend NotOverridable Overrides ReadOnly Property HasAnyDeclaredRequiredMembers As Boolean + Get + Return False + End Get + End Property End Class End Namespace diff --git a/src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/PublicSymbols/AnonymousTypeOrDelegatePublicSymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/PublicSymbols/AnonymousTypeOrDelegatePublicSymbol.vb index 367ce7090acb3..32e56f8a53c3f 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/PublicSymbols/AnonymousTypeOrDelegatePublicSymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/PublicSymbols/AnonymousTypeOrDelegatePublicSymbol.vb @@ -328,7 +328,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Public NotOverridable Overrides Function GetHashCode() As Integer Return Hash.Combine(Me.TypeDescriptor.GetHashCode(), TypeKind) End Function - End Class + Friend NotOverridable Overrides ReadOnly Property HasAnyDeclaredRequiredMembers As Boolean + Get + Return False + End Get + End Property + End Class End Class End Namespace diff --git a/src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousTypeOrDelegateTemplateSymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousTypeOrDelegateTemplateSymbol.vb index c658de1b073d3..c0322f765a435 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousTypeOrDelegateTemplateSymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousTypeOrDelegateTemplateSymbol.vb @@ -380,6 +380,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend NotOverridable Overrides Function GetSynthesizedWithEventsOverrides() As IEnumerable(Of PropertySymbol) Return SpecializedCollections.EmptyEnumerable(Of PropertySymbol)() End Function + + Friend NotOverridable Overrides ReadOnly Property HasAnyDeclaredRequiredMembers As Boolean + Get + Return False + End Get + End Property End Class End Class diff --git a/src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousType_PropertySymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousType_PropertySymbol.vb index 56d1dc0e5655f..79941c6ffb76f 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousType_PropertySymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousType_PropertySymbol.vb @@ -217,6 +217,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Return False End Get End Property + + Public Overrides ReadOnly Property IsRequired As Boolean + Get + Return False + End Get + End Property End Class End Class diff --git a/src/Compilers/VisualBasic/Portable/Symbols/ConstraintsHelper.vb b/src/Compilers/VisualBasic/Portable/Symbols/ConstraintsHelper.vb index 4fa27b739b3a0..d7a8f078fc96a 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/ConstraintsHelper.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/ConstraintsHelper.vb @@ -903,8 +903,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Debug.Assert(typeParameter.HasConstructorConstraint) Select Case typeArgument.TypeKind - Case TypeKind.Enum, - TypeKind.Structure + Case TypeKind.Enum Return True Case TypeKind.TypeParameter @@ -919,28 +918,37 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols End If Case Else - If typeArgument.TypeKind = TypeKind.Class Then - Dim classType = DirectCast(typeArgument, NamedTypeSymbol) - - If HasPublicParameterlessConstructor(classType) Then - If classType.IsMustInherit Then - If diagnosticsBuilder IsNot Nothing Then - ' "Type argument '{0}' is declared 'MustInherit' and does not satisfy the 'New' constraint for type parameter '{1}'." - diagnosticsBuilder.Add(New TypeParameterDiagnosticInfo(typeParameter, ErrorFactory.ErrorInfo(ERRID.ERR_MustInheritForNewConstraint2, typeArgument, typeParameter))) - End If - Return False - Else - Return True - End If - End If + Dim isStructure As Boolean = typeArgument.TypeKind = TypeKind.Structure + + Dim constraintError = ConstructorConstraintError.NoPublicParameterlessConstructor + If typeArgument.TypeKind = TypeKind.Class OrElse isStructure Then + Dim namedType = DirectCast(typeArgument, NamedTypeSymbol) + constraintError = HasPublicParameterlessConstructor(namedType) + + If constraintError = ConstructorConstraintError.None AndAlso namedType.IsMustInherit Then + constraintError = ConstructorConstraintError.MustInheritType + End If End If If diagnosticsBuilder IsNot Nothing Then - ' "Type argument '{0}' must have a public parameterless instance constructor to satisfy the 'New' constraint for type parameter '{1}'." - diagnosticsBuilder.Add(New TypeParameterDiagnosticInfo(typeParameter, ErrorFactory.ErrorInfo(ERRID.ERR_NoSuitableNewForNewConstraint2, typeArgument, typeParameter))) + Select Case constraintError + Case ConstructorConstraintError.NoPublicParameterlessConstructor + ' "Type argument '{0}' must have a public parameterless instance constructor to satisfy the 'New' constraint for type parameter '{1}'." + diagnosticsBuilder.Add(New TypeParameterDiagnosticInfo(typeParameter, ErrorFactory.ErrorInfo(ERRID.ERR_NoSuitableNewForNewConstraint2, typeArgument, typeParameter))) + Case ConstructorConstraintError.MustInheritType + ' "Type argument '{0}' is declared 'MustInherit' and does not satisfy the 'New' constraint for type parameter '{1}'." + diagnosticsBuilder.Add(New TypeParameterDiagnosticInfo(typeParameter, ErrorFactory.ErrorInfo(ERRID.ERR_MustInheritForNewConstraint2, typeArgument, typeParameter))) + Case ConstructorConstraintError.HasRequiredMembers + ' '{2}' cannot satisfy the 'New' constraint on parameter '{1}' in the generic type or or method '{0}' because '{2}' has required members. + diagnosticsBuilder.Add(New TypeParameterDiagnosticInfo(typeParameter, ErrorFactory.ErrorInfo(ERRID.ERR_NewConstraintCannotHaveRequiredMembers, typeParameter.ContainingSymbol, typeParameter, typeArgument))) + Case ConstructorConstraintError.None + Case Else + Throw ExceptionUtilities.UnexpectedValue(constraintError) + End Select End If - Return False + + Return constraintError = ConstructorConstraintError.None End Select End Function @@ -1110,28 +1118,54 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Return New CompoundDiagnosticInfo(diagnostics) End Function + Public Enum ConstructorConstraintError + None + NoPublicParameterlessConstructor + MustInheritType + HasRequiredMembers + End Enum + ''' ''' Return true if the class type has a public parameterless constructor. ''' - Public Function HasPublicParameterlessConstructor(type As NamedTypeSymbol) As Boolean + Public Function HasPublicParameterlessConstructor(type As NamedTypeSymbol) As ConstructorConstraintError type = type.OriginalDefinition - Debug.Assert(type.TypeKind = TypeKind.Class) + Debug.Assert(type.TypeKind = TypeKind.Class OrElse type.TypeKind = TypeKind.Structure) - Dim sourceNamedType = TryCast(type, SourceNamedTypeSymbol) + Dim sourceClass = If(type.TypeKind = TypeKind.Class, TryCast(type, SourceNamedTypeSymbol), Nothing) - If sourceNamedType IsNot Nothing AndAlso Not sourceNamedType.MembersHaveBeenCreated Then + If sourceClass IsNot Nothing AndAlso Not sourceClass.MembersHaveBeenCreated Then ' When we are dealing with group classes and synthetic entry points, ' we can end up here while we are building the set of members for the type. ' Using InstanceConstructors property will send us into an infinite loop. - Return sourceNamedType.InferFromSyntaxIfClassWillHavePublicParameterlessConstructor() + If sourceClass.InferFromSyntaxIfClassWillHavePublicParameterlessConstructor() Then + Return ConstructorConstraintError.None + Else + Return ConstructorConstraintError.NoPublicParameterlessConstructor + End If End If + Dim hasRequiredMembers = type.AllRequiredMembers.Count > 0 OrElse type.HasRequiredMembersError + For Each constructor In type.InstanceConstructors If constructor.ParameterCount = 0 Then - Return constructor.DeclaredAccessibility = Accessibility.Public + If constructor.DeclaredAccessibility <> Accessibility.Public Then + Return ConstructorConstraintError.NoPublicParameterlessConstructor + ElseIf hasRequiredMembers AndAlso Not constructor.HasSetsRequiredMembers Then + Return ConstructorConstraintError.HasRequiredMembers + Else + Return ConstructorConstraintError.None + End If End If Next - Return False + + If Not type.TypeKind = TypeKind.Structure Then + Return ConstructorConstraintError.NoPublicParameterlessConstructor + ElseIf hasRequiredMembers Then + Return ConstructorConstraintError.HasRequiredMembers + Else + Return ConstructorConstraintError.None + End If End Function ''' diff --git a/src/Compilers/VisualBasic/Portable/Symbols/ErrorMethodSymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/ErrorMethodSymbol.vb index eb1c938ca0e71..f67b1a089169d 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/ErrorMethodSymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/ErrorMethodSymbol.vb @@ -262,6 +262,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer Throw ExceptionUtilities.Unreachable End Function + + Friend Overrides ReadOnly Property HasSetsRequiredMembers As Boolean + Get + Return False + End Get + End Property End Class End Namespace diff --git a/src/Compilers/VisualBasic/Portable/Symbols/ErrorTypeSymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/ErrorTypeSymbol.vb index 5ee99125b6e53..7d7b3a179883f 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/ErrorTypeSymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/ErrorTypeSymbol.vb @@ -406,6 +406,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Return SpecializedCollections.EmptyEnumerable(Of PropertySymbol)() End Function + Friend NotOverridable Overrides ReadOnly Property HasAnyDeclaredRequiredMembers As Boolean + Get + Return False + End Get + End Property + #Region "IErrorTypeSymbol members" Public ReadOnly Property IErrorTypeSymbol_CandidateSymbols As ImmutableArray(Of ISymbol) Implements IErrorTypeSymbol.CandidateSymbols diff --git a/src/Compilers/VisualBasic/Portable/Symbols/FieldSymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/FieldSymbol.vb index 1bb5312c11be2..9263073591ec4 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/FieldSymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/FieldSymbol.vb @@ -70,6 +70,8 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' Public MustOverride ReadOnly Property CustomModifiers As ImmutableArray(Of CustomModifier) + Public MustOverride ReadOnly Property IsRequired As Boolean + ''' ''' If this variable serves as a backing variable for an automatically generated ''' property or event, returns that property or event. @@ -419,7 +421,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Private ReadOnly Property IFieldSymbol_IsRequired As Boolean Implements IFieldSymbol.IsRequired Get - Return False + Return Me.IsRequired End Get End Property diff --git a/src/Compilers/VisualBasic/Portable/Symbols/Metadata/PE/PEFieldSymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/Metadata/PE/PEFieldSymbol.vb index 8f95e414d66a8..45e323c4448d9 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/Metadata/PE/PEFieldSymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/Metadata/PE/PEFieldSymbol.vb @@ -44,6 +44,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Private _lazyCustomAttributes As ImmutableArray(Of VisualBasicAttributeData) Private _lazyCachedUseSiteInfo As CachedUseSiteInfo(Of AssemblySymbol) = CachedUseSiteInfo(Of AssemblySymbol).Uninitialized ' Indicates unknown state. Private _lazyObsoleteAttributeData As ObsoleteAttributeData = ObsoleteAttributeData.Uninitialized + Private _lazyIsRequired As ThreeState = ThreeState.Unknown Friend Sub New( moduleSymbol As PEModuleSymbol, @@ -289,6 +290,16 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Return _lazyConstantValue End Function + Public Overrides ReadOnly Property IsRequired As Boolean + Get + If Not _lazyIsRequired.HasValue() Then + _lazyIsRequired = PEModule.HasAttribute(Handle, AttributeDescription.RequiredMemberAttribute).ToThreeState() + End If + + Return _lazyIsRequired.Value() + End Get + End Property + Public Overrides ReadOnly Property IsShared As Boolean Get Return (_flags And FieldAttributes.Static) <> 0 diff --git a/src/Compilers/VisualBasic/Portable/Symbols/Metadata/PE/PEMethodSymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/Metadata/PE/PEMethodSymbol.vb index 915e2b12b7e86..ef0fa8f4785ed 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/Metadata/PE/PEMethodSymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/Metadata/PE/PEMethodSymbol.vb @@ -51,7 +51,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Private Structure PackedFlags ' Flags are packed into a 32-bit int with the following layout: - ' | |j|i|h|g|f|e|d|c|b|aaaaa| + ' | l|k|j|i|h|g|f|e|d|c|b|aaaaa| ' ' a = method kind. 5 bits ' b = method kind populated. 1 bit @@ -63,6 +63,8 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE ' h = conditional attributes populated. 1 bit ' i = is init-only. 1 bit. ' j = is init-only populated. 1 bit. + ' k = has SetsRequiredMembers. 1 bit. + ' l = has SetsRequiredMembers populated. 1 bit. Private _bits As Integer @@ -77,6 +79,8 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Private Const s_isConditionalAttributePopulatedBit As Integer = 1 << 11 Private Const s_isInitOnlyBit = 1 << 12 Private Const s_isInitOnlyPopulatedBit = 1 << 13 + Private Const s_hasSetsRequiredMembersBit = 1 << 14 + Private Const s_hasSetsRequiredMembersPopulatedBit = 1 << 15 Public Property MethodKind As MethodKind Get @@ -142,6 +146,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE End Get End Property + Public Function TryGetHasSetsRequiredMembers(ByRef hasSetsRequiredMembers As Boolean) As Boolean + Dim bits = _bits + hasSetsRequiredMembers = (bits And s_hasSetsRequiredMembersBit) <> 0 + Return (bits And s_hasSetsRequiredMembersPopulatedBit) <> 0 + End Function + Private Shared Function BitsAreUnsetOrSame(bits As Integer, mask As Integer) As Boolean Return (bits And mask) = 0 OrElse (bits And mask) = mask End Function @@ -180,6 +190,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Debug.Assert(BitsAreUnsetOrSame(_bits, bitsToSet)) ThreadSafeFlagOperations.Set(_bits, bitsToSet) End Sub + + Public Sub InitializeSetsRequiredMembers(hasSetsRequiredMembers As Boolean) + Dim bitsToSet = If(hasSetsRequiredMembers, s_hasSetsRequiredMembersBit, 0) Or s_hasSetsRequiredMembersPopulatedBit + Debug.Assert(BitsAreUnsetOrSame(_bits, bitsToSet)) + ThreadSafeFlagOperations.Set(_bits, bitsToSet) + End Sub End Structure ''' @@ -1144,6 +1160,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE DeriveCompilerFeatureRequiredUseSiteInfo(errorInfo) EnsureTypeParametersAreLoaded(errorInfo) CheckUnmanagedCallersOnly(errorInfo) + CheckRequiredMembersError(errorInfo) Return InitializeUseSiteInfo(useSiteInfo.AdjustDiagnosticInfo(errorInfo)) End If @@ -1173,7 +1190,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Dim containingModule = _containingType.ContainingPEModule Dim decoder As New MetadataDecoder(containingModule, Me) - errorInfo = DeriveCompilerFeatureRequiredAttributeDiagnostic(Me, DirectCast(containingModule, PEModuleSymbol), Handle, CompilerFeatureRequiredFeatures.None, decoder) + errorInfo = DeriveCompilerFeatureRequiredAttributeDiagnostic(Me, DirectCast(containingModule, PEModuleSymbol), Handle, CompilerFeatureRequiredFeatures.RequiredMembers, decoder) If errorInfo IsNot Nothing Then Return End If @@ -1200,6 +1217,17 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE errorInfo = _containingType.GetCompilerFeatureRequiredDiagnostic() End Sub + Private Sub CheckRequiredMembersError(ByRef errorInfo As DiagnosticInfo) + If errorInfo Is Nothing AndAlso + MethodKind = MethodKind.Constructor AndAlso + (Not HasSetsRequiredMembers) AndAlso + ContainingType.HasRequiredMembersError Then + + errorInfo = ErrorFactory.ErrorInfo(ERRID.ERR_RequiredMembersInvalid, ContainingType) + End If + + End Sub + Private Function InitializeUseSiteInfo(useSiteInfo As UseSiteInfo(Of AssemblySymbol)) As UseSiteInfo(Of AssemblySymbol) If _packedFlags.IsUseSiteDiagnosticPopulated Then Return GetCachedUseSiteInfo() @@ -1288,6 +1316,24 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Friend Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer Throw ExceptionUtilities.Unreachable End Function + + Friend Overrides ReadOnly Property HasSetsRequiredMembers As Boolean + Get + If MethodKind <> MethodKind.Constructor Then + Return False + End If + + Dim hasSetsRequiredMembersValue As Boolean = False + If _packedFlags.TryGetHasSetsRequiredMembers(hasSetsRequiredMembersValue) Then + Return hasSetsRequiredMembersValue + End If + + hasSetsRequiredMembersValue = DirectCast(ContainingModule, PEModuleSymbol).Module.HasAttribute(Handle, AttributeDescription.SetsRequiredMembersAttribute) + _packedFlags.InitializeSetsRequiredMembers(hasSetsRequiredMembersValue) + + Return hasSetsRequiredMembersValue + End Get + End Property End Class End Namespace diff --git a/src/Compilers/VisualBasic/Portable/Symbols/Metadata/PE/PENamedTypeSymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/Metadata/PE/PENamedTypeSymbol.vb index a19d27a9d1806..18cd55d9a2149 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/Metadata/PE/PENamedTypeSymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/Metadata/PE/PENamedTypeSymbol.vb @@ -1556,6 +1556,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Friend NotOverridable Overrides Function GetSynthesizedWithEventsOverrides() As IEnumerable(Of PropertySymbol) Return SpecializedCollections.EmptyEnumerable(Of PropertySymbol)() End Function + + Friend Overrides ReadOnly Property HasAnyDeclaredRequiredMembers As Boolean + Get + Return ContainingPEModule.Module.HasAttribute(Handle, AttributeDescription.RequiredMemberAttribute) + End Get + End Property End Class End Namespace diff --git a/src/Compilers/VisualBasic/Portable/Symbols/Metadata/PE/PEPropertySymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/Metadata/PE/PEPropertySymbol.vb index 69c8626504d6f..e25261d5bdda6 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/Metadata/PE/PEPropertySymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/Metadata/PE/PEPropertySymbol.vb @@ -44,6 +44,8 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Private _lazyDeclaredAccessibility As Integer = s_unsetAccessibility Private _lazyObsoleteAttributeData As ObsoleteAttributeData = ObsoleteAttributeData.Uninitialized + Private _lazyIsRequired As ThreeState = ThreeState.Unknown + Friend Shared Function Create( moduleSymbol As PEModuleSymbol, containingType As PENamedTypeSymbol, @@ -610,6 +612,16 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE End Get End Property + Public Overrides ReadOnly Property IsRequired As Boolean + Get + If Not _lazyIsRequired.HasValue() Then + _lazyIsRequired = _containingType.ContainingPEModule.Module.HasAttribute(Handle, AttributeDescription.RequiredMemberAttribute).ToThreeState() + End If + + Return _lazyIsRequired.Value() + End Get + End Property + Private NotInheritable Class PEPropertySymbolWithCustomModifiers Inherits PEPropertySymbol diff --git a/src/Compilers/VisualBasic/Portable/Symbols/MethodSymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/MethodSymbol.vb index 4ac60fce32d45..5fdb64d88c6dc 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/MethodSymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/MethodSymbol.vb @@ -869,6 +869,8 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols End Get End Property + Friend MustOverride ReadOnly Property HasSetsRequiredMembers As Boolean + #Region "IMethodSymbol" Private ReadOnly Property IMethodSymbol_Arity As Integer Implements IMethodSymbol.Arity diff --git a/src/Compilers/VisualBasic/Portable/Symbols/NamedTypeSymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/NamedTypeSymbol.vb index 5679a6a081366..cdbdf16e05fc9 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/NamedTypeSymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/NamedTypeSymbol.vb @@ -13,6 +13,7 @@ Imports Microsoft.CodeAnalysis.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind +Imports Microsoft.CodeAnalysis.Collections Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols @@ -23,6 +24,15 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Inherits TypeSymbol Implements INamedTypeSymbol, INamedTypeSymbolInternal + Protected Shared ReadOnly s_requiredMembersErrorSentinel As ImmutableSegmentedDictionary(Of String, Symbol) = ImmutableSegmentedDictionary(Of String, Symbol).Empty.Add("", Nothing) + + ''' + ''' if uninitialized. if there are errors. + ''' if there are no required members. Otherwise, + ''' the required members. + ''' + Private _lazyRequiredMembers As ImmutableSegmentedDictionary(Of String, Symbol) = Nothing + ' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ' Changes to the public interface of this class should remain synchronized with the C# version. ' Do not make any changes to the public interface without making the corresponding change @@ -1089,6 +1099,104 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' Friend MustOverride Function GetSynthesizedWithEventsOverrides() As IEnumerable(Of PropertySymbol) + ''' + ''' Gets all of the required members from this type and all base types. This will be a set of the most derived overrides. If is true, + ''' this will be . + ''' + Friend ReadOnly Property AllRequiredMembers As ImmutableSegmentedDictionary(Of String, Symbol) + Get + EnsureRequiredMembersCalculated() + Debug.Assert(Not _lazyRequiredMembers.IsDefault) + Return If(_lazyRequiredMembers = s_requiredMembersErrorSentinel, ImmutableSegmentedDictionary(Of String, Symbol).Empty, _lazyRequiredMembers) + End Get + End Property + + ''' + ''' True if this or any base type has a required members error, and constructors should be blocked unless attributed with SetsRequiredMembersAttribute. When this is + ''' true, will be + ''' + Friend ReadOnly Property HasRequiredMembersError As Boolean + Get + EnsureRequiredMembersCalculated() + Debug.Assert(Not _lazyRequiredMembers.IsDefault) + Return _lazyRequiredMembers = s_requiredMembersErrorSentinel + End Get + End Property + + Friend MustOverride ReadOnly Property HasAnyDeclaredRequiredMembers As Boolean + + Private Sub EnsureRequiredMembersCalculated() + Dim lazyRequiredMembers As ImmutableSegmentedDictionary(Of String, Symbol) = _lazyRequiredMembers + + If Not lazyRequiredMembers.IsDefault Then + Return + End If + + Dim requiredMembersBuilder As ImmutableSegmentedDictionary(Of String, Symbol).Builder = Nothing + Dim success = TryCalculateRequiredMembers(requiredMembersBuilder) + + Dim requiredMembers = If(success, + If(requiredMembersBuilder?.ToImmutable(), If(BaseTypeNoUseSiteDiagnostics?.AllRequiredMembers, ImmutableSegmentedDictionary(Of String, Symbol).Empty)), + s_requiredMembersErrorSentinel) + + RoslynImmutableInterlocked.InterlockedInitialize(_lazyRequiredMembers, requiredMembers) + End Sub + + Private Function TryCalculateRequiredMembers( ByRef requiredMembersBuilder As ImmutableSegmentedDictionary(Of String, Symbol).Builder) As Boolean + If BaseTypeNoUseSiteDiagnostics?.HasRequiredMembersError = True Then + Return False + End If + + Dim baseAllRequiredMembers = If(BaseTypeNoUseSiteDiagnostics?.AllRequiredMembers, ImmutableSegmentedDictionary(Of String, Symbol).Empty) + Dim typeHasDeclaredRequiredMembers = HasAnyDeclaredRequiredMembers + + If (Not typeHasDeclaredRequiredMembers) AndAlso baseAllRequiredMembers.IsEmpty Then + Return True + End If + + For Each member In GetMembersUnordered() + ' Indexed properties cannot be required. + Dim [property] = TryCast(member, PropertySymbol) + If [property] IsNot Nothing AndAlso [property].ParameterCount > 0 Then + If [property].IsRequired Then + Return False + Else + Continue For + End If + End If + + Dim existingMember As Symbol = Nothing + ' Need to make sure that members from a base type weren't hidden by members from the current type. That is an error scenario + If baseAllRequiredMembers.TryGetValue(member.Name, existingMember) Then + ' This is only permitted if the member is an override of a required member from a base type, and is required itself + Dim overriddenMember = TryCast(member, PropertySymbol)?.OverriddenProperty + + If (Not member.IsRequired()) OrElse + overriddenMember Is Nothing OrElse + (Not overriddenMember.Equals(existingMember, TypeCompareKind.IgnoreTupleNames)) Then + Return False + End If + End If + + If Not member.IsRequired() Then + Continue For + End If + + If Not typeHasDeclaredRequiredMembers Then + ' Bad metadata. Type claimed it didn't declare any required members, but we found one. + Return False + End If + + If requiredMembersBuilder Is Nothing Then + requiredMembersBuilder = baseAllRequiredMembers.ToBuilder() + End If + + requiredMembersBuilder(member.Name) = member + Next + + Return True + End Function + #Region "INamedTypeSymbol" Private ReadOnly Property INamedTypeSymbol_Arity As Integer Implements INamedTypeSymbol.Arity diff --git a/src/Compilers/VisualBasic/Portable/Symbols/ObsoleteAttributeHelpers.vb b/src/Compilers/VisualBasic/Portable/Symbols/ObsoleteAttributeHelpers.vb index 12411f11b7d10..afeb698898f8c 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/ObsoleteAttributeHelpers.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/ObsoleteAttributeHelpers.vb @@ -33,8 +33,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend Shared Function GetObsoleteDataFromMetadata(token As EntityHandle, containingModule As PEModuleSymbol) As ObsoleteAttributeData Dim obsoleteAttributeData As ObsoleteAttributeData = Nothing ' ignoreByRefLikeMarker := False, since VB does not support ref-like types - ' https://github.com/dotnet/roslyn/issues/61435: Determine what support will be added for VB - obsoleteAttributeData = containingModule.Module.TryGetDeprecatedOrExperimentalOrObsoleteAttribute(token, New MetadataDecoder(containingModule), ignoreByRefLikeMarker:=False, ignoreRequiredMemberMarker:=False) + obsoleteAttributeData = containingModule.Module.TryGetDeprecatedOrExperimentalOrObsoleteAttribute(token, New MetadataDecoder(containingModule), ignoreByRefLikeMarker:=False, ignoreRequiredMemberMarker:=True) Debug.Assert(obsoleteAttributeData Is Nothing OrElse Not obsoleteAttributeData.IsUninitialized) Return obsoleteAttributeData End Function diff --git a/src/Compilers/VisualBasic/Portable/Symbols/PropertySymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/PropertySymbol.vb index 911794dc49176..22cdc43eb0c50 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/PropertySymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/PropertySymbol.vb @@ -533,6 +533,8 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' Friend MustOverride Overrides ReadOnly Property IsMyGroupCollectionProperty As Boolean + Public MustOverride ReadOnly Property IsRequired As Boolean + #Region "IPropertySymbol" Private ReadOnly Property IPropertySymbol_ExplicitInterfaceImplementations As ImmutableArray(Of IPropertySymbol) Implements IPropertySymbol.ExplicitInterfaceImplementations @@ -573,7 +575,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Private ReadOnly Property IPropertySymbol_IsRequired As Boolean Implements IPropertySymbol.IsRequired Get - Return False + Return Me.IsRequired End Get End Property diff --git a/src/Compilers/VisualBasic/Portable/Symbols/ReducedExtensionMethodSymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/ReducedExtensionMethodSymbol.vb index 4b14c26338747..8dfaf13e7f301 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/ReducedExtensionMethodSymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/ReducedExtensionMethodSymbol.vb @@ -847,6 +847,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols End Get End Property End Class + + Friend Overrides ReadOnly Property HasSetsRequiredMembers As Boolean + Get + Return False + End Get + End Property End Class Friend MustInherit Class ReducedParameterSymbolBase diff --git a/src/Compilers/VisualBasic/Portable/Symbols/Retargeting/RetargetingFieldSymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/Retargeting/RetargetingFieldSymbol.vb index 6724641e11f4f..b2982c8dc3917 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/Retargeting/RetargetingFieldSymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/Retargeting/RetargetingFieldSymbol.vb @@ -206,6 +206,13 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols.Retargeting Return _underlyingField.GetConstantValue(inProgress) End Function + Public Overrides ReadOnly Property IsRequired As Boolean + Get + Debug.Assert(Not _underlyingField.IsRequired) + Return False + End Get + End Property + Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return _underlyingField.Locations diff --git a/src/Compilers/VisualBasic/Portable/Symbols/Retargeting/RetargetingMethodSymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/Retargeting/RetargetingMethodSymbol.vb index ff84b2ff4355f..00bd421bbaab5 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/Retargeting/RetargetingMethodSymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/Retargeting/RetargetingMethodSymbol.vb @@ -518,5 +518,11 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols.Retargeting ' retargeting symbols refer to a symbol from another compilation, they don't define locals in the current compilation Throw ExceptionUtilities.Unreachable End Function + + Friend Overrides ReadOnly Property HasSetsRequiredMembers As Boolean + Get + Return _underlyingMethod.HasSetsRequiredMembers + End Get + End Property End Class End Namespace diff --git a/src/Compilers/VisualBasic/Portable/Symbols/Retargeting/RetargetingNamedTypeSymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/Retargeting/RetargetingNamedTypeSymbol.vb index f18c0e14a1290..dbfdad97cd702 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/Retargeting/RetargetingNamedTypeSymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/Retargeting/RetargetingNamedTypeSymbol.vb @@ -546,5 +546,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols.Retargeting Yield RetargetingTranslator.Retarget(underlying) Next End Function + + Friend Overrides ReadOnly Property HasAnyDeclaredRequiredMembers As Boolean + Get + Debug.Assert(Not _underlyingType.HasAnyDeclaredRequiredMembers) + Return False + End Get + End Property End Class End Namespace diff --git a/src/Compilers/VisualBasic/Portable/Symbols/Retargeting/RetargetingPropertySymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/Retargeting/RetargetingPropertySymbol.vb index efac9a254ed24..308499a9c2c66 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/Retargeting/RetargetingPropertySymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/Retargeting/RetargetingPropertySymbol.vb @@ -329,5 +329,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols.Retargeting Public Overrides Function GetDocumentationCommentXml(Optional preferredCulture As CultureInfo = Nothing, Optional expandIncludes As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As String Return _underlyingProperty.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken) End Function + + Public Overrides ReadOnly Property IsRequired As Boolean + Get + Debug.Assert(Not _underlyingProperty.IsRequired) + Return False + End Get + End Property End Class End Namespace diff --git a/src/Compilers/VisualBasic/Portable/Symbols/SignatureOnlyMethodSymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/SignatureOnlyMethodSymbol.vb index e94bf3daeb880..5455c9e34853d 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/SignatureOnlyMethodSymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/SignatureOnlyMethodSymbol.vb @@ -322,6 +322,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer Throw ExceptionUtilities.Unreachable End Function + + Friend Overrides ReadOnly Property HasSetsRequiredMembers As Boolean + Get + Throw ExceptionUtilities.Unreachable + End Get + End Property #End Region End Class End Namespace diff --git a/src/Compilers/VisualBasic/Portable/Symbols/SignatureOnlyPropertySymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/SignatureOnlyPropertySymbol.vb index d0c0b9e4b352f..ee362dfe262aa 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/SignatureOnlyPropertySymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/SignatureOnlyPropertySymbol.vb @@ -234,6 +234,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Throw ExceptionUtilities.Unreachable End Get End Property + + Public Overrides ReadOnly Property IsRequired As Boolean + Get + Throw ExceptionUtilities.Unreachable + End Get + End Property #End Region End Class End Namespace diff --git a/src/Compilers/VisualBasic/Portable/Symbols/Source/LambdaSymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/Source/LambdaSymbol.vb index 6527fe5cdbc06..4e1db4d908905 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/Source/LambdaSymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/Source/LambdaSymbol.vb @@ -372,6 +372,11 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Return hc End Function + Friend NotOverridable Overrides ReadOnly Property HasSetsRequiredMembers As Boolean + Get + Return False + End Get + End Property End Class End Namespace diff --git a/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceFieldSymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceFieldSymbol.vb index 4c1cea291fbba..cb69710cc7e0f 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceFieldSymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceFieldSymbol.vb @@ -141,6 +141,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols End Get End Property + Public NotOverridable Overrides ReadOnly Property IsRequired As Boolean + Get + Return False + End Get + End Property + Public Overrides ReadOnly Property AssociatedSymbol As Symbol Get Return Nothing diff --git a/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceMemberContainerTypeSymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceMemberContainerTypeSymbol.vb index dafca8a636ee5..54541fa138628 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceMemberContainerTypeSymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceMemberContainerTypeSymbol.vb @@ -4033,6 +4033,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Return Me._lazyAnyMemberHasAttributes.Value() End Get End Property + + Friend NotOverridable Overrides ReadOnly Property HasAnyDeclaredRequiredMembers As Boolean + Get + Return False + End Get + End Property End Class Friend Class EqualsIgnoringComparer diff --git a/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceMethodSymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceMethodSymbol.vb index 8ec5f4640f8d6..091c6923795bf 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceMethodSymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceMethodSymbol.vb @@ -2017,6 +2017,12 @@ lReportErrorOnTwoTokens: Public MustOverride Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol) Friend MustOverride Overrides ReadOnly Property OverriddenMembers As OverriddenMembersResult(Of MethodSymbol) + + Friend NotOverridable Overrides ReadOnly Property HasSetsRequiredMembers As Boolean + Get + Return False + End Get + End Property End Class Friend MustInherit Class SourceNonPropertyAccessorMethodSymbol diff --git a/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceNamedTypeSymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceNamedTypeSymbol.vb index ba21829839ee4..76fa00c5be9f2 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceNamedTypeSymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceNamedTypeSymbol.vb @@ -1404,6 +1404,11 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols If declaredOrDefaultBase IsNot Nothing Then ReportUseSiteInfoForBaseType(declaredOrDefaultBase, declaredBase, diagnostics) + + If declaredOrDefaultBase.AllRequiredMembers.Count > 0 OrElse declaredOrDefaultBase.HasRequiredMembersError Then + ' Cannot inherit from '{0}' because it has required members. + diagnostics.Add(ERRID.ERR_CannotInheritFromTypeWithRequiredMembers, GetInheritsLocation(Me), declaredOrDefaultBase) + End If End If Return declaredOrDefaultBase diff --git a/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceNamedTypeSymbol_ComClass.vb b/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceNamedTypeSymbol_ComClass.vb index 58f423cb4c760..0ac8859759bc1 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceNamedTypeSymbol_ComClass.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceNamedTypeSymbol_ComClass.vb @@ -1025,6 +1025,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend Overrides Function GetSynthesizedWithEventsOverrides() As IEnumerable(Of PropertySymbol) Return SpecializedCollections.EmptyEnumerable(Of PropertySymbol)() End Function + + Friend Overrides ReadOnly Property HasAnyDeclaredRequiredMembers As Boolean + Get + Return False + End Get + End Property End Class Private Class SynthesizedComMethod @@ -1373,6 +1379,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer Throw ExceptionUtilities.Unreachable End Function + + Friend NotOverridable Overrides ReadOnly Property HasSetsRequiredMembers As Boolean + Get + Return False + End Get + End Property End Class Private Class SynthesizedComEventMethod @@ -1851,6 +1863,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Return False End Get End Property + + Public Overrides ReadOnly Property IsRequired As Boolean + Get + Return False + End Get + End Property End Class End Class diff --git a/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceNamedTypeSymbol_GroupClass.vb b/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceNamedTypeSymbol_GroupClass.vb index ff9f9e45de933..983d6a7faf08f 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceNamedTypeSymbol_GroupClass.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceNamedTypeSymbol_GroupClass.vb @@ -289,8 +289,9 @@ DoneWithBindingAttributes: Private Shared Function MyGroupCollectionCandidateHasPublicParameterlessConstructor(candidate As SourceNamedTypeSymbol) As Boolean ' Simply calling HasPublicParameterlessConstructor might get us in a cycle. + Debug.Assert(candidate.TypeKind = TypeKind.Class) If candidate.MembersHaveBeenCreated Then - Return HasPublicParameterlessConstructor(candidate) + Return HasPublicParameterlessConstructor(candidate) = ConstructorConstraintError.None Else Return candidate.InferFromSyntaxIfClassWillHavePublicParameterlessConstructor() End If @@ -300,7 +301,12 @@ DoneWithBindingAttributes: Protected Overrides Sub VerifyMembers() If Me.TypeKind = TypeKind.Class Then Debug.Assert(MembersHaveBeenCreated) - Debug.Assert(HasPublicParameterlessConstructor(Me) = InferFromSyntaxIfClassWillHavePublicParameterlessConstructor()) + Dim constructorConstraintError As ConstructorConstraintError = HasPublicParameterlessConstructor(Me) + If InferFromSyntaxIfClassWillHavePublicParameterlessConstructor() Then + Debug.Assert(constructorConstraintError = ConstructorConstraintError.None OrElse constructorConstraintError = ConstructorConstraintError.HasRequiredMembers) + Else + Debug.Assert(constructorConstraintError = ConstructorConstraintError.NoPublicParameterlessConstructor) + End If End If End Sub #End If diff --git a/src/Compilers/VisualBasic/Portable/Symbols/Source/SourcePropertySymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/Source/SourcePropertySymbol.vb index eb38d02a40e6a..e5166a117c5df 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/Source/SourcePropertySymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/Source/SourcePropertySymbol.vb @@ -1213,6 +1213,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols AddSynthesizedAttribute(attributes, DeclaringCompilation.SynthesizeTupleNamesAttribute(Type)) End If End Sub + + Public Overrides ReadOnly Property IsRequired As Boolean + Get + Return False + End Get + End Property End Class End Namespace diff --git a/src/Compilers/VisualBasic/Portable/Symbols/Source/SynthesizedFieldSymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/Source/SynthesizedFieldSymbol.vb index 6411c6aed8c5c..d28f645f3c89d 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/Source/SynthesizedFieldSymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/Source/SynthesizedFieldSymbol.vb @@ -111,6 +111,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Return Nothing End Function + Public NotOverridable Overrides ReadOnly Property IsRequired As Boolean + Get + Return False + End Get + End Property + Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return Me._containingType diff --git a/src/Compilers/VisualBasic/Portable/Symbols/SubstitutedFieldSymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/SubstitutedFieldSymbol.vb index 7d4b4e1689a49..3da8dae5c3650 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/SubstitutedFieldSymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/SubstitutedFieldSymbol.vb @@ -201,6 +201,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Public Overrides Function GetDocumentationCommentXml(Optional preferredCulture As CultureInfo = Nothing, Optional expandIncludes As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As String Return _originalDefinition.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken) End Function + + Public Overrides ReadOnly Property IsRequired As Boolean + Get + Return _originalDefinition.IsRequired + End Get + End Property End Class End Namespace diff --git a/src/Compilers/VisualBasic/Portable/Symbols/SubstitutedMethodSymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/SubstitutedMethodSymbol.vb index cd7148d721ed3..944349b0db12c 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/SubstitutedMethodSymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/SubstitutedMethodSymbol.vb @@ -404,6 +404,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Return OriginalDefinition.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken) End Function + Friend NotOverridable Overrides ReadOnly Property HasSetsRequiredMembers As Boolean + Get + Return OriginalDefinition.HasSetsRequiredMembers + End Get + End Property + ''' ''' Base class for symbols representing non-generic or open generic methods contained within constructed generic type. ''' For example: A(Of Integer).B, A(Of Integer).B.C or A(Of Integer).B.C(Of ). diff --git a/src/Compilers/VisualBasic/Portable/Symbols/SubstitutedNamedType.vb b/src/Compilers/VisualBasic/Portable/Symbols/SubstitutedNamedType.vb index d1c3d3437f989..7a8486170a1b0 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/SubstitutedNamedType.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/SubstitutedNamedType.vb @@ -589,6 +589,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Next End Function + Friend Overrides ReadOnly Property HasAnyDeclaredRequiredMembers As Boolean + Get + Return OriginalDefinition.HasAnyDeclaredRequiredMembers + End Get + End Property + ''' ''' Base class for symbols representing non-generic or open generic types contained within constructed generic type. ''' For example: A(Of Integer).B, A(Of Integer).B.C or A(Of Integer).B.C(Of ). diff --git a/src/Compilers/VisualBasic/Portable/Symbols/SubstitutedPropertySymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/SubstitutedPropertySymbol.vb index 23b8ee27102b4..1101d84b3197f 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/SubstitutedPropertySymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/SubstitutedPropertySymbol.vb @@ -297,6 +297,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Public Overrides Function GetDocumentationCommentXml(Optional preferredCulture As CultureInfo = Nothing, Optional expandIncludes As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As String Return _originalDefinition.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken) End Function + + Public Overrides ReadOnly Property IsRequired As Boolean + Get + Return _originalDefinition.IsRequired + End Get + End Property End Class End Namespace diff --git a/src/Compilers/VisualBasic/Portable/Symbols/SymbolExtensions.vb b/src/Compilers/VisualBasic/Portable/Symbols/SymbolExtensions.vb index f88fe64cf68f8..2001188497c49 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/SymbolExtensions.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/SymbolExtensions.vb @@ -481,5 +481,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Private Function ContainsTupleNames(parameters As ImmutableArray(Of ParameterSymbol)) As Boolean Return parameters.Any(Function(p) p.Type.ContainsTupleNames()) End Function + + + Friend Function IsRequired(member As Symbol) As Boolean + Return If(TryCast(member, PropertySymbol)?.IsRequired, + If(TryCast(member, FieldSymbol)?.IsRequired, + False)) + End Function End Module End Namespace diff --git a/src/Compilers/VisualBasic/Portable/Symbols/Symbol_Attributes.vb b/src/Compilers/VisualBasic/Portable/Symbols/Symbol_Attributes.vb index c5a457bb9b0c8..95a1f0c45f704 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/Symbol_Attributes.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/Symbol_Attributes.vb @@ -200,6 +200,8 @@ Namespace Microsoft.CodeAnalysis.VisualBasic DirectCast(arguments.Diagnostics, BindingDiagnosticBag).Add(ERRID.WRN_AttributeNotSupportedInVB, arguments.AttributeSyntaxOpt.Location, AttributeDescription.SkipLocalsInitAttribute.FullName) ElseIf arguments.Attribute.IsTargetAttribute(Me, AttributeDescription.CompilerFeatureRequiredAttribute) Then DirectCast(arguments.Diagnostics, BindingDiagnosticBag).Add(ERRID.ERR_DoNotUseCompilerFeatureRequired, arguments.AttributeSyntaxOpt.Location) + ElseIf arguments.Attribute.IsTargetAttribute(Me, AttributeDescription.RequiredMemberAttribute) Then + DirectCast(arguments.Diagnostics, BindingDiagnosticBag).Add(ERRID.ERR_DoNotUseRequiredMember, arguments.AttributeSyntaxOpt.Location) End If End Sub diff --git a/src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/SynthesizedBackingFieldBase.vb b/src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/SynthesizedBackingFieldBase.vb index af78f26b65aca..8fce0b2a282b2 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/SynthesizedBackingFieldBase.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/SynthesizedBackingFieldBase.vb @@ -178,5 +178,11 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Return Nothing End Get End Property + + Public NotOverridable Overrides ReadOnly Property IsRequired As Boolean + Get + Return False + End Get + End Property End Class End Namespace diff --git a/src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/SynthesizedDelegateMethodSymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/SynthesizedDelegateMethodSymbol.vb index ef4ab1cec98e4..3a04cf6b8ed57 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/SynthesizedDelegateMethodSymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/SynthesizedDelegateMethodSymbol.vb @@ -449,5 +449,11 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer Throw ExceptionUtilities.Unreachable End Function + + Friend Overrides ReadOnly Property HasSetsRequiredMembers As Boolean + Get + Return False + End Get + End Property End Class End Namespace diff --git a/src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/SynthesizedEventDelegateSymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/SynthesizedEventDelegateSymbol.vb index c6b9b1722f5a3..bba66f54f6524 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/SynthesizedEventDelegateSymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/SynthesizedEventDelegateSymbol.vb @@ -54,7 +54,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols End If Dim sourceModule = DirectCast(Me.ContainingModule, SourceModuleSymbol) - Dim binder As binder = BinderBuilder.CreateBinderForType(sourceModule, _syntaxRef.SyntaxTree, Me.ContainingType) + Dim binder As Binder = BinderBuilder.CreateBinderForType(sourceModule, _syntaxRef.SyntaxTree, Me.ContainingType) Dim diagBag = BindingDiagnosticBag.GetInstance() @@ -352,7 +352,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols End Get End Property - Public Overrides ReadOnly Property TypeKind As TYPEKIND + Public Overrides ReadOnly Property TypeKind As TypeKind Get Return TypeKind.Delegate End Get @@ -444,6 +444,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend Overrides Function GetSynthesizedWithEventsOverrides() As IEnumerable(Of PropertySymbol) Return SpecializedCollections.EmptyEnumerable(Of PropertySymbol)() End Function + + Friend Overrides ReadOnly Property HasAnyDeclaredRequiredMembers As Boolean + Get + Return False + End Get + End Property End Class End Namespace diff --git a/src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/SynthesizedGlobalMethodBase.vb b/src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/SynthesizedGlobalMethodBase.vb index ef756f5ce879d..e7a7e0fb04606 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/SynthesizedGlobalMethodBase.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/SynthesizedGlobalMethodBase.vb @@ -351,6 +351,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer Throw ExceptionUtilities.Unreachable End Function + + Friend NotOverridable Overrides ReadOnly Property HasSetsRequiredMembers As Boolean + Get + Return False + End Get + End Property End Class End Namespace diff --git a/src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/SynthesizedMethodBase.vb b/src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/SynthesizedMethodBase.vb index c5d3992d949cb..365f9b28a2581 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/SynthesizedMethodBase.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/SynthesizedMethodBase.vb @@ -215,6 +215,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Return False End Get End Property + + Friend NotOverridable Overrides ReadOnly Property HasSetsRequiredMembers As Boolean + Get + Return False + End Get + End Property End Class End Namespace diff --git a/src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/SynthesizedOverridingWitheventsProperty.vb b/src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/SynthesizedOverridingWitheventsProperty.vb index 8d63176df27b8..57a4efd374c3b 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/SynthesizedOverridingWitheventsProperty.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/SynthesizedOverridingWitheventsProperty.vb @@ -256,5 +256,11 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Return False End Get End Property + + Public Overrides ReadOnly Property IsRequired As Boolean + Get + Return False + End Get + End Property End Class End Namespace diff --git a/src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/SynthesizedPropertyBase.vb b/src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/SynthesizedPropertyBase.vb index 9dcbd3cebf2af..557a14555b8c6 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/SynthesizedPropertyBase.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/SynthesizedPropertyBase.vb @@ -132,6 +132,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Return False End Get End Property + + Public NotOverridable Overrides ReadOnly Property IsRequired As Boolean + Get + Return False + End Get + End Property End Class End Namespace diff --git a/src/Compilers/VisualBasic/Portable/Symbols/Tuples/TupleFieldSymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/Tuples/TupleFieldSymbol.vb index 85050bab55250..a52d5d4638a48 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/Tuples/TupleFieldSymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/Tuples/TupleFieldSymbol.vb @@ -116,6 +116,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols _tupleElementIndex = other._tupleElementIndex AndAlso TypeSymbol.Equals(_containingTuple, other._containingTuple, TypeCompareKind.ConsiderEverything) End Function + + Public NotOverridable Overrides ReadOnly Property IsRequired As Boolean + Get + Return _underlyingField.IsRequired + End Get + End Property End Class ''' diff --git a/src/Compilers/VisualBasic/Portable/Symbols/Tuples/TupleMethodSymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/Tuples/TupleMethodSymbol.vb index a04069a68be78..226ab68708a6a 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/Tuples/TupleMethodSymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/Tuples/TupleMethodSymbol.vb @@ -146,5 +146,11 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Return other Is Me OrElse (other IsNot Nothing AndAlso TypeSymbol.Equals(Me._containingType, other._containingType, TypeCompareKind.ConsiderEverything) AndAlso Me._underlyingMethod.ConstructedFrom = other._underlyingMethod.ConstructedFrom) End Function + + Friend Overrides ReadOnly Property HasSetsRequiredMembers As Boolean + Get + Return _underlyingMethod.HasSetsRequiredMembers + End Get + End Property End Class End Namespace diff --git a/src/Compilers/VisualBasic/Portable/Symbols/Tuples/TuplePropertySymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/Tuples/TuplePropertySymbol.vb index dfab34acfcff5..2ddef7b5becac 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/Tuples/TuplePropertySymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/Tuples/TuplePropertySymbol.vb @@ -132,5 +132,11 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Public Overrides Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData) Return Me._underlyingProperty.GetAttributes() End Function + + Public Overrides ReadOnly Property IsRequired As Boolean + Get + Return _underlyingProperty.IsRequired + End Get + End Property End Class End Namespace diff --git a/src/Compilers/VisualBasic/Portable/Symbols/Tuples/TupleTypeSymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/Tuples/TupleTypeSymbol.vb index 42ebb8880b7da..8fdfed37c7355 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/Tuples/TupleTypeSymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/Tuples/TupleTypeSymbol.vb @@ -1126,5 +1126,10 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Next End Sub + Friend Overrides ReadOnly Property HasAnyDeclaredRequiredMembers As Boolean + Get + Return _underlyingType.HasAnyDeclaredRequiredMembers + End Get + End Property End Class End Namespace diff --git a/src/Compilers/VisualBasic/Portable/Symbols/UnboundGenericType.vb b/src/Compilers/VisualBasic/Portable/Symbols/UnboundGenericType.vb index 7bed5447d2323..69be00896c834 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/UnboundGenericType.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/UnboundGenericType.vb @@ -338,6 +338,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Return SpecializedCollections.EmptyEnumerable(Of PropertySymbol)() End Function + Friend NotOverridable Overrides ReadOnly Property HasAnyDeclaredRequiredMembers As Boolean + Get + Return False + End Get + End Property + Private NotInheritable Class ConstructedSymbol Inherits UnboundGenericType diff --git a/src/Compilers/VisualBasic/Portable/VBResources.resx b/src/Compilers/VisualBasic/Portable/VBResources.resx index 9b288c911c2b0..1ab1410a67155 100644 --- a/src/Compilers/VisualBasic/Portable/VBResources.resx +++ b/src/Compilers/VisualBasic/Portable/VBResources.resx @@ -5670,4 +5670,19 @@ Analyzer reference specified multiple times + + Required member '{0}' must be set in the object initializer or attribute arguments. + + + Cannot inherit from '{0}' because it has required members. + + + The required members list for '{0}' is malformed and cannot be interpreted. + + + '{2}' cannot satisfy the 'New' constraint on parameter '{1}' in the generic type or or method '{0}' because '{2}' has required members. + + + 'System.Runtime.CompilerServices.RequiredMemberAttribute' is reserved for compiler usage only. + \ No newline at end of file diff --git a/src/Compilers/VisualBasic/Portable/xlf/VBResources.cs.xlf b/src/Compilers/VisualBasic/Portable/xlf/VBResources.cs.xlf index 2aad39e12293c..78d4f4581e8bb 100644 --- a/src/Compilers/VisualBasic/Portable/xlf/VBResources.cs.xlf +++ b/src/Compilers/VisualBasic/Portable/xlf/VBResources.cs.xlf @@ -17,6 +17,11 @@ Chyba syntaxe příkazového řádku: {0} není platná hodnota možnosti {1}. Hodnota musí mít tvar {2}. + + Cannot inherit from '{0}' because it has required members. + Cannot inherit from '{0}' because it has required members. + + Please use language version {0} or greater to use comments after line continuation character. Použijte prosím verzi jazyka {0} nebo vyšší, abyste mohli používat komentáře za znakem pro pokračování řádku. @@ -32,11 +37,21 @@ Atribut System.Runtime.CompilerServices.CompilerFeatureRequiredAttribute je vyhrazen pouze pro použití kompilátorem. + + 'System.Runtime.CompilerServices.RequiredMemberAttribute' is reserved for compiler usage only. + 'System.Runtime.CompilerServices.RequiredMemberAttribute' is reserved for compiler usage only. + + Multiple analyzer config files cannot be in the same directory ('{0}'). Ve stejném adresáři nemůže být více konfiguračních souborů analyzátoru ({0}). + + '{2}' cannot satisfy the 'New' constraint on parameter '{1}' in the generic type or or method '{0}' because '{2}' has required members. + '{2}' cannot satisfy the 'New' constraint on parameter '{1}' in the generic type or or method '{0}' because '{2}' has required members. + + '{0}' cannot override init-only '{1}'. {0} nemůže přepsat init-only {1}. @@ -52,6 +67,16 @@ Typ {0} nemůže být vložený, protože má reabstrakci člena ze základního rozhraní. Zvažte nastavení vlastnosti Vložit typy spolupráce na hodnotu false. + + Required member '{0}' must be set in the object initializer or attribute arguments. + Required member '{0}' must be set in the object initializer or attribute arguments. + + + + The required members list for '{0}' is malformed and cannot be interpreted. + The required members list for '{0}' is malformed and cannot be interpreted. + + Target runtime doesn't support default interface implementation. Cílový modul runtime nepodporuje implementaci výchozího rozhraní. diff --git a/src/Compilers/VisualBasic/Portable/xlf/VBResources.de.xlf b/src/Compilers/VisualBasic/Portable/xlf/VBResources.de.xlf index 1c929d820e9ba..2b94448b25db4 100644 --- a/src/Compilers/VisualBasic/Portable/xlf/VBResources.de.xlf +++ b/src/Compilers/VisualBasic/Portable/xlf/VBResources.de.xlf @@ -17,6 +17,11 @@ Fehler in der Befehlszeilensyntax: "{0}" ist kein gültiger Wert für die Option "{1}". Der Wert muss im Format "{2}" vorliegen. + + Cannot inherit from '{0}' because it has required members. + Cannot inherit from '{0}' because it has required members. + + Please use language version {0} or greater to use comments after line continuation character. Verwenden Sie Sprachversion {0} oder höher, um Kommentare nach dem Zeilenfortsetzungszeichen zu verwenden. @@ -32,11 +37,21 @@ "System.Runtime.CompilerServices.CompilerFeatureRequiredAttribute" ist nur für die Compilerverwendung reserviert. + + 'System.Runtime.CompilerServices.RequiredMemberAttribute' is reserved for compiler usage only. + 'System.Runtime.CompilerServices.RequiredMemberAttribute' is reserved for compiler usage only. + + Multiple analyzer config files cannot be in the same directory ('{0}'). Dasselbe Verzeichnis ({0}) darf nicht mehrere Konfigurationsdateien des Analysetools enthalten. + + '{2}' cannot satisfy the 'New' constraint on parameter '{1}' in the generic type or or method '{0}' because '{2}' has required members. + '{2}' cannot satisfy the 'New' constraint on parameter '{1}' in the generic type or or method '{0}' because '{2}' has required members. + + '{0}' cannot override init-only '{1}'. Init-only "{1}" kann durch "{0}" nicht überschrieben werden. @@ -52,6 +67,16 @@ Der Typ "{0}" kann nicht eingebettet werden, weil er eine Neuabstraktion eines Members aus der Basisschnittstelle aufweist. Legen Sie die Eigenschaft "Interoptypen einbetten" ggf. auf FALSE fest. + + Required member '{0}' must be set in the object initializer or attribute arguments. + Required member '{0}' must be set in the object initializer or attribute arguments. + + + + The required members list for '{0}' is malformed and cannot be interpreted. + The required members list for '{0}' is malformed and cannot be interpreted. + + Target runtime doesn't support default interface implementation. Die Standardschnittstellenimplementierung wird von der Zielruntime nicht unterstützt. diff --git a/src/Compilers/VisualBasic/Portable/xlf/VBResources.es.xlf b/src/Compilers/VisualBasic/Portable/xlf/VBResources.es.xlf index c7f1499382bcf..2bde3eda0ff26 100644 --- a/src/Compilers/VisualBasic/Portable/xlf/VBResources.es.xlf +++ b/src/Compilers/VisualBasic/Portable/xlf/VBResources.es.xlf @@ -17,6 +17,11 @@ Error de sintaxis de la línea de comandos: "{0}" no es un valor válido para la opción "{1}". El valor debe tener el formato "{2}". + + Cannot inherit from '{0}' because it has required members. + Cannot inherit from '{0}' because it has required members. + + Please use language version {0} or greater to use comments after line continuation character. Use la versión de lenguaje {0} o superior para usar los comentarios después del carácter de continuación de línea. @@ -32,11 +37,21 @@ 'System.Runtime.CompilerServices.CompilerFeatureRequiredAttribute' está reservado solo para el uso del compilador. + + 'System.Runtime.CompilerServices.RequiredMemberAttribute' is reserved for compiler usage only. + 'System.Runtime.CompilerServices.RequiredMemberAttribute' is reserved for compiler usage only. + + Multiple analyzer config files cannot be in the same directory ('{0}'). No es posible que un mismo directorio ("{0}") contenga varios archivos de configuración del analizador. + + '{2}' cannot satisfy the 'New' constraint on parameter '{1}' in the generic type or or method '{0}' because '{2}' has required members. + '{2}' cannot satisfy the 'New' constraint on parameter '{1}' in the generic type or or method '{0}' because '{2}' has required members. + + '{0}' cannot override init-only '{1}'. "{0}" no puede sobrescribir la propiedad init-only "{1}". @@ -52,6 +67,16 @@ El tipo "{0}" no se puede insertar porque tiene una reabstracción de un miembro de la interfaz base. Puede establecer la propiedad "Incrustar tipos de interoperabilidad" en false. + + Required member '{0}' must be set in the object initializer or attribute arguments. + Required member '{0}' must be set in the object initializer or attribute arguments. + + + + The required members list for '{0}' is malformed and cannot be interpreted. + The required members list for '{0}' is malformed and cannot be interpreted. + + Target runtime doesn't support default interface implementation. El tiempo de ejecución de destino no admite la implementación de interfaz predeterminada. diff --git a/src/Compilers/VisualBasic/Portable/xlf/VBResources.fr.xlf b/src/Compilers/VisualBasic/Portable/xlf/VBResources.fr.xlf index 8a6e2e25c0f1c..324e70dc7dcf1 100644 --- a/src/Compilers/VisualBasic/Portable/xlf/VBResources.fr.xlf +++ b/src/Compilers/VisualBasic/Portable/xlf/VBResources.fr.xlf @@ -17,6 +17,11 @@ Erreur de syntaxe de ligne de commande : '{0}' est une valeur non valide pour l'option '{1}'. La valeur doit se présenter sous la forme '{2}'. + + Cannot inherit from '{0}' because it has required members. + Cannot inherit from '{0}' because it has required members. + + Please use language version {0} or greater to use comments after line continuation character. Utilisez la version de langage {0} ou une version ultérieure pour utiliser des commentaires après le caractère de continuation de la ligne. @@ -32,11 +37,21 @@ « System.Runtime.CompilerServices.CompilerFeatureRequiredAttribute » est réservé à l’utilisation du compilateur uniquement. + + 'System.Runtime.CompilerServices.RequiredMemberAttribute' is reserved for compiler usage only. + 'System.Runtime.CompilerServices.RequiredMemberAttribute' is reserved for compiler usage only. + + Multiple analyzer config files cannot be in the same directory ('{0}'). Plusieurs fichiers config d'analyseur ne peuvent pas figurer dans le même répertoire ('{0}'). + + '{2}' cannot satisfy the 'New' constraint on parameter '{1}' in the generic type or or method '{0}' because '{2}' has required members. + '{2}' cannot satisfy the 'New' constraint on parameter '{1}' in the generic type or or method '{0}' because '{2}' has required members. + + '{0}' cannot override init-only '{1}'. '{0}' ne peut pas substituer le '{1}' d'initialisation uniquement. @@ -52,6 +67,16 @@ Impossible d'incorporer le type '{0}', car il a une nouvelle abstraction d'un membre de l'interface de base. Affectez la valeur false à la propriété 'Incorporer les types interop'. + + Required member '{0}' must be set in the object initializer or attribute arguments. + Required member '{0}' must be set in the object initializer or attribute arguments. + + + + The required members list for '{0}' is malformed and cannot be interpreted. + The required members list for '{0}' is malformed and cannot be interpreted. + + Target runtime doesn't support default interface implementation. Le runtime cible ne prend pas en charge l'implémentation d'interface par défaut. diff --git a/src/Compilers/VisualBasic/Portable/xlf/VBResources.it.xlf b/src/Compilers/VisualBasic/Portable/xlf/VBResources.it.xlf index c8c5b9a4270ea..dc4527c57c197 100644 --- a/src/Compilers/VisualBasic/Portable/xlf/VBResources.it.xlf +++ b/src/Compilers/VisualBasic/Portable/xlf/VBResources.it.xlf @@ -17,6 +17,11 @@ Errore di sintassi della riga di comando: '{0}' non è un valore valido per l'opzione '{1}'. Il valore deve essere espresso nel formato '{2}'. + + Cannot inherit from '{0}' because it has required members. + Cannot inherit from '{0}' because it has required members. + + Please use language version {0} or greater to use comments after line continuation character. Usare la versione {0} o versioni successive del linguaggio per usare commenti dopo il carattere di continuazione di riga. @@ -32,11 +37,21 @@ 'System.Runtime.CompilerServices.CompilerFeatureRequiredAttribute' è riservato all'utilizzo esclusivo del compilatore. + + 'System.Runtime.CompilerServices.RequiredMemberAttribute' is reserved for compiler usage only. + 'System.Runtime.CompilerServices.RequiredMemberAttribute' is reserved for compiler usage only. + + Multiple analyzer config files cannot be in the same directory ('{0}'). La stessa directory ('{0}') non può contenere più file di configurazione dell'analizzatore. + + '{2}' cannot satisfy the 'New' constraint on parameter '{1}' in the generic type or or method '{0}' because '{2}' has required members. + '{2}' cannot satisfy the 'New' constraint on parameter '{1}' in the generic type or or method '{0}' because '{2}' has required members. + + '{0}' cannot override init-only '{1}'. '{0}' non può eseguire l'override della proprietà di sola inizializzazione '{1}'. @@ -52,6 +67,16 @@ Non è possibile incorporare il tipo '{0}' perché contiene una nuova astrazione di un membro dell'interfaccia di base. Provare a impostare la proprietà 'Incorpora tipi di interoperabilità' su false. + + Required member '{0}' must be set in the object initializer or attribute arguments. + Required member '{0}' must be set in the object initializer or attribute arguments. + + + + The required members list for '{0}' is malformed and cannot be interpreted. + The required members list for '{0}' is malformed and cannot be interpreted. + + Target runtime doesn't support default interface implementation. Il runtime di destinazione non supporta l'implementazione di interfaccia predefinita. diff --git a/src/Compilers/VisualBasic/Portable/xlf/VBResources.ja.xlf b/src/Compilers/VisualBasic/Portable/xlf/VBResources.ja.xlf index 5919d133d020b..5ea74d453c40f 100644 --- a/src/Compilers/VisualBasic/Portable/xlf/VBResources.ja.xlf +++ b/src/Compilers/VisualBasic/Portable/xlf/VBResources.ja.xlf @@ -17,6 +17,11 @@ コマンドライン構文エラー: '{0}' は、'{1}' オプションの有効な値ではありません。値は '{2}' の形式にする必要があります。 + + Cannot inherit from '{0}' because it has required members. + Cannot inherit from '{0}' because it has required members. + + Please use language version {0} or greater to use comments after line continuation character. 行連結文字の後のコメントを使用するには、言語バージョン {0} 以上をご使用ください。 @@ -32,11 +37,21 @@ 'System.Runtime.CompilerServices.CompilerFeatureRequiredAttribute' は、コンパイラのみで使用するために予約されています。 + + 'System.Runtime.CompilerServices.RequiredMemberAttribute' is reserved for compiler usage only. + 'System.Runtime.CompilerServices.RequiredMemberAttribute' is reserved for compiler usage only. + + Multiple analyzer config files cannot be in the same directory ('{0}'). 複数のアナライザー構成ファイルを同じディレクトリに入れることはできません ('{0}')。 + + '{2}' cannot satisfy the 'New' constraint on parameter '{1}' in the generic type or or method '{0}' because '{2}' has required members. + '{2}' cannot satisfy the 'New' constraint on parameter '{1}' in the generic type or or method '{0}' because '{2}' has required members. + + '{0}' cannot override init-only '{1}'. '{0}' では、初期化専用 '{1}' をオーバーライドできません。 @@ -52,6 +67,16 @@ 型 '{0}' には基底インターフェイスからのメンバーの再抽象化があるため、この型を埋め込むことはできません。'相互運用型の埋め込み' プロパティを false に設定することをご検討ください。 + + Required member '{0}' must be set in the object initializer or attribute arguments. + Required member '{0}' must be set in the object initializer or attribute arguments. + + + + The required members list for '{0}' is malformed and cannot be interpreted. + The required members list for '{0}' is malformed and cannot be interpreted. + + Target runtime doesn't support default interface implementation. ターゲット ランタイムは、既定のインターフェイスの実装をサポートしていません。 diff --git a/src/Compilers/VisualBasic/Portable/xlf/VBResources.ko.xlf b/src/Compilers/VisualBasic/Portable/xlf/VBResources.ko.xlf index 9124adc5e964a..0c2fd82f626c1 100644 --- a/src/Compilers/VisualBasic/Portable/xlf/VBResources.ko.xlf +++ b/src/Compilers/VisualBasic/Portable/xlf/VBResources.ko.xlf @@ -17,6 +17,11 @@ 명령줄 구문 오류: '{0}'은(는) '{1}' 옵션에 유효한 값이 아닙니다. 값은 '{2}' 형식이어야 합니다. + + Cannot inherit from '{0}' because it has required members. + Cannot inherit from '{0}' because it has required members. + + Please use language version {0} or greater to use comments after line continuation character. 줄 연속 문자 뒤에 주석을 사용하려면 언어 버전 {0} 이상을 사용하세요. @@ -32,11 +37,21 @@ 'System.Runtime.CompilerServices.CompilerFeatureRequiredAttribute'는 컴파일러 용도로만 예약되어 있습니다. + + 'System.Runtime.CompilerServices.RequiredMemberAttribute' is reserved for compiler usage only. + 'System.Runtime.CompilerServices.RequiredMemberAttribute' is reserved for compiler usage only. + + Multiple analyzer config files cannot be in the same directory ('{0}'). 분석기 구성 파일 여러 개가 동일한 디렉터리('{0}')에 있을 수 없습니다. + + '{2}' cannot satisfy the 'New' constraint on parameter '{1}' in the generic type or or method '{0}' because '{2}' has required members. + '{2}' cannot satisfy the 'New' constraint on parameter '{1}' in the generic type or or method '{0}' because '{2}' has required members. + + '{0}' cannot override init-only '{1}'. '{0}'은(는) 초기값 전용 '{1}'을(를) 재정의할 수 없습니다. @@ -52,6 +67,16 @@ '{0}' 형식에는 기본 인터페이스 멤버의 재추상화가 있으므로 해당 형식을 포함할 수 없습니다. 'Interop 형식 포함' 속성을 false로 설정해 보세요. + + Required member '{0}' must be set in the object initializer or attribute arguments. + Required member '{0}' must be set in the object initializer or attribute arguments. + + + + The required members list for '{0}' is malformed and cannot be interpreted. + The required members list for '{0}' is malformed and cannot be interpreted. + + Target runtime doesn't support default interface implementation. 대상 런타임이 기본 인터페이스 구현을 지원하지 않습니다. diff --git a/src/Compilers/VisualBasic/Portable/xlf/VBResources.pl.xlf b/src/Compilers/VisualBasic/Portable/xlf/VBResources.pl.xlf index ebb8cc4ef576d..b991b5393a5f1 100644 --- a/src/Compilers/VisualBasic/Portable/xlf/VBResources.pl.xlf +++ b/src/Compilers/VisualBasic/Portable/xlf/VBResources.pl.xlf @@ -17,6 +17,11 @@ Błąd składni wiersza polecenia: „{0}” nie jest prawidłową wartością dla opcji „{1}”. Wartość musi mieć postać „{2}”. + + Cannot inherit from '{0}' because it has required members. + Cannot inherit from '{0}' because it has required members. + + Please use language version {0} or greater to use comments after line continuation character. Użyj wersji języka {0} lub nowszej, aby stosować komentarze po znaku kontynuacji wiersza. @@ -32,11 +37,21 @@ Element „System.Runtime.CompilerServices.CompilerFeatureRequiredAttribute” jest zarezerwowany tylko do użycia przez kompilator. + + 'System.Runtime.CompilerServices.RequiredMemberAttribute' is reserved for compiler usage only. + 'System.Runtime.CompilerServices.RequiredMemberAttribute' is reserved for compiler usage only. + + Multiple analyzer config files cannot be in the same directory ('{0}'). Wiele plików konfiguracji analizatora nie może znajdować się w tym samym katalogu („{0}”). + + '{2}' cannot satisfy the 'New' constraint on parameter '{1}' in the generic type or or method '{0}' because '{2}' has required members. + '{2}' cannot satisfy the 'New' constraint on parameter '{1}' in the generic type or or method '{0}' because '{2}' has required members. + + '{0}' cannot override init-only '{1}'. Właściwość „{0}” nie może przesłonić właściwości tylko do inicjowania „{1}”. @@ -52,6 +67,16 @@ Nie można osadzić typu „{0}”, ponieważ zawiera ponowną abstrakcję składowej z interfejsu podstawowego. Rozważ ustawienie właściwości „Osadź typy międzyoperacyjne” na wartość false. + + Required member '{0}' must be set in the object initializer or attribute arguments. + Required member '{0}' must be set in the object initializer or attribute arguments. + + + + The required members list for '{0}' is malformed and cannot be interpreted. + The required members list for '{0}' is malformed and cannot be interpreted. + + Target runtime doesn't support default interface implementation. Docelowe środowisko uruchomieniowe nie obsługuje domyślnej implementacji interfejsu. diff --git a/src/Compilers/VisualBasic/Portable/xlf/VBResources.pt-BR.xlf b/src/Compilers/VisualBasic/Portable/xlf/VBResources.pt-BR.xlf index e0b4c6b51bdaa..4af0d2bbc9fa0 100644 --- a/src/Compilers/VisualBasic/Portable/xlf/VBResources.pt-BR.xlf +++ b/src/Compilers/VisualBasic/Portable/xlf/VBResources.pt-BR.xlf @@ -17,6 +17,11 @@ Erro de sintaxe de linha de comando: '{0}' não é um valor válido para a opção '{1}'. O valor precisa estar no formato '{2}'. + + Cannot inherit from '{0}' because it has required members. + Cannot inherit from '{0}' because it has required members. + + Please use language version {0} or greater to use comments after line continuation character. Use a versão de linguagem {0} ou posterior para usar comentários após o caractere de continuação de linha. @@ -32,11 +37,21 @@ 'System.Runtime.CompilerServices.CompilerFeatureRequiredAttribute' é reservado apanas para uso do compilador. + + 'System.Runtime.CompilerServices.RequiredMemberAttribute' is reserved for compiler usage only. + 'System.Runtime.CompilerServices.RequiredMemberAttribute' is reserved for compiler usage only. + + Multiple analyzer config files cannot be in the same directory ('{0}'). Não é possível que haja vários arquivos de configuração do analisador no mesmo diretório ('{0}'). + + '{2}' cannot satisfy the 'New' constraint on parameter '{1}' in the generic type or or method '{0}' because '{2}' has required members. + '{2}' cannot satisfy the 'New' constraint on parameter '{1}' in the generic type or or method '{0}' because '{2}' has required members. + + '{0}' cannot override init-only '{1}'. A propriedade '{0}' não pode substituir a propriedade '{1}' apenas para inicialização. @@ -52,6 +67,16 @@ O tipo '{0}' não pode ser inserido porque tem uma nova abstração de um membro da interface base. Considere a configuração da propriedade 'Embed Interop Types' como false. + + Required member '{0}' must be set in the object initializer or attribute arguments. + Required member '{0}' must be set in the object initializer or attribute arguments. + + + + The required members list for '{0}' is malformed and cannot be interpreted. + The required members list for '{0}' is malformed and cannot be interpreted. + + Target runtime doesn't support default interface implementation. O runtime de destino não é compatível com a implementação de interface padrão. diff --git a/src/Compilers/VisualBasic/Portable/xlf/VBResources.ru.xlf b/src/Compilers/VisualBasic/Portable/xlf/VBResources.ru.xlf index 0b0ff244cdc2b..090f2a6f470b6 100644 --- a/src/Compilers/VisualBasic/Portable/xlf/VBResources.ru.xlf +++ b/src/Compilers/VisualBasic/Portable/xlf/VBResources.ru.xlf @@ -17,6 +17,11 @@ Ошибка в синтаксисе командной строки: "{0}" не является допустимым значением для параметра "{1}". Значение должно иметь форму "{2}". + + Cannot inherit from '{0}' because it has required members. + Cannot inherit from '{0}' because it has required members. + + Please use language version {0} or greater to use comments after line continuation character. Используйте версию языка {0} или более позднюю, чтобы использовать комментарии после символа продолжения строки. @@ -32,11 +37,21 @@ "System.Runtime.CompilerServices.CompilerFeatureRequiredAttribute" зарезервирован для использования только компилятором. + + 'System.Runtime.CompilerServices.RequiredMemberAttribute' is reserved for compiler usage only. + 'System.Runtime.CompilerServices.RequiredMemberAttribute' is reserved for compiler usage only. + + Multiple analyzer config files cannot be in the same directory ('{0}'). В одном каталоге ("{0}") не может находиться несколько файлов конфигурации анализатора. + + '{2}' cannot satisfy the 'New' constraint on parameter '{1}' in the generic type or or method '{0}' because '{2}' has required members. + '{2}' cannot satisfy the 'New' constraint on parameter '{1}' in the generic type or or method '{0}' because '{2}' has required members. + + '{0}' cannot override init-only '{1}'. "{0}" не может переопределить свойство "{1}", предназначенное только для инициализации. @@ -52,6 +67,16 @@ Невозможно внедрить тип "{0}", так как он переопределяет абстракцию элемента базового интерфейса. Попробуйте задать для свойства "Внедрить типы взаимодействия" значение false (ложь). + + Required member '{0}' must be set in the object initializer or attribute arguments. + Required member '{0}' must be set in the object initializer or attribute arguments. + + + + The required members list for '{0}' is malformed and cannot be interpreted. + The required members list for '{0}' is malformed and cannot be interpreted. + + Target runtime doesn't support default interface implementation. Целевая среда выполнения не поддерживает реализацию интерфейса по умолчанию. diff --git a/src/Compilers/VisualBasic/Portable/xlf/VBResources.tr.xlf b/src/Compilers/VisualBasic/Portable/xlf/VBResources.tr.xlf index d6d0fce63e880..d7dd9755dc36f 100644 --- a/src/Compilers/VisualBasic/Portable/xlf/VBResources.tr.xlf +++ b/src/Compilers/VisualBasic/Portable/xlf/VBResources.tr.xlf @@ -17,6 +17,11 @@ Komut satırı söz dizimi hatası: '{0}', '{1}' seçeneği için geçerli bir değer değil. Değer '{2}' biçiminde olmalıdır. + + Cannot inherit from '{0}' because it has required members. + Cannot inherit from '{0}' because it has required members. + + Please use language version {0} or greater to use comments after line continuation character. Lütfen satır devamı karakterinden sonra açıklama kullanmak için {0} veya daha yüksek bir dil sürümü kullanın. @@ -32,11 +37,21 @@ 'System.Runtime.CompilerServices.CompilerFeatureRequiredAttribute' yalnızca derleyici kullanımı için ayrılmıştır. + + 'System.Runtime.CompilerServices.RequiredMemberAttribute' is reserved for compiler usage only. + 'System.Runtime.CompilerServices.RequiredMemberAttribute' is reserved for compiler usage only. + + Multiple analyzer config files cannot be in the same directory ('{0}'). Birden çok çözümleyici yapılandırma dosyası aynı dizinde ('{0}') olamaz. + + '{2}' cannot satisfy the 'New' constraint on parameter '{1}' in the generic type or or method '{0}' because '{2}' has required members. + '{2}' cannot satisfy the 'New' constraint on parameter '{1}' in the generic type or or method '{0}' because '{2}' has required members. + + '{0}' cannot override init-only '{1}'. '{0}', '{1}' init-only özelliğini geçersiz kılamaz. @@ -52,6 +67,16 @@ '{0}' türünün temel arabirimden yeniden soyutlanmış bir üyesi olduğundan bu tür eklenemiyor. 'Embed Interop Types' özelliğini false olarak ayarlamayı deneyin. + + Required member '{0}' must be set in the object initializer or attribute arguments. + Required member '{0}' must be set in the object initializer or attribute arguments. + + + + The required members list for '{0}' is malformed and cannot be interpreted. + The required members list for '{0}' is malformed and cannot be interpreted. + + Target runtime doesn't support default interface implementation. Hedef çalışma zamanı varsayılan arabirim uygulamasını desteklemiyor. diff --git a/src/Compilers/VisualBasic/Portable/xlf/VBResources.zh-Hans.xlf b/src/Compilers/VisualBasic/Portable/xlf/VBResources.zh-Hans.xlf index 958e0be310564..125695b2fbeb5 100644 --- a/src/Compilers/VisualBasic/Portable/xlf/VBResources.zh-Hans.xlf +++ b/src/Compilers/VisualBasic/Portable/xlf/VBResources.zh-Hans.xlf @@ -17,6 +17,11 @@ 命令行语法错误:“{0}”不是“{1}”选项的有效值。值的格式必须为 "{2}"。 + + Cannot inherit from '{0}' because it has required members. + Cannot inherit from '{0}' because it has required members. + + Please use language version {0} or greater to use comments after line continuation character. 请使用语言版本 {0} 或更高版本,以在行继续符后使用注释。 @@ -32,11 +37,21 @@ 'System.Runtime.CompilerServices.CompilerFeatureRequiredAttribute' 仅保留供编译器使用。 + + 'System.Runtime.CompilerServices.RequiredMemberAttribute' is reserved for compiler usage only. + 'System.Runtime.CompilerServices.RequiredMemberAttribute' is reserved for compiler usage only. + + Multiple analyzer config files cannot be in the same directory ('{0}'). 多个分析器配置文件不能位于同一目录({0})中。 + + '{2}' cannot satisfy the 'New' constraint on parameter '{1}' in the generic type or or method '{0}' because '{2}' has required members. + '{2}' cannot satisfy the 'New' constraint on parameter '{1}' in the generic type or or method '{0}' because '{2}' has required members. + + '{0}' cannot override init-only '{1}'. "{0}" 无法重写 init-only "{1}"。 @@ -52,6 +67,16 @@ 无法嵌入类型“{0}”,因为它有基本接口成员的重新抽象。请考虑将“嵌入互操作类型”属性设置为 false。 + + Required member '{0}' must be set in the object initializer or attribute arguments. + Required member '{0}' must be set in the object initializer or attribute arguments. + + + + The required members list for '{0}' is malformed and cannot be interpreted. + The required members list for '{0}' is malformed and cannot be interpreted. + + Target runtime doesn't support default interface implementation. 目标运行时不支持默认接口实现。 diff --git a/src/Compilers/VisualBasic/Portable/xlf/VBResources.zh-Hant.xlf b/src/Compilers/VisualBasic/Portable/xlf/VBResources.zh-Hant.xlf index 414bb417104d8..51c0cb2e499a3 100644 --- a/src/Compilers/VisualBasic/Portable/xlf/VBResources.zh-Hant.xlf +++ b/src/Compilers/VisualBasic/Portable/xlf/VBResources.zh-Hant.xlf @@ -17,6 +17,11 @@ 命令列語法錯誤: '{0}' 對 '{1}' 選項而言不是有效的值。此值的格式必須是 '{2}'。 + + Cannot inherit from '{0}' because it has required members. + Cannot inherit from '{0}' because it has required members. + + Please use language version {0} or greater to use comments after line continuation character. 若要在行接續字元後使用註解,請使用 {0} 或更高的語言版本。 @@ -32,11 +37,21 @@ 'System.Runtime.CompilerServices.CompilerFeatureRequiredAttribute' 僅保留給編譯器使用。 + + 'System.Runtime.CompilerServices.RequiredMemberAttribute' is reserved for compiler usage only. + 'System.Runtime.CompilerServices.RequiredMemberAttribute' is reserved for compiler usage only. + + Multiple analyzer config files cannot be in the same directory ('{0}'). 多個分析器組態檔無法處於相同目錄 ('{0}') 中。 + + '{2}' cannot satisfy the 'New' constraint on parameter '{1}' in the generic type or or method '{0}' because '{2}' has required members. + '{2}' cannot satisfy the 'New' constraint on parameter '{1}' in the generic type or or method '{0}' because '{2}' has required members. + + '{0}' cannot override init-only '{1}'. '{0}' 無法覆寫僅限初始化的 '{1}'。 @@ -52,6 +67,16 @@ 因為類型 '{0}' 有重新抽象成員 (來自基底介面),所以無法內嵌。請考慮將 [內嵌 Interop 類型] 屬性設為 false。 + + Required member '{0}' must be set in the object initializer or attribute arguments. + Required member '{0}' must be set in the object initializer or attribute arguments. + + + + The required members list for '{0}' is malformed and cannot be interpreted. + The required members list for '{0}' is malformed and cannot be interpreted. + + Target runtime doesn't support default interface implementation. 目標執行階段不支援預設介面實作。 diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/RequiredMembersTests.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/RequiredMembersTests.vb new file mode 100644 index 0000000000000..03517b3fe3ff8 --- /dev/null +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/RequiredMembersTests.vb @@ -0,0 +1,2479 @@ +' 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. +Imports Microsoft.CodeAnalysis.CSharp +Imports Microsoft.CodeAnalysis.Test.Utilities +Imports Microsoft.CodeAnalysis.VisualBasic.Symbols +Imports Microsoft.CodeAnalysis.VisualBasic.Syntax +Imports Roslyn.Test.Utilities + +Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests + + Public Class RequiredMembersTests + Inherits BasicTestBase + + Private Function CreateCSharpCompilationWithRequiredMembers(source As String) As CSharpCompilation + Return CreateCSharpCompilation(source, referencedAssemblies:=Basic.Reference.Assemblies.Net70.All) + End Function + + + Public Sub CannotInheritFromTypesWithRequiredMembers() + Dim csharp = " +public class Base +{ + public required int Field { get; set; } +} +public class Derived : Base {}" + + Dim csharpReference = CreateCSharpCompilationWithRequiredMembers(csharp).EmitToImageReference() + + Dim vb = CreateCompilation(" +Class VbDerivedBase + Inherits Base +End Class + +Class VbDerivedDerived + Inherits Derived +End Class + +Module M + Sub Main() + Dim v1 = New VbDerivedBase() + Dim v2 = New VbDerivedDerived() + G(Of VbDerivedBase)() + G(Of VbDerivedDerived)() + End Sub + + Sub G(Of T As New)() + End Sub +End Module", references:={csharpReference}) + + vb.AssertTheseDiagnostics( +BC37322: Cannot inherit from 'Base' because it has required members. + Inherits Base + ~~~~~~~~~~~~~ +BC37322: Cannot inherit from 'Derived' because it has required members. + Inherits Derived + ~~~~~~~~~~~~~~~~ +BC37321: Required member 'Public Overloads Property Field As Integer' must be set in the object initializer or attribute arguments. + Dim v1 = New VbDerivedBase() + ~~~~~~~~~~~~~ +BC37321: Required member 'Public Overloads Property Field As Integer' must be set in the object initializer or attribute arguments. + Dim v2 = New VbDerivedDerived() + ~~~~~~~~~~~~~~~~ +BC37324: 'VbDerivedBase' cannot satisfy the 'New' constraint on parameter 'T' in the generic type or or method 'Public Sub G(Of T As New)()' because 'VbDerivedBase' has required members. + G(Of VbDerivedBase)() + ~~~~~~~~~~~~~~~~~~~ +BC37324: 'VbDerivedDerived' cannot satisfy the 'New' constraint on parameter 'T' in the generic type or or method 'Public Sub G(Of T As New)()' because 'VbDerivedDerived' has required members. + G(Of VbDerivedDerived)() + ~~~~~~~~~~~~~~~~~~~~~~ +) + + Dim vbDerived = vb.GlobalNamespace.GetTypeMember("VbDerivedBase") + Assert.False(vbDerived.HasRequiredMembersError) + Assert.False(vbDerived.HasAnyDeclaredRequiredMembers) + AssertEx.Equal({"Property Base.Field As System.Int32"}, vbDerived.AllRequiredMembers.Select(Function(m) m.Value.ToTestDisplayString())) + + Dim vbDerivedDerived = vb.GlobalNamespace.GetTypeMember("VbDerivedDerived") + Assert.False(vbDerivedDerived.HasRequiredMembersError) + Assert.False(vbDerivedDerived.HasAnyDeclaredRequiredMembers) + AssertEx.Equal({"Property Base.Field As System.Int32"}, vbDerivedDerived.AllRequiredMembers.Select(Function(m) m.Value.ToTestDisplayString())) + End Sub + + + Public Sub CannotInheritFromTypesWithRequiredMembers_WithMalformedRequiredMemberList() + ' Equivalent to + ' public class Base + ' { + ' public required int P { get; set; } + ' } + ' public class Derived + ' { + ' public new required int P { get; set; } + ' public Derived() {} + ' } + Dim il = " +.class public auto ansi Base + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .field private int32 _P + + .method public specialname rtspecialname + instance void .ctor () cil managed + { + ldarg.0 + call instance void [mscorlib]System.Object::.ctor() + ret + } + + .method public specialname + instance int32 get_P () cil managed + { + IL_0000: ldarg.0 + IL_0001: ldfld int32 Base::_P + IL_0006: br.s IL_0008 + + IL_0008: ret + } + + .method public specialname + instance void set_P ( + int32 AutoPropertyValue + ) cil managed + { + ldarg.0 + ldarg.1 + stfld int32 Base::_P + ret + } + + .property instance int32 P() + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .get instance int32 Base::get_P() + .set instance void Base::set_P(int32) + } +} + +.class public auto ansi Derived + extends Base +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .field private int32 _P + + .method public specialname + instance int32 get_P () cil managed + { + IL_0000: ldarg.0 + IL_0001: ldfld int32 Derived::_P + IL_0006: br.s IL_0008 + + IL_0008: ret + } + + .method public specialname + instance void set_P ( + int32 AutoPropertyValue + ) cil managed + { + ldarg.0 + ldarg.1 + stfld int32 Derived::_P + ret + } + + .method public specialname rtspecialname + instance void .ctor () cil managed + { + nop + ldarg.0 + call instance void Base::.ctor() + ret + } + + .property instance int32 P() + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .get instance int32 Derived::get_P() + .set instance void Derived::set_P(int32) + } +}" + + Dim ilRef = CompileIL(il) + + Dim vb = CreateCompilation(" +Class VbDerivedDerived + Inherits Derived +End Class + +Module M + Sub Main() + Dim v2 = New VbDerivedDerived() + G(Of VbDerivedDerived)() + End Sub + + Sub G(Of T As New)() + End Sub +End Module", references:={ilRef}) + + vb.AssertTheseDiagnostics( +BC37322: Cannot inherit from 'Derived' because it has required members. + Inherits Derived + ~~~~~~~~~~~~~~~~ +BC37324: 'VbDerivedDerived' cannot satisfy the 'New' constraint on parameter 'T' in the generic type or or method 'Public Sub G(Of T As New)()' because 'VbDerivedDerived' has required members. + G(Of VbDerivedDerived)() + ~~~~~~~~~~~~~~~~~~~~~~ + ) + + Dim vbDerivedDerived = vb.GlobalNamespace.GetTypeMember("VbDerivedDerived") + Assert.True(vbDerivedDerived.HasRequiredMembersError) + Assert.False(vbDerivedDerived.HasAnyDeclaredRequiredMembers) + AssertEx.Empty(vbDerivedDerived.AllRequiredMembers.Select(Function(m) m.Value.ToTestDisplayString())) + End Sub + + Private Shared Function GetCDefinition(hasSetsRequiredMembers As Boolean, Optional typeKind As String = "class") As String + Return $" +using System.Diagnostics.CodeAnalysis; +public {typeKind} C +{{ + public required int Prop {{ get; set; }} + public required int Field; + + {If(hasSetsRequiredMembers, "[SetsRequiredMembers]", "")} + public C() {{}} +}}" + End Function + + + + Public Sub EnforcedRequiredMembers_NoInheritance_NoneSet( constructor As String) + + Dim cComp = CreateCSharpCompilationWithRequiredMembers(GetCDefinition(hasSetsRequiredMembers:=False)) + + Dim vbCode = $" +Module M + Sub Main() + Dim t {constructor} + End Sub +End Module" + + Dim comp = CreateCompilation(vbCode, {cComp.EmitToImageReference()}) + comp.AssertTheseDiagnostics( +BC37321: Required member 'Public Field As Integer' must be set in the object initializer or attribute arguments. + Dim t <%= constructor %> + ~ +BC37321: Required member 'Public Overloads Property Prop As Integer' must be set in the object initializer or attribute arguments. + Dim t <%= constructor %> + ~ + ) + End Sub + + + + Public Sub EnforcedRequiredMembers_NoInheritance_PartialSet( constructor As String) + Dim cComp = CreateCSharpCompilationWithRequiredMembers(GetCDefinition(hasSetsRequiredMembers:=False)) + + Dim vbCode = $" +Module M + Sub Main() + Dim t {constructor} With {{ .Prop = 1 }} + End Sub +End Module" + + Dim comp = CreateCompilation(vbCode, {cComp.EmitToImageReference()}) + comp.AssertTheseDiagnostics( +BC37321: Required member 'Public Field As Integer' must be set in the object initializer or attribute arguments. + Dim t <%= constructor %> With { .Prop = 1 } + ~ + ) + End Sub + + + + Public Sub EnforcedRequiredMembers_NoInheritance_AllSet( constructor As String) + + Dim cComp = CreateCSharpCompilationWithRequiredMembers(GetCDefinition(hasSetsRequiredMembers:=False)) + + Dim vbCode = $" +Module M + Sub Main() + Dim t {constructor} With {{ .Prop = 1, .Field = 2 }} + End Sub +End Module" + + Dim comp = CreateCompilation(vbCode, {cComp.EmitToImageReference()}) + comp.AssertNoDiagnostics() + End Sub + + + + Public Sub EnforcedRequiredMembers_NoInheritance_HasSetsRequiredMembers( constructor As String) + Dim cComp = CreateCSharpCompilationWithRequiredMembers(GetCDefinition(hasSetsRequiredMembers:=True)) + + Dim vbCode = $" +Module M + Sub Main() + Dim t {constructor} + End Sub +End Module" + + Dim comp = CreateCompilation(vbCode, {cComp.EmitToImageReference()}) + comp.AssertNoDiagnostics + End Sub + + Private Shared Function GetBaseDerivedDefinition(hasSetsRequiredMembers As Boolean) As String + Return $" +using System.Diagnostics.CodeAnalysis; +public class Base +{{ + public required int Prop1 {{ get; set; }} + public required int Field1; + + {If(hasSetsRequiredMembers, "[SetsRequiredMembers]", "")} + public Base() {{}} +}} +public class Derived : Base +{{ + public required int Prop2 {{ get; set; }} + public required int Field2; + + {If(hasSetsRequiredMembers, "[SetsRequiredMembers]", "")} + public Derived() {{}} +}} +public class DerivedDerived : Derived +{{ + {If(hasSetsRequiredMembers, "[SetsRequiredMembers]", "")} + public DerivedDerived() {{}} +}}" + End Function + + + + Public Sub EnforcedRequiredMembers_Inheritance_NoneSet( constructor As String) + Dim cComp = CreateCSharpCompilationWithRequiredMembers(GetBaseDerivedDefinition(hasSetsRequiredMembers:=False)) + + Dim vbCode = $" +Module M + Sub Main() + Dim t {constructor} + End Sub +End Module" + + Dim comp = CreateCompilation(vbCode, {cComp.EmitToImageReference()}) + comp.AssertTheseDiagnostics( +BC37321: Required member 'Public Field1 As Integer' must be set in the object initializer or attribute arguments. + Dim t <%= constructor %> + ~~~~~~~~~~~~~~ +BC37321: Required member 'Public Field2 As Integer' must be set in the object initializer or attribute arguments. + Dim t <%= constructor %> + ~~~~~~~~~~~~~~ +BC37321: Required member 'Public Overloads Property Prop1 As Integer' must be set in the object initializer or attribute arguments. + Dim t <%= constructor %> + ~~~~~~~~~~~~~~ +BC37321: Required member 'Public Overloads Property Prop2 As Integer' must be set in the object initializer or attribute arguments. + Dim t <%= constructor %> + ~~~~~~~~~~~~~~ + ) + End Sub + + + + Public Sub EnforcedRequiredMembers_Inheritance_PartialSet( constructor As String) + Dim cComp = CreateCSharpCompilationWithRequiredMembers(GetBaseDerivedDefinition(hasSetsRequiredMembers:=False)) + + Dim vbCode = $" +Module M + Sub Main() + Dim t {constructor} With {{ .Prop1 = 1, .Field2 = 2 }} + End Sub +End Module" + + Dim comp = CreateCompilation(vbCode, {cComp.EmitToImageReference()}) + comp.AssertTheseDiagnostics( +BC37321: Required member 'Public Field1 As Integer' must be set in the object initializer or attribute arguments. + Dim t <%= constructor %> With { .Prop1 = 1, .Field2 = 2 } + ~~~~~~~~~~~~~~ +BC37321: Required member 'Public Overloads Property Prop2 As Integer' must be set in the object initializer or attribute arguments. + Dim t <%= constructor %> With { .Prop1 = 1, .Field2 = 2 } + ~~~~~~~~~~~~~~ + ) + End Sub + + + + Public Sub EnforcedRequiredMembers_Inheritance_AllSet( constructor As String) + Dim cComp = CreateCSharpCompilationWithRequiredMembers(GetBaseDerivedDefinition(hasSetsRequiredMembers:=False)) + + Dim vbCode = $" +Module M + Sub Main() + Dim t {constructor} With {{ .Prop1 = 1, .Prop2 = 2, .Field1 = 1, .Field2 = 2 }} + End Sub +End Module" + + Dim comp = CreateCompilation(vbCode, {cComp.EmitToImageReference()}) + comp.AssertNoDiagnostics() + End Sub + + + + Public Sub EnforcedRequiredMembers_Inheritance_NoneSet_HasSetsRequiredMembers( constructor As String) + Dim cComp = CreateCSharpCompilationWithRequiredMembers(GetBaseDerivedDefinition(hasSetsRequiredMembers:=True)) + + Dim vbCode = $" +Module M + Sub Main() + Dim t {constructor} + End Sub +End Module" + + Dim comp = CreateCompilation(vbCode, {cComp.EmitToImageReference()}) + comp.AssertNoDiagnostics() + End Sub + + + Public Sub EnforcedRequiredMembers_ThroughRetargeting_NoneSet() + Dim retargetedCode = GetCDefinition(hasSetsRequiredMembers:=False) + + Dim originalC = CreateCSharpCompilation(New AssemblyIdentity("Ret", New Version(1, 0, 0, 0), isRetargetable:=True), retargetedCode, referencedAssemblies:=Basic.Reference.Assemblies.Net70.All) + + Dim originalBasic = CreateCompilation(" +Public Class Base + Public Property C As C +End Class", {originalC.EmitToImageReference()}) + + Dim retargetedC = CreateCSharpCompilation(New AssemblyIdentity("Ret", New Version(2, 0, 0, 0), isRetargetable:=True), retargetedCode, referencedAssemblies:=Basic.Reference.Assemblies.Net70.All) + + Dim comp = CreateCompilation(" +Module M + Public Sub Main() + Dim b As New Base() With { .C = New C() } + End Sub +End Module", {originalBasic.ToMetadataReference(), retargetedC.EmitToImageReference()}) + + comp.AssertTheseDiagnostics( +BC37321: Required member 'Public Field As Integer' must be set in the object initializer or attribute arguments. + Dim b As New Base() With { .C = New C() } + ~ +BC37321: Required member 'Public Overloads Property Prop As Integer' must be set in the object initializer or attribute arguments. + Dim b As New Base() With { .C = New C() } + ~ + ) + End Sub + + + + Public Sub EnforcedRequiredMembers_ThroughRetargeting_AllSet( constructor As String) + Dim retargetedCode = GetCDefinition(hasSetsRequiredMembers:=False) + + Dim originalC = CreateCSharpCompilation(New AssemblyIdentity("Ret", New Version(1, 0, 0, 0), isRetargetable:=True), retargetedCode, referencedAssemblies:=Basic.Reference.Assemblies.Net70.All) + + Dim originalBasic = CreateCompilation(" +Public Class Base + Public Property C As C +End Class", {originalC.EmitToImageReference()}) + + Dim retargetedC = CreateCSharpCompilation(New AssemblyIdentity("Ret", New Version(2, 0, 0, 0), isRetargetable:=True), retargetedCode, referencedAssemblies:=Basic.Reference.Assemblies.Net70.All) + + Dim comp = CreateCompilation(" +Module M + Public Sub Main() + Dim b As New Base() With { .C = New C() With { .Field = 1, .Prop = 1 } } + End Sub +End Module", {originalBasic.ToMetadataReference(), retargetedC.EmitToImageReference()}) + + comp.AssertNoDiagnostics() + End Sub + + + + Public Sub EnforcedRequiredMembers_ThroughRetargeting_HasSetsRequiredMembers( constructor As String) + + Dim retargetedCode = GetCDefinition(hasSetsRequiredMembers:=True) + + Dim originalC = CreateCSharpCompilation(New AssemblyIdentity("Ret", New Version(1, 0, 0, 0), isRetargetable:=True), retargetedCode, referencedAssemblies:=Basic.Reference.Assemblies.Net70.All) + + Dim originalBasic = CreateCompilation(" +Public Class Base + Public Property C As C +End Class", {originalC.EmitToImageReference()}) + + Dim retargetedC = CreateCSharpCompilation(New AssemblyIdentity("Ret", New Version(2, 0, 0, 0), isRetargetable:=True), retargetedCode, referencedAssemblies:=Basic.Reference.Assemblies.Net70.All) + + Dim comp = CreateCompilation(" +Module M + Public Sub Main() + Dim b As New Base() With { .C = New C() } + End Sub +End Module", {originalBasic.ToMetadataReference(), retargetedC.EmitToImageReference()}) + + comp.AssertNoDiagnostics() + End Sub + + + Public Sub EnforcedRequiredMembers_ThroughRetargeting_RequiredMemberAdded() + Dim codeWithRequired = GetCDefinition(hasSetsRequiredMembers:=False) + Dim codeWithoutRequired = codeWithRequired.Replace("required ", "") + + Dim originalC = CreateCSharpCompilation(New AssemblyIdentity("Ret", New Version(1, 0, 0, 0), isRetargetable:=True), codeWithoutRequired, referencedAssemblies:=Basic.Reference.Assemblies.Net70.All) + + Dim originalBasic = CreateCompilation(" +Public Class Derived + Inherits C +End Class", {originalC.EmitToImageReference()}) + + Dim retargetedC = CreateCSharpCompilation(New AssemblyIdentity("Ret", New Version(2, 0, 0, 0), isRetargetable:=True), codeWithRequired, referencedAssemblies:=Basic.Reference.Assemblies.Net70.All) + + Dim comp = CreateCompilation(" +Module M + Public Sub Main() + Dim b As New Derived() + End Sub +End Module", {originalBasic.ToMetadataReference(), retargetedC.EmitToImageReference()}) + + comp.AssertTheseDiagnostics( +BC37321: Required member 'Public Field As Integer' must be set in the object initializer or attribute arguments. + Dim b As New Derived() + ~~~~~~~ +BC37321: Required member 'Public Overloads Property Prop As Integer' must be set in the object initializer or attribute arguments. + Dim b As New Derived() + ~~~~~~~ + ) + End Sub + + + + Public Sub EnforcedRequiredMembers_ThroughMetadataAndSource( constructor As String) + Dim originalVbComp = CreateCompilation(" +Public Class Base +End Class", targetFramework:=TargetFramework.Net70) + + originalVbComp.AssertNoDiagnostics() + + Dim csharpComp = CreateCSharpCompilation(" +public class Derived : Base +{ + public required int Prop { get; set; } +}", referencedAssemblies:=DirectCast(Basic.Reference.Assemblies.Net70.All, IEnumerable(Of MetadataReference)).Append(originalVbComp.EmitToImageReference())) + + Dim comp = CreateCompilation($" +Module M + Sub Main() + Dim derived {constructor} + End Sub +End Module", {originalVbComp.ToMetadataReference(), csharpComp.EmitToImageReference()}) + + comp.AssertTheseDiagnostics( +BC37321: Required member 'Public Overloads Property Prop As Integer' must be set in the object initializer or attribute arguments. + Dim derived <%= constructor %> + ~~~~~~~ + + ) + End Sub + + Private Function GetDerivedOverrideDefinition(hasSetsRequiredMembers As Boolean) As String + Return $" +using System.Diagnostics.CodeAnalysis; +public class Base +{{ + public virtual required int Prop {{ get; set; }} + + {If(hasSetsRequiredMembers, "[SetsRequiredMembers]", "")} + public Base() {{}} +}} +public class Derived : Base +{{ + public override required int Prop {{ get; set; }} + + {If(hasSetsRequiredMembers, "[SetsRequiredMembers]", "")} + public Derived() {{}} +}} +public class DerivedDerived : Derived +{{ + public override required int Prop {{ get; set; }} + + {If(hasSetsRequiredMembers, "[SetsRequiredMembers]", "")} + public DerivedDerived() {{}} +}}" + End Function + + + + Public Sub EnforcedRequiredMembers_Override_NoneSet_01( constructor As String) + Dim cComp = CreateCSharpCompilationWithRequiredMembers(GetDerivedOverrideDefinition(hasSetsRequiredMembers:=False)) + + Dim vbCode = $" +Module M + Sub Main() + Dim t {constructor} + End Sub +End Module" + + Dim comp = CreateCompilation(vbCode, {cComp.EmitToImageReference()}) + comp.AssertTheseDiagnostics( +BC37321: Required member 'Public Overrides Property Prop As Integer' must be set in the object initializer or attribute arguments. + Dim t <%= constructor %> + ~~~~~~~ + ) + End Sub + + + + Public Sub EnforcedRequiredMembers_Override_NoneSet_02( constructor As String) + Dim cComp = CreateCSharpCompilationWithRequiredMembers(GetDerivedOverrideDefinition(hasSetsRequiredMembers:=False)) + + Dim vbCode = $" +Module M + Sub Main() + Dim t {constructor} + End Sub +End Module" + + Dim comp = CreateCompilation(vbCode, {cComp.EmitToImageReference()}) + comp.AssertTheseDiagnostics( +BC37321: Required member 'Public Overrides Property Prop As Integer' must be set in the object initializer or attribute arguments. + Dim t <%= constructor %> + ~~~~~~~~~~~~~~ + ) + End Sub + + + + Public Sub EnforcedRequiredMembers_Override_AllSet_01( constructor As String) + Dim cComp = CreateCSharpCompilationWithRequiredMembers(GetDerivedOverrideDefinition(hasSetsRequiredMembers:=False)) + + Dim vbCode = $" +Module M + Sub Main() + Dim t {constructor} With {{ .Prop = 1 }} + End Sub +End Module" + + Dim comp = CreateCompilation(vbCode, {cComp.EmitToImageReference()}) + comp.AssertNoDiagnostics() + End Sub + + + + Public Sub EnforcedRequiredMembers_Override_AllSet_02( constructor As String) + Dim cComp = CreateCSharpCompilationWithRequiredMembers(GetDerivedOverrideDefinition(hasSetsRequiredMembers:=False)) + + Dim vbCode = $" +Module M + Sub Main() + Dim t {constructor} With {{ .Prop = 1 }} + End Sub +End Module" + + Dim comp = CreateCompilation(vbCode, {cComp.EmitToImageReference()}) + comp.AssertNoDiagnostics() + End Sub + + + + Public Sub EnforcedRequiredMembers_Override_HasSetsRequiredMembers( constructor As String) + Dim cComp = CreateCSharpCompilationWithRequiredMembers(GetDerivedOverrideDefinition(hasSetsRequiredMembers:=True)) + + Dim vbCode = $" +Module M + Sub Main() + Dim t {constructor} + End Sub +End Module" + + Dim comp = CreateCompilation(vbCode, {cComp.EmitToImageReference()}) + comp.AssertNoDiagnostics() + End Sub + + + Public Sub EnforcedRequiredMembers_StructureNothing_ImplicitCtor() + Dim cComp = CreateCSharpCompilationWithRequiredMembers(" +using System.Diagnostics.CodeAnalysis; +public struct S +{ + public required int F; +}") + + Dim vbCode = $" +Module M + Sub Main() + Dim s As S = Nothing + End Sub +End Module" + + Dim comp = CreateCompilation(vbCode, {cComp.EmitToImageReference()}) + comp.AssertNoDiagnostics() + End Sub + + + Public Sub EnforcedRequiredMembers_StructureNothing_ExplicitCtor() + Dim cComp = CreateCSharpCompilationWithRequiredMembers(" +using System.Diagnostics.CodeAnalysis; +public struct S +{ + public required int F; + public S() {} +}") + + Dim vbCode = $" +Module M + Sub Main() + Dim s As S = Nothing + End Sub +End Module" + + Dim comp = CreateCompilation(vbCode, {cComp.EmitToImageReference()}) + comp.AssertNoDiagnostics() + End Sub + + + Public Sub EnforcedRequiredMembers_StructureNothing_HasSetsRequiredMembers() + Dim cComp = CreateCSharpCompilationWithRequiredMembers(" +using System.Diagnostics.CodeAnalysis; +public struct S +{ + public required int F; + [SetsRequiredMembers] + public S() {} +}") + + Dim vbCode = $" +Module M + Sub Main() + Dim s As S = Nothing + End Sub +End Module" + + Dim comp = CreateCompilation(vbCode, {cComp.EmitToImageReference()}) + comp.AssertNoDiagnostics() + End Sub + + + Public Sub EnforcedRequiredMembers_ShadowedFromMetadata_01() + ' Equivalent to + ' public class Base + ' { + ' public required int P { get; set; } + ' } + ' public class Derived + ' { + ' public new required int P { get; set; } + ' public Derived() {} + ' [SetsRequiredMembers] public Derived(int unused) {} + ' } + Dim il = " +.class public auto ansi Base + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .field private int32 _P + + .method public specialname rtspecialname + instance void .ctor () cil managed + { + ldarg.0 + call instance void [mscorlib]System.Object::.ctor() + ret + } + + .method public specialname + instance int32 get_P () cil managed + { + IL_0000: ldarg.0 + IL_0001: ldfld int32 Base::_P + IL_0006: br.s IL_0008 + + IL_0008: ret + } + + .method public specialname + instance void set_P ( + int32 AutoPropertyValue + ) cil managed + { + ldarg.0 + ldarg.1 + stfld int32 Base::_P + ret + } + + .property instance int32 P() + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .get instance int32 Base::get_P() + .set instance void Base::set_P(int32) + } +} + +.class public auto ansi Derived + extends Base +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .field private int32 _P + + .method public specialname + instance int32 get_P () cil managed + { + IL_0000: ldarg.0 + IL_0001: ldfld int32 Derived::_P + IL_0006: br.s IL_0008 + + IL_0008: ret + } + + .method public specialname + instance void set_P ( + int32 AutoPropertyValue + ) cil managed + { + ldarg.0 + ldarg.1 + stfld int32 Derived::_P + ret + } + + .method public specialname rtspecialname + instance void .ctor () cil managed + { + nop + ldarg.0 + call instance void Base::.ctor() + ret + } + + .method public specialname rtspecialname + instance void .ctor ( + int32 'unused' + ) cil managed + { + .custom instance void [mscorlib]System.Diagnostics.CodeAnalysis.SetsRequiredMembersAttribute::.ctor() = ( + 01 00 00 00 + ) + ldarg.0 + call instance void Base::.ctor() + ret + } + + .property instance int32 P() + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .get instance int32 Derived::get_P() + .set instance void Derived::set_P(int32) + } +}" + + Dim ilRef = CompileIL(il) + + Dim comp = CreateCompilation(" +Module M + Sub Main() + Dim d1 = New Derived() + Dim d2 = New Derived(1) + End Sub +End Module", {ilRef}, targetFramework:=TargetFramework.Net70) + + comp.AssertTheseDiagnostics( +BC37323: The required members list for 'Derived' is malformed and cannot be interpreted. + Dim d1 = New Derived() + ~~~~~~~~~~~~~ + ) + End Sub + + + Public Sub EnforcedRequiredMembers_ShadowedFromMetadata_02() + ' Equivalent to + ' public class Base + ' { + ' public required int P { get; set; } + ' } + ' [RequiredMember] public class Derived + ' { + ' public new int P { get; set; } + ' public Derived() {} + ' [SetsRequiredMembers] public Derived(int unused) {} + ' } + Dim il = " +.class public auto ansi Base + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .field private int32 _P + + .method public specialname rtspecialname + instance void .ctor () cil managed + { + ldarg.0 + call instance void [mscorlib]System.Object::.ctor() + ret + } + + .method public specialname + instance int32 get_P () cil managed + { + IL_0000: ldarg.0 + IL_0001: ldfld int32 Base::_P + IL_0006: br.s IL_0008 + + IL_0008: ret + } + + .method public specialname + instance void set_P ( + int32 AutoPropertyValue + ) cil managed + { + ldarg.0 + ldarg.1 + stfld int32 Base::_P + ret + } + + .property instance int32 P() + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .get instance int32 Base::get_P() + .set instance void Base::set_P(int32) + } +} + +.class public auto ansi Derived + extends Base +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .field private int32 _P + + .method public specialname + instance int32 get_P () cil managed + { + IL_0000: ldarg.0 + IL_0001: ldfld int32 Derived::_P + IL_0006: br.s IL_0008 + + IL_0008: ret + } + + .method public specialname + instance void set_P ( + int32 AutoPropertyValue + ) cil managed + { + ldarg.0 + ldarg.1 + stfld int32 Derived::_P + ret + } + + .method public specialname rtspecialname + instance void .ctor () cil managed + { + nop + ldarg.0 + call instance void Base::.ctor() + ret + } + + .method public specialname rtspecialname + instance void .ctor ( + int32 'unused' + ) cil managed + { + .custom instance void [mscorlib]System.Diagnostics.CodeAnalysis.SetsRequiredMembersAttribute::.ctor() = ( + 01 00 00 00 + ) + ldarg.0 + call instance void Base::.ctor() + ret + } + + .property instance int32 P() + { + .get instance int32 Derived::get_P() + .set instance void Derived::set_P(int32) + } +}" + + Dim ilRef = CompileIL(il) + + Dim comp = CreateCompilation(" +Module M + Sub Main() + Dim d1 = New Derived() + Dim d2 = New Derived(1) + End Sub +End Module", {ilRef}, targetFramework:=TargetFramework.Net70) + + comp.AssertTheseDiagnostics( +BC37323: The required members list for 'Derived' is malformed and cannot be interpreted. + Dim d1 = New Derived() + ~~~~~~~~~~~~~ + ) + End Sub + + + Public Sub EnforcedRequiredMembers_ShadowedFromMetadata_03() + ' Equivalent to + ' public class Base + ' { + ' public required int P { get; set; } + ' } + ' public class Derived + ' { + ' public new int P { get; set; } + ' public Derived() {} + ' [SetsRequiredMembers] public Derived(int unused) {} + ' } + Dim il = " +.class public auto ansi Base + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .field private int32 _P + + .method public specialname rtspecialname + instance void .ctor () cil managed + { + ldarg.0 + call instance void [mscorlib]System.Object::.ctor() + ret + } + + .method public specialname + instance int32 get_P () cil managed + { + IL_0000: ldarg.0 + IL_0001: ldfld int32 Base::_P + IL_0006: br.s IL_0008 + + IL_0008: ret + } + + .method public specialname + instance void set_P ( + int32 AutoPropertyValue + ) cil managed + { + ldarg.0 + ldarg.1 + stfld int32 Base::_P + ret + } + + .property instance int32 P() + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .get instance int32 Base::get_P() + .set instance void Base::set_P(int32) + } +} + +.class public auto ansi Derived + extends Base +{ + .field private int32 _P + + .method public specialname + instance int32 get_P () cil managed + { + IL_0000: ldarg.0 + IL_0001: ldfld int32 Derived::_P + IL_0006: br.s IL_0008 + + IL_0008: ret + } + + .method public specialname + instance void set_P ( + int32 AutoPropertyValue + ) cil managed + { + ldarg.0 + ldarg.1 + stfld int32 Derived::_P + ret + } + + .method public specialname rtspecialname + instance void .ctor () cil managed + { + nop + ldarg.0 + call instance void Base::.ctor() + ret + } + + .method public specialname rtspecialname + instance void .ctor ( + int32 'unused' + ) cil managed + { + .custom instance void [mscorlib]System.Diagnostics.CodeAnalysis.SetsRequiredMembersAttribute::.ctor() = ( + 01 00 00 00 + ) + ldarg.0 + call instance void Base::.ctor() + ret + } + + .property instance int32 P() + { + .get instance int32 Derived::get_P() + .set instance void Derived::set_P(int32) + } +}" + + Dim ilRef = CompileIL(il) + + Dim comp = CreateCompilation(" +Module M + Sub Main() + Dim d1 = New Derived() + Dim d2 = New Derived(1) + End Sub +End Module", {ilRef}, targetFramework:=TargetFramework.Net70) + + comp.AssertTheseDiagnostics( +BC37323: The required members list for 'Derived' is malformed and cannot be interpreted. + Dim d1 = New Derived() + ~~~~~~~~~~~~~ + ) + End Sub + + + Public Sub EnforcedRequiredMembers_OverriddenFromMetadata() + ' Equivalent to + ' public class Base + ' { + ' public virtual int P { get; set; } + ' public virtual required modopt(int) int P { get; set; } + ' } + ' public class Derived + ' { + ' public override int P { get; set; } + ' public Derived() {} + ' } + Dim il = " +.class public auto ansi beforefieldinit Base extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + + .field private int32 'k__BackingField' + + // Methods + .method public hidebysig specialname newslot virtual + instance int32 get_Prop () cil managed + { + ldarg.0 + ldfld int32 Base::'k__BackingField' + ret + } + + .method public hidebysig specialname newslot virtual + instance int32 modopt(int32) get_Prop () cil managed + { + ldarg.0 + ldfld int32 Base::'k__BackingField' + ret + } + + .method public hidebysig specialname newslot virtual + instance void set_Prop ( + int32 'value' + ) cil managed + { + ldarg.0 + ldarg.1 + stfld int32 Base::'k__BackingField' + ret + } + + .method public hidebysig specialname newslot virtual + instance void set_Prop ( + int32 modopt(int32) 'value' + ) cil managed + { + ret + } + + .method public hidebysig specialname rtspecialname + instance void .ctor () cil managed + { + .custom instance void [mscorlib]System.ObsoleteAttribute::.ctor(string, bool) = ( + 01 00 5f 43 6f 6e 73 74 72 75 63 74 6f 72 73 20 + 6f 66 20 74 79 70 65 73 20 77 69 74 68 20 72 65 + 71 75 69 72 65 64 20 6d 65 6d 62 65 72 73 20 61 + 72 65 20 6e 6f 74 20 73 75 70 70 6f 72 74 65 64 + 20 69 6e 20 74 68 69 73 20 76 65 72 73 69 6f 6e + 20 6f 66 20 79 6f 75 72 20 63 6f 6d 70 69 6c 65 + 72 2e 01 00 00 + ) + .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerFeatureRequiredAttribute::.ctor(string) = ( + 01 00 0f 52 65 71 75 69 72 65 64 4d 65 6d 62 65 + 72 73 00 00 + ) + + ldarg.0 + call instance void [mscorlib]System.Object::.ctor() + nop + ret + } + + .property instance int32 modopt(int32) Prop() + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .get instance int32 modopt(int32) Base::get_Prop() + .set instance void Base::set_Prop(int32 modopt(int32)) + } + + .property instance int32 Prop() + { + .get instance int32 Base::get_Prop() + .set instance void Base::set_Prop(int32) + } + +} // end of class Base + +.class public auto ansi beforefieldinit Derived + extends Base +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .field private int32 'k__BackingField' + + .method public hidebysig specialname virtual + instance int32 get_Prop () cil managed + { + ldarg.0 + ldfld int32 Derived::'k__BackingField' + ret + } + + .method public hidebysig specialname virtual + instance void set_Prop ( + int32 'value' + ) cil managed + { + ldarg.0 + ldarg.1 + stfld int32 Derived::'k__BackingField' + ret + } + + .method public hidebysig specialname rtspecialname + instance void .ctor () cil managed + { + ldarg.0 + call instance void Base::.ctor() + nop + ret + } + + .property instance int32 Prop() + { + .get instance int32 Derived::get_Prop() + .set instance void Derived::set_Prop(int32) + } + +}" + + Dim ilRef = CompileIL(il) + + Dim comp = CreateCompilation(" +Module M + Sub Main() + Dim d1 = New Derived() + End Sub +End Module", {ilRef}, targetFramework:=TargetFramework.Net70) + + comp.AssertTheseDiagnostics( +BC37323: The required members list for 'Derived' is malformed and cannot be interpreted. + Dim d1 = New Derived() + ~~~~~~~~~~~~~ + ) + End Sub + + + Public Sub CoClassWithRequiredMembers_NoneSet() + Dim cComp = CreateCSharpCompilationWithRequiredMembers(" +using System; +using System.Runtime.InteropServices; + +[ComImport, Guid(""00020810-0000-0000-C000-000000000046"")] +[CoClass(typeof(C))] +public interface I +{ +} + +public class C : I +{ + public required int P { get; set; } +} +") + Dim comp = CreateCompilation(" +Module M + Sub Main() + Dim i = New I() + End Sub +End Module", {cComp.EmitToImageReference()}) + + comp.AssertTheseDiagnostics( +BC37321: Required member 'Public Overloads Property P As Integer' must be set in the object initializer or attribute arguments. + Dim i = New I() + ~ + ) + End Sub + + + Public Sub CoClassWithRequiredMembers_AllSet() + Dim cComp = CreateCSharpCompilationWithRequiredMembers(" +using System; +using System.Runtime.InteropServices; + +[ComImport, Guid(""00020810-0000-0000-C000-000000000046"")] +[CoClass(typeof(C))] +public interface I +{ + public int P { get; set; } +} + +public class C : I +{ + public required int P { get; set; } +} +") + Dim comp = CreateCompilation(" +Module M + Sub Main() + Dim i = New I() With { .P = 1 } + End Sub +End Module", {cComp.EmitToImageReference()}) + + comp.AssertTheseDiagnostics( +BC37321: Required member 'Public Overloads Property P As Integer' must be set in the object initializer or attribute arguments. + Dim i = New I() With { .P = 1 } + ~ + ) + End Sub + + Public Function GetAttributeDefinition(hasSetsRequiredMembers As Boolean) As String + Return $" +using System; +public class AttrAttribute : Attribute +{{ + {If(hasSetsRequiredMembers, "[SetsRequiredMembers]", "")} + public AttrAttribute() {{}} + + public required int P {{ get; set; }} +}} +" + End Function + + + Public Sub RequiredMemberInAttribute_NoneSet() + Dim cComp = CreateCSharpCompilationWithRequiredMembers(GetAttributeDefinition(hasSetsRequiredMembers:=False)) + + Dim vbCode = $" + +Class C +End Class" + + Dim comp = CreateCompilation(vbCode, {cComp.EmitToImageReference()}) + comp.AssertTheseDiagnostics( + ~~~~ +]]>) + End Sub + + + Public Sub RequiredMemberInAttribute_AllSet() + Dim cComp = CreateCSharpCompilationWithRequiredMembers(GetAttributeDefinition(hasSetsRequiredMembers:=False)) + + Dim vbCode = $" + +Class C +End Class" + + Dim comp = CreateCompilation(vbCode, {cComp.EmitToImageReference()}) + comp.AssertNoDiagnostics() + End Sub + + + Public Sub PublicAPITests() + Dim cComp = CreateCSharpCompilationWithRequiredMembers(GetCDefinition(hasSetsRequiredMembers:=False)) + + Dim vbComp = CreateCompilation("", {cComp.EmitToImageReference()}) + + Dim c = vbComp.GetTypeByMetadataName("C") + Assert.False(c.HasRequiredMembersError) + Dim prop = c.GetMember(Of PropertySymbol)("Prop") + Dim field = c.GetMember(Of FieldSymbol)("Field") + + AssertEx.Equal(Of Symbol)({field, prop}, From kvp In c.AllRequiredMembers + Order By kvp.Key + Select kvp.Value) + + Assert.True(prop.IsRequired) + Assert.True(field.IsRequired) + End Sub + + + + + Public Sub GenericConstrainedToNew_Forbidden(typeKind As String) + Dim cComp = CreateCSharpCompilationWithRequiredMembers(GetCDefinition(hasSetsRequiredMembers:=False, typeKind)) + + Dim vbCode = " +Module M + Sub Main() + Generic(Of C)() + End Sub + + Sub Generic(Of T As New)() + End Sub +End Module" + + Dim comp = CreateCompilation(vbCode, {cComp.EmitToImageReference()}) + comp.AssertTheseDiagnostics( +BC37324: 'C' cannot satisfy the 'New' constraint on parameter 'T' in the generic type or or method 'Public Sub Generic(Of T As New)()' because 'C' has required members. + Generic(Of C)() + ~~~~~~~~~~~~~ + ) + End Sub + + + + + Public Sub GenericConstrainedToNew_Forbidden_HasRequiredMembersError(typeKind As String) + ' Equivalent to + ' public class Base + ' { + ' public required int P { get; set; } + ' } + ' public class Derived + ' { + ' public new required int P { get; set; } + ' public Derived() {} + ' } + Dim il = " +.class public auto ansi Base + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .field private int32 _P + + .method public specialname rtspecialname + instance void .ctor () cil managed + { + ldarg.0 + call instance void [mscorlib]System.Object::.ctor() + ret + } + + .method public specialname + instance int32 get_P () cil managed + { + IL_0000: ldarg.0 + IL_0001: ldfld int32 Base::_P + IL_0006: br.s IL_0008 + + IL_0008: ret + } + + .method public specialname + instance void set_P ( + int32 AutoPropertyValue + ) cil managed + { + ldarg.0 + ldarg.1 + stfld int32 Base::_P + ret + } + + .property instance int32 P() + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .get instance int32 Base::get_P() + .set instance void Base::set_P(int32) + } +} + +.class public auto ansi Derived + extends Base +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .field private int32 _P + + .method public specialname + instance int32 get_P () cil managed + { + IL_0000: ldarg.0 + IL_0001: ldfld int32 Derived::_P + IL_0006: br.s IL_0008 + + IL_0008: ret + } + + .method public specialname + instance void set_P ( + int32 AutoPropertyValue + ) cil managed + { + ldarg.0 + ldarg.1 + stfld int32 Derived::_P + ret + } + + .method public specialname rtspecialname + instance void .ctor () cil managed + { + nop + ldarg.0 + call instance void Base::.ctor() + ret + } + + .property instance int32 P() + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .get instance int32 Derived::get_P() + .set instance void Derived::set_P(int32) + } +}" + + Dim ilRef = CompileIL(il) + + Dim vbCode = " +Module M + Sub Main() + Generic(Of Derived)() + End Sub + + Sub Generic(Of T As New)() + End Sub +End Module" + + Dim comp = CreateCompilation(vbCode, {ilRef}) + comp.AssertTheseDiagnostics( +BC37324: 'Derived' cannot satisfy the 'New' constraint on parameter 'T' in the generic type or or method 'Public Sub Generic(Of T As New)()' because 'Derived' has required members. + Generic(Of Derived)() + ~~~~~~~~~~~~~~~~~~~ + ) + End Sub + + + + + Public Sub GenericConstrainedToNew_HasSetsRequiredMembers_Allowed(typeKind As String) + Dim cComp = CreateCSharpCompilationWithRequiredMembers(GetCDefinition(hasSetsRequiredMembers:=True, typeKind)) + + Dim vbCode = " +Module M + Sub Main() + Generic(Of C)() + End Sub + + Sub Generic(Of T As New)() + End Sub +End Module" + + Dim comp = CreateCompilation(vbCode, {cComp.EmitToImageReference()}) + comp.AssertNoDiagnostics() + End Sub + + + Public Sub GenericSubstitution_NoneSet() + Dim cDef = " +public class C +{ + public required T Prop { get; set; } + public required T Field; +}" + + Dim cComp = CreateCSharpCompilationWithRequiredMembers(cDef) + + Dim vbCode = " +Module M + Sub Main() + Dim c = New C(Of Integer)() + End Sub +End Module" + + Dim comp = CreateCompilation(vbCode, {cComp.EmitToImageReference()}) + comp.AssertTheseDiagnostics( +BC37321: Required member 'Public Field As Integer' must be set in the object initializer or attribute arguments. + Dim c = New C(Of Integer)() + ~~~~~~~~~~~~~ +BC37321: Required member 'Public Overloads Property Prop As Integer' must be set in the object initializer or attribute arguments. + Dim c = New C(Of Integer)() + ~~~~~~~~~~~~~ + ) + End Sub + + + Public Sub GenericSubstitution_AllSet() + Dim cDef = " +public class C +{ + public required T Prop { get; set; } + public required T Field; +}" + + Dim cComp = CreateCSharpCompilationWithRequiredMembers(cDef) + + Dim vbCode = " +Module M + Sub Main() + Dim c = New C(Of Integer)() With { .Prop = 1, .Field = 2 } + End Sub +End Module" + + Dim comp = CreateCompilation(vbCode, {cComp.EmitToImageReference()}) + comp.AssertNoDiagnostics() + End Sub + + + Public Sub GenericSubstitution_Unbound() + Dim cDef = " +public class C +{ + public required T Prop { get; set; } + public required T Field; +}" + + Dim cComp = CreateCSharpCompilationWithRequiredMembers(cDef) + + Dim vbCode = " +Module M + Sub Main() + Dim c = New C(Of)() + End Sub +End Module" + + Dim comp = CreateCompilation(vbCode, {cComp.EmitToImageReference()}) + comp.AssertTheseDiagnostics( +BC37321: Required member 'Public Field As ?' must be set in the object initializer or attribute arguments. + Dim c = New C(Of)() + ~~~~~ +BC37321: Required member 'Public Overloads Property Prop As ?' must be set in the object initializer or attribute arguments. + Dim c = New C(Of)() + ~~~~~ +BC30182: Type expected. + Dim c = New C(Of)() + ~ + ) + + Dim c = comp.GetTypeByMetadataName("C`1") + Dim u_c = c.ConstructUnboundGenericType() + Assert.False(u_c.HasAnyDeclaredRequiredMembers) + Assert.Empty(u_c.AllRequiredMembers) + End Sub + + + Public Sub GenericSubstitution_Inheritance_NoneSet() + Dim cDef = " +public class C +{ + public required T Prop { get; set; } + public required T Field; +} +public class D : C {}" + + Dim cComp = CreateCSharpCompilationWithRequiredMembers(cDef) + + Dim vbCode = " +Module M + Sub Main() + Dim d = New D() + End Sub +End Module" + + Dim comp = CreateCompilation(vbCode, {cComp.EmitToImageReference()}) + comp.AssertTheseDiagnostics( +BC37321: Required member 'Public Field As Integer' must be set in the object initializer or attribute arguments. + Dim d = New D() + ~ +BC37321: Required member 'Public Overloads Property Prop As Integer' must be set in the object initializer or attribute arguments. + Dim d = New D() + ~ + ) + End Sub + + + Public Sub GenericSubstitution_InheritanceAndOverride_NoneSet() + Dim cDef = " +public class C +{ + public virtual required T Prop { get; set; } +} +public class D : C +{ + public override required int Prop { get; set; } +}" + + Dim cComp = CreateCSharpCompilationWithRequiredMembers(cDef) + + Dim vbCode = " +Module M + Sub Main() + Dim d = New D() + End Sub +End Module" + + Dim comp = CreateCompilation(vbCode, {cComp.EmitToImageReference()}) + comp.AssertTheseDiagnostics( +BC37321: Required member 'Public Overrides Property Prop As Integer' must be set in the object initializer or attribute arguments. + Dim d = New D() + ~ + ) + End Sub + + + Public Sub ProtectedParameterlessConstructorInStruct() + ' Equivalent to + ' public struct S + ' { + ' protected S() {} + ' public required int Prop { get; set; } + ' } + Dim il = " +.class public sequential ansi sealed beforefieldinit S + extends [mscorlib]System.ValueType +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .field private int32 f + + .method family hidebysig specialname rtspecialname + instance void .ctor () cil managed + { + .custom instance void [mscorlib]System.ObsoleteAttribute::.ctor(string, bool) = ( + 01 00 5f 43 6f 6e 73 74 72 75 63 74 6f 72 73 20 + 6f 66 20 74 79 70 65 73 20 77 69 74 68 20 72 65 + 71 75 69 72 65 64 20 6d 65 6d 62 65 72 73 20 61 + 72 65 20 6e 6f 74 20 73 75 70 70 6f 72 74 65 64 + 20 69 6e 20 74 68 69 73 20 76 65 72 73 69 6f 6e + 20 6f 66 20 79 6f 75 72 20 63 6f 6d 70 69 6c 65 + 72 2e 01 00 00 + ) + .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerFeatureRequiredAttribute::.ctor(string) = ( + 01 00 0f 52 65 71 75 69 72 65 64 4d 65 6d 62 65 + 72 73 00 00 + ) + ret + } + + .method public hidebysig specialname + instance int32 get_Prop () cil managed + { + ldarg.0 + ldfld int32 S::f + ret + } + + .method public hidebysig specialname + instance void set_Prop ( + int32 'value' + ) cil managed + { + ldarg.0 + ldarg.1 + stfld int32 S::f + ret + } + + .property instance int32 Prop() + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .get instance int32 S::get_Prop() + .set instance void S::set_Prop(int32) + } +} +" + + Dim ilAssembly = CompileIL(il) + + Dim comp = CreateCompilation(" +Module M + Sub Main() + Dim s = New S() + End Sub +End Module +", {ilAssembly}, targetFramework:=TargetFramework.Net70) + + comp.AssertTheseDiagnostics( +BC37321: Required member 'Public Overloads Property Prop As Integer' must be set in the object initializer or attribute arguments. + Dim s = New S() + ~ + ) + End Sub + + + Public Sub RequiredMemberAttributeDisallowedInSource() + Dim comp = CreateCompilation(" +Imports System.Runtime.CompilerServices + ' 1 +Public Class C + ' 2 + Public Property P As Integer + + ' 3 + Public F As Integer +End Class", targetFramework:=TargetFramework.Net70) + + comp.AssertTheseDiagnostics( ' 1 + ~~~~~~~~~~~~~~ +BC37325: 'System.Runtime.CompilerServices.RequiredMemberAttribute' is reserved for compiler usage only. + ' 2 + ~~~~~~~~~~~~~~ +BC37325: 'System.Runtime.CompilerServices.RequiredMemberAttribute' is reserved for compiler usage only. + ' 3 + ~~~~~~~~~~~~~~]]>) + End Sub + + + Public Sub TupleWithRequiredFields() + Dim csharpComp = CreateCSharpCompilation(" +namespace System +{ + public struct ValueTuple + { + public required T1 Item1; + public required T2 Item2; + public required int AnotherField; + public required int Property { get; set; } + + public ValueTuple(T1 item1, T2 item2) + { + this.Item1 = item1; + this.Item2 = item2; + } + + public static bool operator ==(ValueTuple t1, ValueTuple t2) + => throw null; + public static bool operator !=(ValueTuple t1, ValueTuple t2) + => throw null; + + public override bool Equals(object o) + => throw null; + public override int GetHashCode() + => throw null; + } + + public struct ValueTuple where TRest : struct + { + public T1 Item1; + public T2 Item2; + public T3 Item3; + public T4 Item4; + public T5 Item5; + public T6 Item6; + public T7 Item7; + public required TRest Rest; + + public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest) + { + this.Item1 = item1; + this.Item2 = item2; + this.Item3 = item3; + this.Item4 = item4; + this.Item5 = item5; + this.Item6 = item6; + this.Item7 = item7; + this.Rest = rest; + } + + public static bool operator ==(ValueTuple t1, ValueTuple t2) + => throw null; + public static bool operator !=(ValueTuple t1, ValueTuple t2) + => throw null; + + public override bool Equals(object o) + => throw null; + public override int GetHashCode() + => throw null; + } + + namespace Runtime.CompilerServices + { + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Field | AttributeTargets.Property, Inherited = false, AllowMultiple = false)] + public sealed class RequiredMemberAttribute : Attribute + { + public RequiredMemberAttribute() + { + } + } + + [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)] + public sealed class CompilerFeatureRequiredAttribute : Attribute + { + public CompilerFeatureRequiredAttribute(string featureName) + { + FeatureName = featureName; + } + public string FeatureName { get; } + public bool IsOptional { get; set; } + } + } + namespace Diagnostics.CodeAnalysis + { + [AttributeUsage(AttributeTargets.Constructor, Inherited = false, AllowMultiple = false)] + public sealed class SetsRequiredMembersAttribute : Attribute + { + public SetsRequiredMembersAttribute() + { + } + } + } +} +", referencedAssemblies:=Basic.Reference.Assemblies.Net461.All) + Dim csharpCompReference As MetadataReference = csharpComp.EmitToImageReference() + + ' Using Net461 to get a framework without ValueTuple + + Dim comp = CreateCompilation(" +Class C + Sub Main() + Dim t1 = New (Integer, Integer)(1, 2) + Dim t2 = new System.ValueTuple(Of Integer, Integer)(3, 4) + Dim t3 = new System.ValueTuple(Of Integer, Integer)() + Dim t4 As (Integer, Integer) = Nothing + Dim t5 As System.ValueTuple(of integer, integer) = Nothing + Dim t6 = new System.ValueTuple(Of Integer, Integer)() With { + .Item1 = 1, + .Item2 = 2, + .[Property] = 3, + .AnotherField = 4 + } + End Sub +End Class", {csharpCompReference}, targetFramework:=TargetFramework.Mscorlib461) + + comp.AssertTheseDiagnostics( +BC37280: 'New' cannot be used with tuple type. Use a tuple literal expression instead. + Dim t1 = New (Integer, Integer)(1, 2) + ~~~~~~~~~~~~~~~~~~ +BC37321: Required member 'Public AnotherField As Integer' must be set in the object initializer or attribute arguments. + Dim t1 = New (Integer, Integer)(1, 2) + ~~~~~~~~~~~~~~~~~~ +BC37321: Required member 'Public Item1 As Integer' must be set in the object initializer or attribute arguments. + Dim t1 = New (Integer, Integer)(1, 2) + ~~~~~~~~~~~~~~~~~~ +BC37321: Required member 'Public Item2 As Integer' must be set in the object initializer or attribute arguments. + Dim t1 = New (Integer, Integer)(1, 2) + ~~~~~~~~~~~~~~~~~~ +BC37321: Required member 'Public Overloads Property [Property] As Integer' must be set in the object initializer or attribute arguments. + Dim t1 = New (Integer, Integer)(1, 2) + ~~~~~~~~~~~~~~~~~~ +BC37321: Required member 'Public AnotherField As Integer' must be set in the object initializer or attribute arguments. + Dim t2 = new System.ValueTuple(Of Integer, Integer)(3, 4) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +BC37321: Required member 'Public Item1 As Integer' must be set in the object initializer or attribute arguments. + Dim t2 = new System.ValueTuple(Of Integer, Integer)(3, 4) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +BC37321: Required member 'Public Item2 As Integer' must be set in the object initializer or attribute arguments. + Dim t2 = new System.ValueTuple(Of Integer, Integer)(3, 4) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +BC37321: Required member 'Public Overloads Property [Property] As Integer' must be set in the object initializer or attribute arguments. + Dim t2 = new System.ValueTuple(Of Integer, Integer)(3, 4) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +BC37321: Required member 'Public AnotherField As Integer' must be set in the object initializer or attribute arguments. + Dim t3 = new System.ValueTuple(Of Integer, Integer)() + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +BC37321: Required member 'Public Item1 As Integer' must be set in the object initializer or attribute arguments. + Dim t3 = new System.ValueTuple(Of Integer, Integer)() + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +BC37321: Required member 'Public Item2 As Integer' must be set in the object initializer or attribute arguments. + Dim t3 = new System.ValueTuple(Of Integer, Integer)() + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +BC37321: Required member 'Public Overloads Property [Property] As Integer' must be set in the object initializer or attribute arguments. + Dim t3 = new System.ValueTuple(Of Integer, Integer)() + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ) + + comp = CreateCompilation(" +Class C + Sub Main() + Dim t1 = (1, 2) + Dim t2 As (Integer, Integer) = (3, Nothing) + Dim t3 = (1, 2, 3, 4, 5, 6, 7, 8, 9) + End Sub +End Class +", {csharpCompReference}, targetFramework:=TargetFramework.Mscorlib461) + + comp.AssertTheseEmitDiagnostics( +BC37321: Required member 'Public AnotherField As Integer' must be set in the object initializer or attribute arguments. + Dim t1 = (1, 2) + ~~~~~~ +BC37321: Required member 'Public Item1 As Integer' must be set in the object initializer or attribute arguments. + Dim t1 = (1, 2) + ~~~~~~ +BC37321: Required member 'Public Item2 As Integer' must be set in the object initializer or attribute arguments. + Dim t1 = (1, 2) + ~~~~~~ +BC37321: Required member 'Public Overloads Property [Property] As Integer' must be set in the object initializer or attribute arguments. + Dim t1 = (1, 2) + ~~~~~~ +BC37321: Required member 'Public AnotherField As Integer' must be set in the object initializer or attribute arguments. + Dim t2 As (Integer, Integer) = (3, Nothing) + ~~~~~~~~~~~~ +BC37321: Required member 'Public Item1 As Integer' must be set in the object initializer or attribute arguments. + Dim t2 As (Integer, Integer) = (3, Nothing) + ~~~~~~~~~~~~ +BC37321: Required member 'Public Item2 As Integer' must be set in the object initializer or attribute arguments. + Dim t2 As (Integer, Integer) = (3, Nothing) + ~~~~~~~~~~~~ +BC37321: Required member 'Public Overloads Property [Property] As Integer' must be set in the object initializer or attribute arguments. + Dim t2 As (Integer, Integer) = (3, Nothing) + ~~~~~~~~~~~~ +BC37321: Required member 'Public AnotherField As Integer' must be set in the object initializer or attribute arguments. + Dim t3 = (1, 2, 3, 4, 5, 6, 7, 8, 9) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +BC37321: Required member 'Public Item1 As Integer' must be set in the object initializer or attribute arguments. + Dim t3 = (1, 2, 3, 4, 5, 6, 7, 8, 9) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +BC37321: Required member 'Public Item2 As Integer' must be set in the object initializer or attribute arguments. + Dim t3 = (1, 2, 3, 4, 5, 6, 7, 8, 9) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +BC37321: Required member 'Public Overloads Property [Property] As Integer' must be set in the object initializer or attribute arguments. + Dim t3 = (1, 2, 3, 4, 5, 6, 7, 8, 9) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +BC37321: Required member 'Public Rest As TRest' must be set in the object initializer or attribute arguments. + Dim t3 = (1, 2, 3, 4, 5, 6, 7, 8, 9) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ) + + Dim tree = comp.SyntaxTrees(0) + Dim tuple = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().First() + Dim model = comp.GetSemanticModel(tree) + Dim tupleType = DirectCast(model.GetTypeInfo(tuple).Type, TupleTypeSymbol) + + Assert.True(tupleType.HasAnyDeclaredRequiredMembers) + AssertEx.Equal( + {"AnotherField", "Item1", "Item2", "Property"}, + tupleType.AllRequiredMembers.Select(Function(kvp) kvp.Key).OrderBy(StringComparer.InvariantCulture)) + Assert.All(tupleType.TupleElements, Function(field) field.IsRequired) + Assert.True(tupleType.GetMember(Of PropertySymbol)("Property").IsRequired) + End Sub + + + Public Sub TupleWithRequiredFields_SetsRequiredMembers() + Dim csharpComp = CreateCSharpCompilation(" +namespace System +{ + public struct ValueTuple + { + public required T1 Item1; + public required T2 Item2; + public required int AnotherField; + public required int Property { get; set; } + + [System.Diagnostics.CodeAnalysis.SetsRequiredMembers] + public ValueTuple(T1 item1, T2 item2) + { + this.Item1 = item1; + this.Item2 = item2; + } + + public static bool operator ==(ValueTuple t1, ValueTuple t2) + => throw null; + public static bool operator !=(ValueTuple t1, ValueTuple t2) + => throw null; + + public override bool Equals(object o) + => throw null; + public override int GetHashCode() + => throw null; + } + + namespace Runtime.CompilerServices + { + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Field | AttributeTargets.Property, Inherited = false, AllowMultiple = false)] + public sealed class RequiredMemberAttribute : Attribute + { + public RequiredMemberAttribute() + { + } + } + + [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)] + public sealed class CompilerFeatureRequiredAttribute : Attribute + { + public CompilerFeatureRequiredAttribute(string featureName) + { + FeatureName = featureName; + } + public string FeatureName { get; } + public bool IsOptional { get; set; } + } + } + namespace Diagnostics.CodeAnalysis + { + [AttributeUsage(AttributeTargets.Constructor, Inherited = false, AllowMultiple = false)] + public sealed class SetsRequiredMembersAttribute : Attribute + { + public SetsRequiredMembersAttribute() + { + } + } + } +} +", referencedAssemblies:=Basic.Reference.Assemblies.Net461.All) + + ' Using Net461 to get a framework without ValueTuple + + Dim comp = CreateCompilation(" +Class C + Sub Main() + Dim t1 = (1, 2) + Dim t2 As (Integer, Integer) = (3, Nothing) + Dim t3 = New System.ValueTuple(Of Integer, Integer)(4, 5) + End Sub +End Class", {csharpComp.EmitToImageReference()}, targetFramework:=TargetFramework.Mscorlib461) + + CompileAndVerify(comp).VerifyDiagnostics() + + Dim tree = comp.SyntaxTrees(0) + Dim tuple = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().First() + Dim model = comp.GetSemanticModel(tree) + Dim tupleType = DirectCast(model.GetTypeInfo(tuple).Type, TupleTypeSymbol) + + Assert.True(tupleType.HasAnyDeclaredRequiredMembers) + AssertEx.Equal( + {"AnotherField", "Item1", "Item2", "Property"}, + tupleType.AllRequiredMembers.Select(Function(kvp) kvp.Key).OrderBy(StringComparer.InvariantCulture)) + Assert.All(tupleType.TupleElements, Function(field) field.IsRequired) + Assert.True(tupleType.GetMember(Of PropertySymbol)("Property").IsRequired) + End Sub + + + Public Sub IndexedPropertyCannotBeRequired() + ' Equivalent to + ' + ' Public Class C + ' + ' Public Property P1(x As Integer) As Integer + ' Get + ' Return 0 + ' End Get + ' Set + ' End Set + ' End Property + ' End Class + Dim il = " +.class public auto ansi C + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .method public specialname rtspecialname + instance void .ctor () cil managed + { + ldarg.0 + call instance void [mscorlib]System.Object::.ctor() + ret + } + + .method public specialname + instance int32 get_P1 ( + int32 x + ) cil managed + { + ldc.i4.0 + ret + } + + .method public specialname + instance void set_P1 ( + int32 x, + int32 Value + ) cil managed + { + ret + } + + .property instance int32 P1( + int32 x + ) + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .get instance int32 C::get_P1(int32) + .set instance void C::set_P1(int32, int32) + } + +}" + + Dim ilRef = CompileIL(il) + + Dim comp = CreateCompilation(" +Module M + Sub Main() + Dim c = New C() + End Sub +End Module", {ilRef}, targetFramework:=TargetFramework.Net70) + + comp.AssertTheseDiagnostics( +BC37323: The required members list for 'C' is malformed and cannot be interpreted. + Dim c = New C() + ~~~~~~~ + ) + End Sub + + + Public Sub IndexedPropertyOverload_NoneSet() + ' Equivalent to + ' + ' Public Class C + ' + ' Public Overloads Property P1 As Integer + ' Public Overloads Property P1(x As Integer) As Integer + ' Get + ' Return 0 + ' End Get + ' Set + ' End Set + ' End Property + ' End Class + Dim il = " +.class public auto ansi C + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .field private int32 _P1 + + .method public specialname rtspecialname + instance void .ctor () cil managed + { + ldarg.0 + call instance void [mscorlib]System.Object::.ctor() + ret + } + + .method public hidebysig specialname + instance int32 get_P1 ( + int32 x + ) cil managed + { + ldc.i4.0 + ret + } + + .method public hidebysig specialname + instance void set_P1 ( + int32 x, + int32 Value + ) cil managed + { + ret + } + + .method public hidebysig specialname + instance int32 get_P1 () cil managed + { + ldarg.0 + ldfld int32 C::_P1 + ret + } + + .method public hidebysig specialname + instance void set_P1 ( + int32 AutoPropertyValue + ) cil managed + { + ldarg.0 + ldarg.1 + stfld int32 C::_P1 + ret + } + + .property instance int32 P1( + int32 x + ) + { + .get instance int32 C::get_P1(int32) + .set instance void C::set_P1(int32, int32) + } + .property instance int32 P1() + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .get instance int32 C::get_P1() + .set instance void C::set_P1(int32) + } +}" + + Dim ilRef = CompileIL(il) + + Dim comp = CreateCompilation(" +Module M + Sub Main() + Dim c = New C() + End Sub +End Module", {ilRef}, targetFramework:=TargetFramework.Net70) + + comp.AssertTheseDiagnostics( +BC37321: Required member 'Public Overloads Property P1 As Integer' must be set in the object initializer or attribute arguments. + Dim c = New C() + ~ + ) + End Sub + + + Public Sub IndexedPropertyOverload_AllSet() + ' Equivalent to + ' + ' Public Class C + ' + ' Public Overloads Property P1 As Integer + ' Public Overloads Property P1(x As Integer) As Integer + ' Get + ' Return 0 + ' End Get + ' Set + ' End Set + ' End Property + ' End Class + Dim il = " +.class public auto ansi C + extends [mscorlib]System.Object +{ + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .field private int32 _P1 + + .method public specialname rtspecialname + instance void .ctor () cil managed + { + ldarg.0 + call instance void [mscorlib]System.Object::.ctor() + ret + } + + .method public hidebysig specialname + instance int32 get_P1 ( + int32 x + ) cil managed + { + ldc.i4.0 + ret + } + + .method public hidebysig specialname + instance void set_P1 ( + int32 x, + int32 Value + ) cil managed + { + ret + } + + .method public hidebysig specialname + instance int32 get_P1 () cil managed + { + ldarg.0 + ldfld int32 C::_P1 + ret + } + + .method public hidebysig specialname + instance void set_P1 ( + int32 AutoPropertyValue + ) cil managed + { + ldarg.0 + ldarg.1 + stfld int32 C::_P1 + ret + } + + .property instance int32 P1( + int32 x + ) + { + .get instance int32 C::get_P1(int32) + .set instance void C::set_P1(int32, int32) + } + .property instance int32 P1() + { + .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredMemberAttribute::.ctor() = ( + 01 00 00 00 + ) + .get instance int32 C::get_P1() + .set instance void C::set_P1(int32) + } +}" + + Dim ilRef = CompileIL(il) + + Dim comp = CreateCompilation(" +Module M + Sub Main() + Dim c = New C() With { .P1 = 1 } + End Sub +End Module", {ilRef}, targetFramework:=TargetFramework.Net70) + + comp.AssertNoDiagnostics() + End Sub + + + Public Sub IndexedProperty_OverloadInDerivedType() + Dim csharpComp = CreateCSharpCompilationWithRequiredMembers(" +public class C1 +{ + public required int P1 {get;set;} +} + +public class C2 : C1 +{ + [System.Runtime.CompilerServices.IndexerNameAttribute(nameof(P1))] + public int this[int x] => x; +}") + + Dim comp = CreateCompilation(" +Module M + Sub Main() + Dim c = New C2() + Dim c2 = New C2() With { .P1 = 1 } + End Sub +End Module", {csharpComp.EmitToImageReference()}, targetFramework:=TargetFramework.Net70) + + comp.AssertTheseDiagnostics( +BC37321: Required member 'Public Overloads Property P1 As Integer' must be set in the object initializer or attribute arguments. + Dim c = New C2() + ~~ + ) + End Sub + End Class +End Namespace diff --git a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/DisplayClassVariable.vb b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/DisplayClassVariable.vb index 0f30b7d48cac7..ddc3cb72554d3 100644 --- a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/DisplayClassVariable.vb +++ b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/DisplayClassVariable.vb @@ -224,6 +224,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator Throw ExceptionUtilities.Unreachable End Get End Property + + Public Overrides ReadOnly Property IsRequired As Boolean + Get + Return False + End Get + End Property End Class End Class diff --git a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/EEMethodSymbol.vb b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/EEMethodSymbol.vb index 3b9b000879921..cdeb38f621535 100644 --- a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/EEMethodSymbol.vb +++ b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/EEMethodSymbol.vb @@ -625,6 +625,11 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator End Get End Property + Friend Overrides ReadOnly Property HasSetsRequiredMembers As Boolean + Get + Return False + End Get + End Property End Class End Namespace diff --git a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/EENamedTypeSymbol.vb b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/EENamedTypeSymbol.vb index ed60b67c8e7c5..50c4d88a84758 100644 --- a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/EENamedTypeSymbol.vb +++ b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/EENamedTypeSymbol.vb @@ -348,6 +348,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator End Get End Property + Friend Overrides ReadOnly Property HasAnyDeclaredRequiredMembers As Boolean + Get + Return False + End Get + End Property + Friend Overrides Sub GenerateDeclarationErrors(cancellationToken As CancellationToken) Throw ExceptionUtilities.Unreachable End Sub